xref: /sqlite-3.40.0/src/select.c (revision 6f8a503d)
1cce7d176Sdrh /*
2b19a2bc6Sdrh ** 2001 September 15
3cce7d176Sdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
6cce7d176Sdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
10cce7d176Sdrh **
11cce7d176Sdrh *************************************************************************
12cce7d176Sdrh ** This file contains C code routines that are called by the parser
13b19a2bc6Sdrh ** to handle SELECT statements in SQLite.
14cce7d176Sdrh **
15*6f8a503dSdanielk1977 ** $Id: select.c,v 1.163 2004/05/10 10:34:49 danielk1977 Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19315555caSdrh 
20cce7d176Sdrh /*
219bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that
229bb61fe7Sdrh ** structure.
23cce7d176Sdrh */
244adee20fSdanielk1977 Select *sqlite3SelectNew(
25daffd0e5Sdrh   ExprList *pEList,     /* which columns to include in the result */
26ad3cab52Sdrh   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
27daffd0e5Sdrh   Expr *pWhere,         /* the WHERE clause */
28daffd0e5Sdrh   ExprList *pGroupBy,   /* the GROUP BY clause */
29daffd0e5Sdrh   Expr *pHaving,        /* the HAVING clause */
30daffd0e5Sdrh   ExprList *pOrderBy,   /* the ORDER BY clause */
319bbca4c1Sdrh   int isDistinct,       /* true if the DISTINCT keyword is present */
329bbca4c1Sdrh   int nLimit,           /* LIMIT value.  -1 means not used */
33ef0cae50Sdrh   int nOffset           /* OFFSET value.  0 means no offset */
349bb61fe7Sdrh ){
359bb61fe7Sdrh   Select *pNew;
369bb61fe7Sdrh   pNew = sqliteMalloc( sizeof(*pNew) );
37daffd0e5Sdrh   if( pNew==0 ){
384adee20fSdanielk1977     sqlite3ExprListDelete(pEList);
394adee20fSdanielk1977     sqlite3SrcListDelete(pSrc);
404adee20fSdanielk1977     sqlite3ExprDelete(pWhere);
414adee20fSdanielk1977     sqlite3ExprListDelete(pGroupBy);
424adee20fSdanielk1977     sqlite3ExprDelete(pHaving);
434adee20fSdanielk1977     sqlite3ExprListDelete(pOrderBy);
44daffd0e5Sdrh   }else{
45b733d037Sdrh     if( pEList==0 ){
464adee20fSdanielk1977       pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0);
47b733d037Sdrh     }
489bb61fe7Sdrh     pNew->pEList = pEList;
499bb61fe7Sdrh     pNew->pSrc = pSrc;
509bb61fe7Sdrh     pNew->pWhere = pWhere;
519bb61fe7Sdrh     pNew->pGroupBy = pGroupBy;
529bb61fe7Sdrh     pNew->pHaving = pHaving;
539bb61fe7Sdrh     pNew->pOrderBy = pOrderBy;
549bb61fe7Sdrh     pNew->isDistinct = isDistinct;
5582c3d636Sdrh     pNew->op = TK_SELECT;
569bbca4c1Sdrh     pNew->nLimit = nLimit;
579bbca4c1Sdrh     pNew->nOffset = nOffset;
587b58daeaSdrh     pNew->iLimit = -1;
597b58daeaSdrh     pNew->iOffset = -1;
60daffd0e5Sdrh   }
619bb61fe7Sdrh   return pNew;
629bb61fe7Sdrh }
639bb61fe7Sdrh 
649bb61fe7Sdrh /*
6501f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
6601f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
6701f3f253Sdrh ** in terms of the following bit values:
6801f3f253Sdrh **
6901f3f253Sdrh **     JT_INNER
7001f3f253Sdrh **     JT_OUTER
7101f3f253Sdrh **     JT_NATURAL
7201f3f253Sdrh **     JT_LEFT
7301f3f253Sdrh **     JT_RIGHT
7401f3f253Sdrh **
7501f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
7601f3f253Sdrh **
7701f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
7801f3f253Sdrh ** a join type, but put an error in the pParse structure.
7901f3f253Sdrh */
804adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
8101f3f253Sdrh   int jointype = 0;
8201f3f253Sdrh   Token *apAll[3];
8301f3f253Sdrh   Token *p;
8401f3f253Sdrh   static struct {
8501f3f253Sdrh     const char *zKeyword;
8601f3f253Sdrh     int nChar;
8701f3f253Sdrh     int code;
8801f3f253Sdrh   } keywords[] = {
8901f3f253Sdrh     { "natural", 7, JT_NATURAL },
90195e6967Sdrh     { "left",    4, JT_LEFT|JT_OUTER },
91195e6967Sdrh     { "right",   5, JT_RIGHT|JT_OUTER },
92195e6967Sdrh     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
9301f3f253Sdrh     { "outer",   5, JT_OUTER },
9401f3f253Sdrh     { "inner",   5, JT_INNER },
9501f3f253Sdrh     { "cross",   5, JT_INNER },
9601f3f253Sdrh   };
9701f3f253Sdrh   int i, j;
9801f3f253Sdrh   apAll[0] = pA;
9901f3f253Sdrh   apAll[1] = pB;
10001f3f253Sdrh   apAll[2] = pC;
101195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
10201f3f253Sdrh     p = apAll[i];
10301f3f253Sdrh     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
10401f3f253Sdrh       if( p->n==keywords[j].nChar
1054adee20fSdanielk1977           && sqlite3StrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
10601f3f253Sdrh         jointype |= keywords[j].code;
10701f3f253Sdrh         break;
10801f3f253Sdrh       }
10901f3f253Sdrh     }
11001f3f253Sdrh     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
11101f3f253Sdrh       jointype |= JT_ERROR;
11201f3f253Sdrh       break;
11301f3f253Sdrh     }
11401f3f253Sdrh   }
115ad2d8307Sdrh   if(
116ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
117195e6967Sdrh      (jointype & JT_ERROR)!=0
118ad2d8307Sdrh   ){
11901f3f253Sdrh     static Token dummy = { 0, 0 };
12001f3f253Sdrh     char *zSp1 = " ", *zSp2 = " ";
12101f3f253Sdrh     if( pB==0 ){ pB = &dummy; zSp1 = 0; }
12201f3f253Sdrh     if( pC==0 ){ pC = &dummy; zSp2 = 0; }
1234adee20fSdanielk1977     sqlite3SetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
12401f3f253Sdrh        pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0);
12501f3f253Sdrh     pParse->nErr++;
12601f3f253Sdrh     jointype = JT_INNER;
127195e6967Sdrh   }else if( jointype & JT_RIGHT ){
1284adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
129da93d238Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported");
130195e6967Sdrh     jointype = JT_INNER;
13101f3f253Sdrh   }
13201f3f253Sdrh   return jointype;
13301f3f253Sdrh }
13401f3f253Sdrh 
13501f3f253Sdrh /*
136ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
137ad2d8307Sdrh ** is not contained in the table.
138ad2d8307Sdrh */
139ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
140ad2d8307Sdrh   int i;
141ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
1424adee20fSdanielk1977     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
143ad2d8307Sdrh   }
144ad2d8307Sdrh   return -1;
145ad2d8307Sdrh }
146ad2d8307Sdrh 
147ad2d8307Sdrh /*
148ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the
149ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2.
150ad2d8307Sdrh */
151ad2d8307Sdrh static void addWhereTerm(
152ad2d8307Sdrh   const char *zCol,        /* Name of the column */
153ad2d8307Sdrh   const Table *pTab1,      /* First table */
154ad2d8307Sdrh   const Table *pTab2,      /* Second table */
155ad2d8307Sdrh   Expr **ppExpr            /* Add the equality term to this expression */
156ad2d8307Sdrh ){
157ad2d8307Sdrh   Token dummy;
158ad2d8307Sdrh   Expr *pE1a, *pE1b, *pE1c;
159ad2d8307Sdrh   Expr *pE2a, *pE2b, *pE2c;
160ad2d8307Sdrh   Expr *pE;
161ad2d8307Sdrh 
162ad2d8307Sdrh   dummy.z = zCol;
163ad2d8307Sdrh   dummy.n = strlen(zCol);
1644b59ab5eSdrh   dummy.dyn = 0;
1654adee20fSdanielk1977   pE1a = sqlite3Expr(TK_ID, 0, 0, &dummy);
1664adee20fSdanielk1977   pE2a = sqlite3Expr(TK_ID, 0, 0, &dummy);
167ad2d8307Sdrh   dummy.z = pTab1->zName;
168ad2d8307Sdrh   dummy.n = strlen(dummy.z);
1694adee20fSdanielk1977   pE1b = sqlite3Expr(TK_ID, 0, 0, &dummy);
170ad2d8307Sdrh   dummy.z = pTab2->zName;
171ad2d8307Sdrh   dummy.n = strlen(dummy.z);
1724adee20fSdanielk1977   pE2b = sqlite3Expr(TK_ID, 0, 0, &dummy);
1734adee20fSdanielk1977   pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
1744adee20fSdanielk1977   pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
1754adee20fSdanielk1977   pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
1761f16230bSdrh   ExprSetProperty(pE, EP_FromJoin);
177ad2d8307Sdrh   if( *ppExpr ){
1784adee20fSdanielk1977     *ppExpr = sqlite3Expr(TK_AND, *ppExpr, pE, 0);
179ad2d8307Sdrh   }else{
180ad2d8307Sdrh     *ppExpr = pE;
181ad2d8307Sdrh   }
182ad2d8307Sdrh }
183ad2d8307Sdrh 
184ad2d8307Sdrh /*
1851f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
1861cc093c2Sdrh **
187e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
1881cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
1891f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
1901f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
1911f16230bSdrh ** WHERE clause during join processing but we need to remember that they
1921f16230bSdrh ** originated in the ON or USING clause.
1931cc093c2Sdrh */
1941cc093c2Sdrh static void setJoinExpr(Expr *p){
1951cc093c2Sdrh   while( p ){
1961f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
1971cc093c2Sdrh     setJoinExpr(p->pLeft);
1981cc093c2Sdrh     p = p->pRight;
1991cc093c2Sdrh   }
2001cc093c2Sdrh }
2011cc093c2Sdrh 
2021cc093c2Sdrh /*
203ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
204ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
205ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
206ad2d8307Sdrh **
207ad2d8307Sdrh ** This routine returns the number of errors encountered.
208ad2d8307Sdrh */
209ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
210ad2d8307Sdrh   SrcList *pSrc;
211ad2d8307Sdrh   int i, j;
212ad2d8307Sdrh   pSrc = p->pSrc;
213ad2d8307Sdrh   for(i=0; i<pSrc->nSrc-1; i++){
214ad2d8307Sdrh     struct SrcList_item *pTerm = &pSrc->a[i];
215ad2d8307Sdrh     struct SrcList_item *pOther = &pSrc->a[i+1];
216ad2d8307Sdrh 
217ad2d8307Sdrh     if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
218ad2d8307Sdrh 
219ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
220ad2d8307Sdrh     ** every column that the two tables have in common.
221ad2d8307Sdrh     */
222ad2d8307Sdrh     if( pTerm->jointype & JT_NATURAL ){
223ad2d8307Sdrh       Table *pTab;
224ad2d8307Sdrh       if( pTerm->pOn || pTerm->pUsing ){
2254adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
226ad2d8307Sdrh            "an ON or USING clause", 0);
227ad2d8307Sdrh         return 1;
228ad2d8307Sdrh       }
229ad2d8307Sdrh       pTab = pTerm->pTab;
230ad2d8307Sdrh       for(j=0; j<pTab->nCol; j++){
231ad2d8307Sdrh         if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
232ad2d8307Sdrh           addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
233ad2d8307Sdrh         }
234ad2d8307Sdrh       }
235ad2d8307Sdrh     }
236ad2d8307Sdrh 
237ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
238ad2d8307Sdrh     */
239ad2d8307Sdrh     if( pTerm->pOn && pTerm->pUsing ){
2404adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
241da93d238Sdrh         "clauses in the same join");
242ad2d8307Sdrh       return 1;
243ad2d8307Sdrh     }
244ad2d8307Sdrh 
245ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
246ad2d8307Sdrh     ** and AND operator.
247ad2d8307Sdrh     */
248ad2d8307Sdrh     if( pTerm->pOn ){
2491cc093c2Sdrh       setJoinExpr(pTerm->pOn);
250ad2d8307Sdrh       if( p->pWhere==0 ){
251ad2d8307Sdrh         p->pWhere = pTerm->pOn;
252ad2d8307Sdrh       }else{
2534adee20fSdanielk1977         p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pTerm->pOn, 0);
254ad2d8307Sdrh       }
255ad2d8307Sdrh       pTerm->pOn = 0;
256ad2d8307Sdrh     }
257ad2d8307Sdrh 
258ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
259ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
260ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
261ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
262ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
263ad2d8307Sdrh     ** not contained in both tables to be joined.
264ad2d8307Sdrh     */
265ad2d8307Sdrh     if( pTerm->pUsing ){
266ad2d8307Sdrh       IdList *pList;
267ad2d8307Sdrh       int j;
268ad2d8307Sdrh       assert( i<pSrc->nSrc-1 );
269ad2d8307Sdrh       pList = pTerm->pUsing;
270ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
271bf5cd97eSdrh         if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
272bf5cd97eSdrh             columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
2734adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
274da93d238Sdrh             "not present in both tables", pList->a[j].zName);
275ad2d8307Sdrh           return 1;
276ad2d8307Sdrh         }
277bf5cd97eSdrh         addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
278ad2d8307Sdrh       }
279ad2d8307Sdrh     }
280ad2d8307Sdrh   }
281ad2d8307Sdrh   return 0;
282ad2d8307Sdrh }
283ad2d8307Sdrh 
284ad2d8307Sdrh /*
2859bb61fe7Sdrh ** Delete the given Select structure and all of its substructures.
2869bb61fe7Sdrh */
2874adee20fSdanielk1977 void sqlite3SelectDelete(Select *p){
28882c3d636Sdrh   if( p==0 ) return;
2894adee20fSdanielk1977   sqlite3ExprListDelete(p->pEList);
2904adee20fSdanielk1977   sqlite3SrcListDelete(p->pSrc);
2914adee20fSdanielk1977   sqlite3ExprDelete(p->pWhere);
2924adee20fSdanielk1977   sqlite3ExprListDelete(p->pGroupBy);
2934adee20fSdanielk1977   sqlite3ExprDelete(p->pHaving);
2944adee20fSdanielk1977   sqlite3ExprListDelete(p->pOrderBy);
2954adee20fSdanielk1977   sqlite3SelectDelete(p->pPrior);
296a76b5dfcSdrh   sqliteFree(p->zSelect);
2979bb61fe7Sdrh   sqliteFree(p);
2989bb61fe7Sdrh }
2999bb61fe7Sdrh 
3009bb61fe7Sdrh /*
3012282792aSdrh ** Delete the aggregate information from the parse structure.
3022282792aSdrh */
3031d83f052Sdrh static void sqliteAggregateInfoReset(Parse *pParse){
3042282792aSdrh   sqliteFree(pParse->aAgg);
3052282792aSdrh   pParse->aAgg = 0;
3062282792aSdrh   pParse->nAgg = 0;
3072282792aSdrh   pParse->useAgg = 0;
3082282792aSdrh }
3092282792aSdrh 
3102282792aSdrh /*
311c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
312c926afbcSdrh ** stack into the sorter.
313c926afbcSdrh */
314c926afbcSdrh static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
315c926afbcSdrh   char *zSortOrder;
316c926afbcSdrh   int i;
317c926afbcSdrh   zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
318c926afbcSdrh   if( zSortOrder==0 ) return;
319c926afbcSdrh   for(i=0; i<pOrderBy->nExpr; i++){
32038640e15Sdrh     int order = pOrderBy->a[i].sortOrder;
32138640e15Sdrh     int type;
32238640e15Sdrh     int c;
32338640e15Sdrh     if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
32438640e15Sdrh       type = SQLITE_SO_TEXT;
32538640e15Sdrh     }else if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_NUM ){
32638640e15Sdrh       type = SQLITE_SO_NUM;
327491791a8Sdrh     }else if( pParse->db->file_format>=4 ){
3284adee20fSdanielk1977       type = sqlite3ExprType(pOrderBy->a[i].pExpr);
32938640e15Sdrh     }else{
33038640e15Sdrh       type = SQLITE_SO_NUM;
33138640e15Sdrh     }
33238640e15Sdrh     if( (order & SQLITE_SO_DIRMASK)==SQLITE_SO_ASC ){
33338640e15Sdrh       c = type==SQLITE_SO_TEXT ? 'A' : '+';
33438640e15Sdrh     }else{
33538640e15Sdrh       c = type==SQLITE_SO_TEXT ? 'D' : '-';
33638640e15Sdrh     }
33738640e15Sdrh     zSortOrder[i] = c;
3384adee20fSdanielk1977     sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr);
339c926afbcSdrh   }
340c926afbcSdrh   zSortOrder[pOrderBy->nExpr] = 0;
3414adee20fSdanielk1977   sqlite3VdbeOp3(v, OP_SortMakeKey, pOrderBy->nExpr, 0, zSortOrder, P3_DYNAMIC);
3424adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_SortPut, 0, 0);
343c926afbcSdrh }
344c926afbcSdrh 
345c926afbcSdrh /*
34638640e15Sdrh ** This routine adds a P3 argument to the last VDBE opcode that was
34738640e15Sdrh ** inserted. The P3 argument added is a string suitable for the
34838640e15Sdrh ** OP_MakeKey or OP_MakeIdxKey opcodes.  The string consists of
34938640e15Sdrh ** characters 't' or 'n' depending on whether or not the various
35038640e15Sdrh ** fields of the key to be generated should be treated as numeric
35138640e15Sdrh ** or as text.  See the OP_MakeKey and OP_MakeIdxKey opcode
35238640e15Sdrh ** documentation for additional information about the P3 string.
3534adee20fSdanielk1977 ** See also the sqlite3AddIdxKeyType() routine.
35438640e15Sdrh */
3554adee20fSdanielk1977 void sqlite3AddKeyType(Vdbe *v, ExprList *pEList){
35638640e15Sdrh   int nColumn = pEList->nExpr;
35738640e15Sdrh   char *zType = sqliteMalloc( nColumn+1 );
35838640e15Sdrh   int i;
35938640e15Sdrh   if( zType==0 ) return;
36038640e15Sdrh   for(i=0; i<nColumn; i++){
3614adee20fSdanielk1977     zType[i] = sqlite3ExprType(pEList->a[i].pExpr)==SQLITE_SO_NUM ? 'n' : 't';
36238640e15Sdrh   }
36338640e15Sdrh   zType[i] = 0;
3644adee20fSdanielk1977   sqlite3VdbeChangeP3(v, -1, zType, P3_DYNAMIC);
36538640e15Sdrh }
36638640e15Sdrh 
36738640e15Sdrh /*
3682282792aSdrh ** This routine generates the code for the inside of the inner loop
3692282792aSdrh ** of a SELECT.
37082c3d636Sdrh **
37138640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
37238640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
37338640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
37438640e15Sdrh ** datatypes for each column.
3752282792aSdrh */
3762282792aSdrh static int selectInnerLoop(
3772282792aSdrh   Parse *pParse,          /* The parser context */
378df199a25Sdrh   Select *p,              /* The complete select statement being coded */
3792282792aSdrh   ExprList *pEList,       /* List of values being extracted */
38082c3d636Sdrh   int srcTab,             /* Pull data from this table */
381967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
3822282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
3832282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
3842282792aSdrh   int eDest,              /* How to dispose of the results */
3852282792aSdrh   int iParm,              /* An argument to the disposal method */
3862282792aSdrh   int iContinue,          /* Jump here to continue with next row */
3872282792aSdrh   int iBreak              /* Jump here to break out of the inner loop */
3882282792aSdrh ){
3892282792aSdrh   Vdbe *v = pParse->pVdbe;
3902282792aSdrh   int i;
39138640e15Sdrh 
392daffd0e5Sdrh   if( v==0 ) return 0;
39338640e15Sdrh   assert( pEList!=0 );
3942282792aSdrh 
395df199a25Sdrh   /* If there was a LIMIT clause on the SELECT statement, then do the check
396df199a25Sdrh   ** to see if this row should be output.
397df199a25Sdrh   */
398df199a25Sdrh   if( pOrderBy==0 ){
3997b58daeaSdrh     if( p->iOffset>=0 ){
4004adee20fSdanielk1977       int addr = sqlite3VdbeCurrentAddr(v);
4014adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+2);
4024adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
403df199a25Sdrh     }
4047b58daeaSdrh     if( p->iLimit>=0 ){
4054adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
406df199a25Sdrh     }
407df199a25Sdrh   }
408df199a25Sdrh 
409967e8b73Sdrh   /* Pull the requested columns.
4102282792aSdrh   */
41138640e15Sdrh   if( nColumn>0 ){
412967e8b73Sdrh     for(i=0; i<nColumn; i++){
4134adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
41482c3d636Sdrh     }
41538640e15Sdrh   }else{
41638640e15Sdrh     nColumn = pEList->nExpr;
41738640e15Sdrh     for(i=0; i<pEList->nExpr; i++){
4184adee20fSdanielk1977       sqlite3ExprCode(pParse, pEList->a[i].pExpr);
41938640e15Sdrh     }
42082c3d636Sdrh   }
4212282792aSdrh 
422daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
423daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
424daffd0e5Sdrh   ** part of the result.
4252282792aSdrh   */
426f5905aa7Sdrh   if( distinct>=0 && pEList && pEList->nExpr>0 ){
4270bd1f4eaSdrh #if NULL_ALWAYS_DISTINCT
4284adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
4290bd1f4eaSdrh #endif
4304adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
4314adee20fSdanielk1977     if( pParse->db->file_format>=4 ) sqlite3AddKeyType(v, pEList);
4324adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
4334adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
4344adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
4354adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_String, 0, 0);
4364adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
4372282792aSdrh   }
43882c3d636Sdrh 
439c926afbcSdrh   switch( eDest ){
44082c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
44182c3d636Sdrh     ** table iParm.
4422282792aSdrh     */
443c926afbcSdrh     case SRT_Union: {
4444adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
4454adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_String, 0, 0);
4464adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
447c926afbcSdrh       break;
448c926afbcSdrh     }
44982c3d636Sdrh 
4505974a30fSdrh     /* Store the result as data using a unique key.
4515974a30fSdrh     */
452c926afbcSdrh     case SRT_Table:
453c926afbcSdrh     case SRT_TempTable: {
4544adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
455c926afbcSdrh       if( pOrderBy ){
456c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
457c926afbcSdrh       }else{
4584adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
4594adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
4604adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
461c926afbcSdrh       }
462c926afbcSdrh       break;
463c926afbcSdrh     }
4645974a30fSdrh 
46582c3d636Sdrh     /* Construct a record from the query result, but instead of
46682c3d636Sdrh     ** saving that record, use it as a key to delete elements from
46782c3d636Sdrh     ** the temporary table iParm.
46882c3d636Sdrh     */
469c926afbcSdrh     case SRT_Except: {
4700bd1f4eaSdrh       int addr;
4714adee20fSdanielk1977       addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
4724adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
4734adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
474c926afbcSdrh       break;
475c926afbcSdrh     }
4762282792aSdrh 
4772282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
4782282792aSdrh     ** then there should be a single item on the stack.  Write this
4792282792aSdrh     ** item into the set table with bogus data.
4802282792aSdrh     */
481c926afbcSdrh     case SRT_Set: {
4824adee20fSdanielk1977       int addr1 = sqlite3VdbeCurrentAddr(v);
48352b36cabSdrh       int addr2;
484967e8b73Sdrh       assert( nColumn==1 );
4854adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
4864adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
4874adee20fSdanielk1977       addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
488c926afbcSdrh       if( pOrderBy ){
489c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
490c926afbcSdrh       }else{
4914adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_String, 0, 0);
4924adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
493c926afbcSdrh       }
4944adee20fSdanielk1977       sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
495c926afbcSdrh       break;
496c926afbcSdrh     }
49782c3d636Sdrh 
4982282792aSdrh     /* If this is a scalar select that is part of an expression, then
4992282792aSdrh     ** store the results in the appropriate memory cell and break out
5002282792aSdrh     ** of the scan loop.
5012282792aSdrh     */
502c926afbcSdrh     case SRT_Mem: {
503967e8b73Sdrh       assert( nColumn==1 );
504c926afbcSdrh       if( pOrderBy ){
505c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
506c926afbcSdrh       }else{
5074adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
5084adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
509c926afbcSdrh       }
510c926afbcSdrh       break;
511c926afbcSdrh     }
5122282792aSdrh 
513f46f905aSdrh     /* Send the data to the callback function.
514f46f905aSdrh     */
515f46f905aSdrh     case SRT_Callback:
516f46f905aSdrh     case SRT_Sorter: {
517f46f905aSdrh       if( pOrderBy ){
5184adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
519f46f905aSdrh         pushOntoSorter(pParse, v, pOrderBy);
520f46f905aSdrh       }else{
521f46f905aSdrh         assert( eDest==SRT_Callback );
5224adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
523f46f905aSdrh       }
524f46f905aSdrh       break;
525f46f905aSdrh     }
526f46f905aSdrh 
527142e30dfSdrh     /* Invoke a subroutine to handle the results.  The subroutine itself
528142e30dfSdrh     ** is responsible for popping the results off of the stack.
529142e30dfSdrh     */
530142e30dfSdrh     case SRT_Subroutine: {
531ac82fcf5Sdrh       if( pOrderBy ){
5324adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
533ac82fcf5Sdrh         pushOntoSorter(pParse, v, pOrderBy);
534ac82fcf5Sdrh       }else{
5354adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
536ac82fcf5Sdrh       }
537142e30dfSdrh       break;
538142e30dfSdrh     }
539142e30dfSdrh 
540d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
541d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
542d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
543d7489c39Sdrh     ** about the actual results of the select.
544d7489c39Sdrh     */
545c926afbcSdrh     default: {
546f46f905aSdrh       assert( eDest==SRT_Discard );
5474adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
548c926afbcSdrh       break;
549c926afbcSdrh     }
550c926afbcSdrh   }
55182c3d636Sdrh   return 0;
55282c3d636Sdrh }
55382c3d636Sdrh 
55482c3d636Sdrh /*
555d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
556d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
557d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
558d8bc7086Sdrh ** routine generates the code needed to do that.
559d8bc7086Sdrh */
560c926afbcSdrh static void generateSortTail(
561c926afbcSdrh   Select *p,       /* The SELECT statement */
562c926afbcSdrh   Vdbe *v,         /* Generate code into this VDBE */
563c926afbcSdrh   int nColumn,     /* Number of columns of data */
564c926afbcSdrh   int eDest,       /* Write the sorted results here */
565c926afbcSdrh   int iParm        /* Optional parameter associated with eDest */
566c926afbcSdrh ){
5674adee20fSdanielk1977   int end1 = sqlite3VdbeMakeLabel(v);
5684adee20fSdanielk1977   int end2 = sqlite3VdbeMakeLabel(v);
569d8bc7086Sdrh   int addr;
570f46f905aSdrh   if( eDest==SRT_Sorter ) return;
5714adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Sort, 0, 0);
5724adee20fSdanielk1977   addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
5737b58daeaSdrh   if( p->iOffset>=0 ){
5744adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+4);
5754adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
5764adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
577df199a25Sdrh   }
5787b58daeaSdrh   if( p->iLimit>=0 ){
5794adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, end2);
580df199a25Sdrh   }
581c926afbcSdrh   switch( eDest ){
582c926afbcSdrh     case SRT_Callback: {
5834adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_SortCallback, nColumn, 0);
584c926afbcSdrh       break;
585c926afbcSdrh     }
586c926afbcSdrh     case SRT_Table:
587c926afbcSdrh     case SRT_TempTable: {
5884adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
5894adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
5904adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
591c926afbcSdrh       break;
592c926afbcSdrh     }
593c926afbcSdrh     case SRT_Set: {
594c926afbcSdrh       assert( nColumn==1 );
5954adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
5964adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
5974adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
5984adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_String, 0, 0);
5994adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
600c926afbcSdrh       break;
601c926afbcSdrh     }
602c926afbcSdrh     case SRT_Mem: {
603c926afbcSdrh       assert( nColumn==1 );
6044adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
6054adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
606c926afbcSdrh       break;
607c926afbcSdrh     }
608ac82fcf5Sdrh     case SRT_Subroutine: {
609ac82fcf5Sdrh       int i;
610ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
6114adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
612ac82fcf5Sdrh       }
6134adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
6144adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
615ac82fcf5Sdrh       break;
616ac82fcf5Sdrh     }
617c926afbcSdrh     default: {
618f46f905aSdrh       /* Do nothing */
619c926afbcSdrh       break;
620c926afbcSdrh     }
621c926afbcSdrh   }
6224adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
6234adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, end2);
6244adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
6254adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, end1);
6264adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
627d8bc7086Sdrh }
628d8bc7086Sdrh 
629d8bc7086Sdrh /*
630fcb78a49Sdrh ** Generate code that will tell the VDBE the datatypes of
631fcb78a49Sdrh ** columns in the result set.
632e78e8284Sdrh **
633e78e8284Sdrh ** This routine only generates code if the "PRAGMA show_datatypes=on"
634e78e8284Sdrh ** has been executed.  The datatypes are reported out in the azCol
635e78e8284Sdrh ** parameter to the callback function.  The first N azCol[] entries
636e78e8284Sdrh ** are the names of the columns, and the second N entries are the
637e78e8284Sdrh ** datatypes for the columns.
638e78e8284Sdrh **
639e78e8284Sdrh ** The "datatype" for a result that is a column of a type is the
640e78e8284Sdrh ** datatype definition extracted from the CREATE TABLE statement.
641e78e8284Sdrh ** The datatype for an expression is either TEXT or NUMERIC.  The
642e78e8284Sdrh ** datatype for a ROWID field is INTEGER.
643fcb78a49Sdrh */
644fcb78a49Sdrh static void generateColumnTypes(
645fcb78a49Sdrh   Parse *pParse,      /* Parser context */
646fcb78a49Sdrh   SrcList *pTabList,  /* List of tables */
647fcb78a49Sdrh   ExprList *pEList    /* Expressions defining the result set */
648fcb78a49Sdrh ){
649fcb78a49Sdrh   Vdbe *v = pParse->pVdbe;
6506a3ea0e6Sdrh   int i, j;
651fcb78a49Sdrh   for(i=0; i<pEList->nExpr; i++){
652fcb78a49Sdrh     Expr *p = pEList->a[i].pExpr;
653fcb78a49Sdrh     char *zType = 0;
654fcb78a49Sdrh     if( p==0 ) continue;
655fcb78a49Sdrh     if( p->op==TK_COLUMN && pTabList ){
6566a3ea0e6Sdrh       Table *pTab;
657fcb78a49Sdrh       int iCol = p->iColumn;
6586a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
6596a3ea0e6Sdrh       assert( j<pTabList->nSrc );
6606a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
661fcb78a49Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
662fcb78a49Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
663fcb78a49Sdrh       if( iCol<0 ){
664fcb78a49Sdrh         zType = "INTEGER";
665fcb78a49Sdrh       }else{
666fcb78a49Sdrh         zType = pTab->aCol[iCol].zType;
667fcb78a49Sdrh       }
668fcb78a49Sdrh     }else{
6694adee20fSdanielk1977       if( sqlite3ExprType(p)==SQLITE_SO_TEXT ){
670fcb78a49Sdrh         zType = "TEXT";
671fcb78a49Sdrh       }else{
672fcb78a49Sdrh         zType = "NUMERIC";
673fcb78a49Sdrh       }
674fcb78a49Sdrh     }
6754adee20fSdanielk1977     sqlite3VdbeOp3(v, OP_ColumnName, i + pEList->nExpr, 0, zType, 0);
676fcb78a49Sdrh   }
677fcb78a49Sdrh }
678fcb78a49Sdrh 
679fcb78a49Sdrh /*
680fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
681fcb78a49Sdrh ** in the result set.  This information is used to provide the
682fcabd464Sdrh ** azCol[] values in the callback.
68382c3d636Sdrh */
684832508b7Sdrh static void generateColumnNames(
685832508b7Sdrh   Parse *pParse,      /* Parser context */
686ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
687832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
688832508b7Sdrh ){
689d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
6906a3ea0e6Sdrh   int i, j;
691fcabd464Sdrh   sqlite *db = pParse->db;
692fcabd464Sdrh   int fullNames, shortNames;
693fcabd464Sdrh 
694d6502758Sdrh   assert( v!=0 );
695*6f8a503dSdanielk1977   if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
696d8bc7086Sdrh   pParse->colNamesSet = 1;
697fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
698fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
69982c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
70082c3d636Sdrh     Expr *p;
701d6502758Sdrh     int p2 = i==pEList->nExpr-1;
7025a38705eSdrh     p = pEList->a[i].pExpr;
7035a38705eSdrh     if( p==0 ) continue;
70482c3d636Sdrh     if( pEList->a[i].zName ){
70582c3d636Sdrh       char *zName = pEList->a[i].zName;
7064adee20fSdanielk1977       sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
70782c3d636Sdrh       continue;
70882c3d636Sdrh     }
709fa173a76Sdrh     if( p->op==TK_COLUMN && pTabList ){
7106a3ea0e6Sdrh       Table *pTab;
71197665873Sdrh       char *zCol;
7128aff1015Sdrh       int iCol = p->iColumn;
7136a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
7146a3ea0e6Sdrh       assert( j<pTabList->nSrc );
7156a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
7168aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
71797665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
718b1363206Sdrh       if( iCol<0 ){
719b1363206Sdrh         zCol = "_ROWID_";
720b1363206Sdrh       }else{
721b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
722b1363206Sdrh       }
723fcabd464Sdrh       if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
7244adee20fSdanielk1977         int addr = sqlite3VdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
7254adee20fSdanielk1977         sqlite3VdbeCompressSpace(v, addr);
726fcabd464Sdrh       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
72782c3d636Sdrh         char *zName = 0;
72882c3d636Sdrh         char *zTab;
72982c3d636Sdrh 
7306a3ea0e6Sdrh         zTab = pTabList->a[j].zAlias;
731fcabd464Sdrh         if( fullNames || zTab==0 ) zTab = pTab->zName;
7324adee20fSdanielk1977         sqlite3SetString(&zName, zTab, ".", zCol, 0);
7334adee20fSdanielk1977         sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, P3_DYNAMIC);
73482c3d636Sdrh       }else{
7354adee20fSdanielk1977         sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zCol, 0);
73682c3d636Sdrh       }
7376977fea8Sdrh     }else if( p->span.z && p->span.z[0] ){
7384adee20fSdanielk1977       int addr = sqlite3VdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
7394adee20fSdanielk1977       sqlite3VdbeCompressSpace(v, addr);
7401bee3d7bSdrh     }else{
7411bee3d7bSdrh       char zName[30];
7421bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
7431bee3d7bSdrh       sprintf(zName, "column%d", i+1);
7444adee20fSdanielk1977       sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
74582c3d636Sdrh     }
74682c3d636Sdrh   }
7475080aaa7Sdrh }
74882c3d636Sdrh 
74982c3d636Sdrh /*
750d8bc7086Sdrh ** Name of the connection operator, used for error messages.
751d8bc7086Sdrh */
752d8bc7086Sdrh static const char *selectOpName(int id){
753d8bc7086Sdrh   char *z;
754d8bc7086Sdrh   switch( id ){
755d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
756d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
757d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
758d8bc7086Sdrh     default:           z = "UNION";       break;
759d8bc7086Sdrh   }
760d8bc7086Sdrh   return z;
761d8bc7086Sdrh }
762d8bc7086Sdrh 
763d8bc7086Sdrh /*
764315555caSdrh ** Forward declaration
765315555caSdrh */
766315555caSdrh static int fillInColumnList(Parse*, Select*);
767315555caSdrh 
768315555caSdrh /*
76922f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
77022f70c32Sdrh ** the result set of that SELECT.
77122f70c32Sdrh */
7724adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
77322f70c32Sdrh   Table *pTab;
774b733d037Sdrh   int i, j;
77522f70c32Sdrh   ExprList *pEList;
776b733d037Sdrh   Column *aCol;
77722f70c32Sdrh 
77822f70c32Sdrh   if( fillInColumnList(pParse, pSelect) ){
77922f70c32Sdrh     return 0;
78022f70c32Sdrh   }
78122f70c32Sdrh   pTab = sqliteMalloc( sizeof(Table) );
78222f70c32Sdrh   if( pTab==0 ){
78322f70c32Sdrh     return 0;
78422f70c32Sdrh   }
78522f70c32Sdrh   pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
78622f70c32Sdrh   pEList = pSelect->pEList;
78722f70c32Sdrh   pTab->nCol = pEList->nExpr;
788417be79cSdrh   assert( pTab->nCol>0 );
789b733d037Sdrh   pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
79022f70c32Sdrh   for(i=0; i<pTab->nCol; i++){
791b733d037Sdrh     Expr *p, *pR;
79222f70c32Sdrh     if( pEList->a[i].zName ){
793b733d037Sdrh       aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
794b733d037Sdrh     }else if( (p=pEList->a[i].pExpr)->op==TK_DOT
795b733d037Sdrh                && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
796b733d037Sdrh       int cnt;
7974adee20fSdanielk1977       sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, 0);
798b733d037Sdrh       for(j=cnt=0; j<i; j++){
7994adee20fSdanielk1977         if( sqlite3StrICmp(aCol[j].zName, aCol[i].zName)==0 ){
800b733d037Sdrh           int n;
801b733d037Sdrh           char zBuf[30];
802b733d037Sdrh           sprintf(zBuf,"_%d",++cnt);
803b733d037Sdrh           n = strlen(zBuf);
8044adee20fSdanielk1977           sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, zBuf, n,0);
805b733d037Sdrh           j = -1;
806b733d037Sdrh         }
807b733d037Sdrh       }
808b733d037Sdrh     }else if( p->span.z && p->span.z[0] ){
8094adee20fSdanielk1977       sqlite3SetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
81022f70c32Sdrh     }else{
81122f70c32Sdrh       char zBuf[30];
81222f70c32Sdrh       sprintf(zBuf, "column%d", i+1);
81322f70c32Sdrh       pTab->aCol[i].zName = sqliteStrDup(zBuf);
81422f70c32Sdrh     }
81522f70c32Sdrh   }
81622f70c32Sdrh   pTab->iPKey = -1;
81722f70c32Sdrh   return pTab;
81822f70c32Sdrh }
81922f70c32Sdrh 
82022f70c32Sdrh /*
821ad2d8307Sdrh ** For the given SELECT statement, do three things.
822d8bc7086Sdrh **
823ad3cab52Sdrh **    (1)  Fill in the pTabList->a[].pTab fields in the SrcList that
82463eb5f29Sdrh **         defines the set of tables that should be scanned.  For views,
82563eb5f29Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
82663eb5f29Sdrh **         that implements the view.  A copy is made of the view's SELECT
82763eb5f29Sdrh **         statement so that we can freely modify or delete that statement
82863eb5f29Sdrh **         without worrying about messing up the presistent representation
82963eb5f29Sdrh **         of the view.
830d8bc7086Sdrh **
831ad2d8307Sdrh **    (2)  Add terms to the WHERE clause to accomodate the NATURAL keyword
832ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
833ad2d8307Sdrh **
834ad2d8307Sdrh **    (3)  Scan the list of columns in the result set (pEList) looking
83554473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
83654473229Sdrh **         If found, expand each "*" to be every column in every table
83754473229Sdrh **         and TABLE.* to be every column in TABLE.
838d8bc7086Sdrh **
839d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
840d8bc7086Sdrh ** in pParse and return non-zero.
841d8bc7086Sdrh */
842d8bc7086Sdrh static int fillInColumnList(Parse *pParse, Select *p){
84354473229Sdrh   int i, j, k, rc;
844ad3cab52Sdrh   SrcList *pTabList;
845daffd0e5Sdrh   ExprList *pEList;
846a76b5dfcSdrh   Table *pTab;
847daffd0e5Sdrh 
848daffd0e5Sdrh   if( p==0 || p->pSrc==0 ) return 1;
849daffd0e5Sdrh   pTabList = p->pSrc;
850daffd0e5Sdrh   pEList = p->pEList;
851d8bc7086Sdrh 
852d8bc7086Sdrh   /* Look up every table in the table list.
853d8bc7086Sdrh   */
854ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
855d8bc7086Sdrh     if( pTabList->a[i].pTab ){
856d8bc7086Sdrh       /* This routine has run before!  No need to continue */
857d8bc7086Sdrh       return 0;
858d8bc7086Sdrh     }
859daffd0e5Sdrh     if( pTabList->a[i].zName==0 ){
86022f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
86122f70c32Sdrh       assert( pTabList->a[i].pSelect!=0 );
862ad2d8307Sdrh       if( pTabList->a[i].zAlias==0 ){
863ad2d8307Sdrh         char zFakeName[60];
864ad2d8307Sdrh         sprintf(zFakeName, "sqlite_subquery_%p_",
865ad2d8307Sdrh            (void*)pTabList->a[i].pSelect);
8664adee20fSdanielk1977         sqlite3SetString(&pTabList->a[i].zAlias, zFakeName, 0);
867ad2d8307Sdrh       }
86822f70c32Sdrh       pTabList->a[i].pTab = pTab =
8694adee20fSdanielk1977         sqlite3ResultSetOfSelect(pParse, pTabList->a[i].zAlias,
87022f70c32Sdrh                                         pTabList->a[i].pSelect);
87122f70c32Sdrh       if( pTab==0 ){
872daffd0e5Sdrh         return 1;
873daffd0e5Sdrh       }
8745cf590c1Sdrh       /* The isTransient flag indicates that the Table structure has been
8755cf590c1Sdrh       ** dynamically allocated and may be freed at any time.  In other words,
8765cf590c1Sdrh       ** pTab is not pointing to a persistent table structure that defines
8775cf590c1Sdrh       ** part of the schema. */
87822f70c32Sdrh       pTab->isTransient = 1;
87922f70c32Sdrh     }else{
880a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
881a76b5dfcSdrh       pTabList->a[i].pTab = pTab =
8824adee20fSdanielk1977         sqlite3LocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
883a76b5dfcSdrh       if( pTab==0 ){
884d8bc7086Sdrh         return 1;
885d8bc7086Sdrh       }
886a76b5dfcSdrh       if( pTab->pSelect ){
88763eb5f29Sdrh         /* We reach here if the named table is a really a view */
8884adee20fSdanielk1977         if( sqlite3ViewGetColumnNames(pParse, pTab) ){
889417be79cSdrh           return 1;
890417be79cSdrh         }
89163eb5f29Sdrh         /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
89263eb5f29Sdrh         ** view within a view.  The SELECT structure has already been
89363eb5f29Sdrh         ** copied by the outer view so we can skip the copy step here
89463eb5f29Sdrh         ** in the inner view.
89563eb5f29Sdrh         */
89663eb5f29Sdrh         if( pTabList->a[i].pSelect==0 ){
8974adee20fSdanielk1977           pTabList->a[i].pSelect = sqlite3SelectDup(pTab->pSelect);
898a76b5dfcSdrh         }
899d8bc7086Sdrh       }
90022f70c32Sdrh     }
90163eb5f29Sdrh   }
902d8bc7086Sdrh 
903ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
904ad2d8307Sdrh   */
905ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
906ad2d8307Sdrh 
9077c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
90854473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
90954473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
9107c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
9117c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
9127c917d19Sdrh   ** each one to the list of all columns in all tables.
91354473229Sdrh   **
91454473229Sdrh   ** The first loop just checks to see if there are any "*" operators
91554473229Sdrh   ** that need expanding.
916d8bc7086Sdrh   */
9177c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
91854473229Sdrh     Expr *pE = pEList->a[k].pExpr;
91954473229Sdrh     if( pE->op==TK_ALL ) break;
92054473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
92154473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
9227c917d19Sdrh   }
92354473229Sdrh   rc = 0;
9247c917d19Sdrh   if( k<pEList->nExpr ){
92554473229Sdrh     /*
92654473229Sdrh     ** If we get here it means the result set contains one or more "*"
92754473229Sdrh     ** operators that need to be expanded.  Loop through each expression
92854473229Sdrh     ** in the result set and expand them one by one.
92954473229Sdrh     */
9307c917d19Sdrh     struct ExprList_item *a = pEList->a;
9317c917d19Sdrh     ExprList *pNew = 0;
9327c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
93354473229Sdrh       Expr *pE = a[k].pExpr;
93454473229Sdrh       if( pE->op!=TK_ALL &&
93554473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
93654473229Sdrh         /* This particular expression does not need to be expanded.
93754473229Sdrh         */
9384adee20fSdanielk1977         pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
9397c917d19Sdrh         pNew->a[pNew->nExpr-1].zName = a[k].zName;
9407c917d19Sdrh         a[k].pExpr = 0;
9417c917d19Sdrh         a[k].zName = 0;
9427c917d19Sdrh       }else{
94354473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
94454473229Sdrh         ** expanded. */
94554473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
94654473229Sdrh         Token *pName;           /* text of name of TABLE */
94754473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
94854473229Sdrh           pName = &pE->pLeft->token;
94954473229Sdrh         }else{
95054473229Sdrh           pName = 0;
95154473229Sdrh         }
952ad3cab52Sdrh         for(i=0; i<pTabList->nSrc; i++){
953d8bc7086Sdrh           Table *pTab = pTabList->a[i].pTab;
95454473229Sdrh           char *zTabName = pTabList->a[i].zAlias;
95554473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
95654473229Sdrh             zTabName = pTab->zName;
95754473229Sdrh           }
95854473229Sdrh           if( pName && (zTabName==0 || zTabName[0]==0 ||
9594adee20fSdanielk1977                  sqlite3StrNICmp(pName->z, zTabName, pName->n)!=0 ||
960c754fa54Sdrh                  zTabName[pName->n]!=0) ){
96154473229Sdrh             continue;
96254473229Sdrh           }
96354473229Sdrh           tableSeen = 1;
964d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
96522f70c32Sdrh             Expr *pExpr, *pLeft, *pRight;
966ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
967ad2d8307Sdrh 
968ad2d8307Sdrh             if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
969ad2d8307Sdrh                 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
970ad2d8307Sdrh               /* In a NATURAL join, omit the join columns from the
971ad2d8307Sdrh               ** table on the right */
972ad2d8307Sdrh               continue;
973ad2d8307Sdrh             }
9744adee20fSdanielk1977             if( i>0 && sqlite3IdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
975ad2d8307Sdrh               /* In a join with a USING clause, omit columns in the
976ad2d8307Sdrh               ** using clause from the table on the right. */
977ad2d8307Sdrh               continue;
978ad2d8307Sdrh             }
9794adee20fSdanielk1977             pRight = sqlite3Expr(TK_ID, 0, 0, 0);
98022f70c32Sdrh             if( pRight==0 ) break;
981ad2d8307Sdrh             pRight->token.z = zName;
982ad2d8307Sdrh             pRight->token.n = strlen(zName);
9834b59ab5eSdrh             pRight->token.dyn = 0;
9844b59ab5eSdrh             if( zTabName && pTabList->nSrc>1 ){
9854adee20fSdanielk1977               pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
9864adee20fSdanielk1977               pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
98722f70c32Sdrh               if( pExpr==0 ) break;
9884b59ab5eSdrh               pLeft->token.z = zTabName;
9894b59ab5eSdrh               pLeft->token.n = strlen(zTabName);
9904b59ab5eSdrh               pLeft->token.dyn = 0;
9914adee20fSdanielk1977               sqlite3SetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
9926977fea8Sdrh               pExpr->span.n = strlen(pExpr->span.z);
9936977fea8Sdrh               pExpr->span.dyn = 1;
9946977fea8Sdrh               pExpr->token.z = 0;
9956977fea8Sdrh               pExpr->token.n = 0;
9966977fea8Sdrh               pExpr->token.dyn = 0;
99722f70c32Sdrh             }else{
99822f70c32Sdrh               pExpr = pRight;
9996977fea8Sdrh               pExpr->span = pExpr->token;
100022f70c32Sdrh             }
10014adee20fSdanielk1977             pNew = sqlite3ExprListAppend(pNew, pExpr, 0);
1002d8bc7086Sdrh           }
1003d8bc7086Sdrh         }
100454473229Sdrh         if( !tableSeen ){
1005f5db2d3eSdrh           if( pName ){
10064adee20fSdanielk1977             sqlite3ErrorMsg(pParse, "no such table: %T", pName);
1007f5db2d3eSdrh           }else{
10084adee20fSdanielk1977             sqlite3ErrorMsg(pParse, "no tables specified");
1009f5db2d3eSdrh           }
101054473229Sdrh           rc = 1;
101154473229Sdrh         }
10127c917d19Sdrh       }
10137c917d19Sdrh     }
10144adee20fSdanielk1977     sqlite3ExprListDelete(pEList);
10157c917d19Sdrh     p->pEList = pNew;
1016d8bc7086Sdrh   }
101754473229Sdrh   return rc;
1018d8bc7086Sdrh }
1019d8bc7086Sdrh 
1020d8bc7086Sdrh /*
1021ff78bd2fSdrh ** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1022ff78bd2fSdrh ** in a select structure.  It just sets the pointers to NULL.  This
1023ff78bd2fSdrh ** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1024ff78bd2fSdrh ** pointer is not NULL, this routine is called recursively on that pointer.
1025ff78bd2fSdrh **
1026ff78bd2fSdrh ** This routine is called on the Select structure that defines a
1027ff78bd2fSdrh ** VIEW in order to undo any bindings to tables.  This is necessary
1028ff78bd2fSdrh ** because those tables might be DROPed by a subsequent SQL command.
10295cf590c1Sdrh ** If the bindings are not removed, then the Select.pSrc->a[].pTab field
10305cf590c1Sdrh ** will be left pointing to a deallocated Table structure after the
10315cf590c1Sdrh ** DROP and a coredump will occur the next time the VIEW is used.
1032ff78bd2fSdrh */
10334adee20fSdanielk1977 void sqlite3SelectUnbind(Select *p){
1034ff78bd2fSdrh   int i;
1035ad3cab52Sdrh   SrcList *pSrc = p->pSrc;
1036ff78bd2fSdrh   Table *pTab;
1037ff78bd2fSdrh   if( p==0 ) return;
1038ad3cab52Sdrh   for(i=0; i<pSrc->nSrc; i++){
1039ff78bd2fSdrh     if( (pTab = pSrc->a[i].pTab)!=0 ){
1040ff78bd2fSdrh       if( pTab->isTransient ){
10414adee20fSdanielk1977         sqlite3DeleteTable(0, pTab);
1042ff78bd2fSdrh       }
1043ff78bd2fSdrh       pSrc->a[i].pTab = 0;
1044ff78bd2fSdrh       if( pSrc->a[i].pSelect ){
10454adee20fSdanielk1977         sqlite3SelectUnbind(pSrc->a[i].pSelect);
1046ff78bd2fSdrh       }
1047ff78bd2fSdrh     }
1048ff78bd2fSdrh   }
1049ff78bd2fSdrh }
1050ff78bd2fSdrh 
1051ff78bd2fSdrh /*
1052d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with
1053d8bc7086Sdrh ** columns in a result.  For each ORDER BY expression, the opcode of
1054967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of
1055d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable
1056d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter.
1057d8bc7086Sdrh **
1058d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first.  A match
1059d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT.
1060d8bc7086Sdrh **
1061d8bc7086Sdrh ** Any entry that does not match is flagged as an error.  The number
1062d8bc7086Sdrh ** of errors is returned.
1063fcb78a49Sdrh **
1064fcb78a49Sdrh ** This routine does NOT correctly initialize the Expr.dataType  field
1065fcb78a49Sdrh ** of the ORDER BY expressions.  The multiSelectSortOrder() routine
1066fcb78a49Sdrh ** must be called to do that after the individual select statements
1067fcb78a49Sdrh ** have all been analyzed.  This routine is unable to compute Expr.dataType
1068fcb78a49Sdrh ** because it must be called before the individual select statements
1069fcb78a49Sdrh ** have been analyzed.
1070d8bc7086Sdrh */
1071d8bc7086Sdrh static int matchOrderbyToColumn(
1072d8bc7086Sdrh   Parse *pParse,          /* A place to leave error messages */
1073d8bc7086Sdrh   Select *pSelect,        /* Match to result columns of this SELECT */
1074d8bc7086Sdrh   ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
1075e4de1febSdrh   int iTable,             /* Insert this value in iTable */
1076d8bc7086Sdrh   int mustComplete        /* If TRUE all ORDER BYs must match */
1077d8bc7086Sdrh ){
1078d8bc7086Sdrh   int nErr = 0;
1079d8bc7086Sdrh   int i, j;
1080d8bc7086Sdrh   ExprList *pEList;
1081d8bc7086Sdrh 
1082daffd0e5Sdrh   if( pSelect==0 || pOrderBy==0 ) return 1;
1083d8bc7086Sdrh   if( mustComplete ){
1084d8bc7086Sdrh     for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1085d8bc7086Sdrh   }
1086d8bc7086Sdrh   if( fillInColumnList(pParse, pSelect) ){
1087d8bc7086Sdrh     return 1;
1088d8bc7086Sdrh   }
1089d8bc7086Sdrh   if( pSelect->pPrior ){
109092cd52f5Sdrh     if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
109192cd52f5Sdrh       return 1;
109292cd52f5Sdrh     }
1093d8bc7086Sdrh   }
1094d8bc7086Sdrh   pEList = pSelect->pEList;
1095d8bc7086Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
1096d8bc7086Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
1097e4de1febSdrh     int iCol = -1;
1098d8bc7086Sdrh     if( pOrderBy->a[i].done ) continue;
10994adee20fSdanielk1977     if( sqlite3ExprIsInteger(pE, &iCol) ){
1100e4de1febSdrh       if( iCol<=0 || iCol>pEList->nExpr ){
11014adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
1102da93d238Sdrh           "ORDER BY position %d should be between 1 and %d",
1103e4de1febSdrh           iCol, pEList->nExpr);
1104e4de1febSdrh         nErr++;
1105e4de1febSdrh         break;
1106e4de1febSdrh       }
1107fcb78a49Sdrh       if( !mustComplete ) continue;
1108e4de1febSdrh       iCol--;
1109e4de1febSdrh     }
1110e4de1febSdrh     for(j=0; iCol<0 && j<pEList->nExpr; j++){
11114cfa7934Sdrh       if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
1112a76b5dfcSdrh         char *zName, *zLabel;
1113a76b5dfcSdrh         zName = pEList->a[j].zName;
1114a76b5dfcSdrh         assert( pE->token.z );
1115a76b5dfcSdrh         zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
11164adee20fSdanielk1977         sqlite3Dequote(zLabel);
11174adee20fSdanielk1977         if( sqlite3StrICmp(zName, zLabel)==0 ){
1118e4de1febSdrh           iCol = j;
1119d8bc7086Sdrh         }
11206e142f54Sdrh         sqliteFree(zLabel);
1121d8bc7086Sdrh       }
11224adee20fSdanielk1977       if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
1123e4de1febSdrh         iCol = j;
1124d8bc7086Sdrh       }
1125e4de1febSdrh     }
1126e4de1febSdrh     if( iCol>=0 ){
1127967e8b73Sdrh       pE->op = TK_COLUMN;
1128e4de1febSdrh       pE->iColumn = iCol;
1129d8bc7086Sdrh       pE->iTable = iTable;
1130d8bc7086Sdrh       pOrderBy->a[i].done = 1;
1131d8bc7086Sdrh     }
1132e4de1febSdrh     if( iCol<0 && mustComplete ){
11334adee20fSdanielk1977       sqlite3ErrorMsg(pParse,
1134da93d238Sdrh         "ORDER BY term number %d does not match any result column", i+1);
1135d8bc7086Sdrh       nErr++;
1136d8bc7086Sdrh       break;
1137d8bc7086Sdrh     }
1138d8bc7086Sdrh   }
1139d8bc7086Sdrh   return nErr;
1140d8bc7086Sdrh }
1141d8bc7086Sdrh 
1142d8bc7086Sdrh /*
1143d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1144d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1145d8bc7086Sdrh */
11464adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1147d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1148d8bc7086Sdrh   if( v==0 ){
11494adee20fSdanielk1977     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1150d8bc7086Sdrh   }
1151d8bc7086Sdrh   return v;
1152d8bc7086Sdrh }
1153d8bc7086Sdrh 
1154fcb78a49Sdrh /*
1155fcb78a49Sdrh ** This routine sets the Expr.dataType field on all elements of
1156fcb78a49Sdrh ** the pOrderBy expression list.  The pOrderBy list will have been
1157fcb78a49Sdrh ** set up by matchOrderbyToColumn().  Hence each expression has
1158fcb78a49Sdrh ** a TK_COLUMN as its root node.  The Expr.iColumn refers to a
1159fcb78a49Sdrh ** column in the result set.   The datatype is set to SQLITE_SO_TEXT
1160fcb78a49Sdrh ** if the corresponding column in p and every SELECT to the left of
1161fcb78a49Sdrh ** p has a datatype of SQLITE_SO_TEXT.  If the cooressponding column
1162fcb78a49Sdrh ** in p or any of the left SELECTs is SQLITE_SO_NUM, then the datatype
1163fcb78a49Sdrh ** of the order-by expression is set to SQLITE_SO_NUM.
1164fcb78a49Sdrh **
1165fcb78a49Sdrh ** Examples:
1166fcb78a49Sdrh **
1167e78e8284Sdrh **     CREATE TABLE one(a INTEGER, b TEXT);
1168e78e8284Sdrh **     CREATE TABLE two(c VARCHAR(5), d FLOAT);
1169e78e8284Sdrh **
1170e78e8284Sdrh **     SELECT b, b FROM one UNION SELECT d, c FROM two ORDER BY 1, 2;
1171e78e8284Sdrh **
1172e78e8284Sdrh ** The primary sort key will use SQLITE_SO_NUM because the "d" in
1173e78e8284Sdrh ** the second SELECT is numeric.  The 1st column of the first SELECT
1174e78e8284Sdrh ** is text but that does not matter because a numeric always overrides
1175e78e8284Sdrh ** a text.
1176e78e8284Sdrh **
1177e78e8284Sdrh ** The secondary key will use the SQLITE_SO_TEXT sort order because
1178e78e8284Sdrh ** both the (second) "b" in the first SELECT and the "c" in the second
1179e78e8284Sdrh ** SELECT have a datatype of text.
1180fcb78a49Sdrh */
1181fcb78a49Sdrh static void multiSelectSortOrder(Select *p, ExprList *pOrderBy){
1182fcb78a49Sdrh   int i;
1183fcb78a49Sdrh   ExprList *pEList;
1184fcb78a49Sdrh   if( pOrderBy==0 ) return;
1185fcb78a49Sdrh   if( p==0 ){
1186fcb78a49Sdrh     for(i=0; i<pOrderBy->nExpr; i++){
1187fcb78a49Sdrh       pOrderBy->a[i].pExpr->dataType = SQLITE_SO_TEXT;
1188fcb78a49Sdrh     }
1189fcb78a49Sdrh     return;
1190fcb78a49Sdrh   }
1191fcb78a49Sdrh   multiSelectSortOrder(p->pPrior, pOrderBy);
1192fcb78a49Sdrh   pEList = p->pEList;
1193fcb78a49Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
1194fcb78a49Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
1195fcb78a49Sdrh     if( pE->dataType==SQLITE_SO_NUM ) continue;
1196fcb78a49Sdrh     assert( pE->iColumn>=0 );
1197fcb78a49Sdrh     if( pEList->nExpr>pE->iColumn ){
11984adee20fSdanielk1977       pE->dataType = sqlite3ExprType(pEList->a[pE->iColumn].pExpr);
1199fcb78a49Sdrh     }
1200fcb78a49Sdrh   }
1201fcb78a49Sdrh }
1202d8bc7086Sdrh 
1203d8bc7086Sdrh /*
12047b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
12057b58daeaSdrh ** nLimit and nOffset fields.  nLimit and nOffset hold the integers
12067b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
12077b58daeaSdrh ** keywords.  Or that hold -1 and 0 if those keywords are omitted.
12087b58daeaSdrh ** iLimit and iOffset are the integer memory register numbers for
12097b58daeaSdrh ** counters used to compute the limit and offset.  If there is no
12107b58daeaSdrh ** limit and/or offset, then iLimit and iOffset are negative.
12117b58daeaSdrh **
12127b58daeaSdrh ** This routine changes the values if iLimit and iOffset only if
12137b58daeaSdrh ** a limit or offset is defined by nLimit and nOffset.  iLimit and
12147b58daeaSdrh ** iOffset should have been preset to appropriate default values
12157b58daeaSdrh ** (usually but not always -1) prior to calling this routine.
12167b58daeaSdrh ** Only if nLimit>=0 or nOffset>0 do the limit registers get
12177b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
12187b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
12197b58daeaSdrh ** SELECT statements.
12207b58daeaSdrh */
12217b58daeaSdrh static void computeLimitRegisters(Parse *pParse, Select *p){
12227b58daeaSdrh   /*
12237b58daeaSdrh   ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
12247b58daeaSdrh   ** all rows.  It is the same as no limit. If the comparision is
12257b58daeaSdrh   ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
12267b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
12277b58daeaSdrh   ** contraversy about what the correct behavior should be.
12287b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
12297b58daeaSdrh   ** no rows.
12307b58daeaSdrh   */
12317b58daeaSdrh   if( p->nLimit>=0 ){
12327b58daeaSdrh     int iMem = pParse->nMem++;
12334adee20fSdanielk1977     Vdbe *v = sqlite3GetVdbe(pParse);
12347b58daeaSdrh     if( v==0 ) return;
12354adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, -p->nLimit, 0);
12364adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
12377b58daeaSdrh     p->iLimit = iMem;
12387b58daeaSdrh   }
12397b58daeaSdrh   if( p->nOffset>0 ){
12407b58daeaSdrh     int iMem = pParse->nMem++;
12414adee20fSdanielk1977     Vdbe *v = sqlite3GetVdbe(pParse);
12427b58daeaSdrh     if( v==0 ) return;
12434adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, -p->nOffset, 0);
12444adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
12457b58daeaSdrh     p->iOffset = iMem;
12467b58daeaSdrh   }
12477b58daeaSdrh }
12487b58daeaSdrh 
12497b58daeaSdrh /*
125082c3d636Sdrh ** This routine is called to process a query that is really the union
125182c3d636Sdrh ** or intersection of two or more separate queries.
1252c926afbcSdrh **
1253e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1254e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1255e78e8284Sdrh ** in which case this routine will be called recursively.
1256e78e8284Sdrh **
1257e78e8284Sdrh ** The results of the total query are to be written into a destination
1258e78e8284Sdrh ** of type eDest with parameter iParm.
1259e78e8284Sdrh **
1260e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1261e78e8284Sdrh **
1262e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1263e78e8284Sdrh **
1264e78e8284Sdrh ** This statement is parsed up as follows:
1265e78e8284Sdrh **
1266e78e8284Sdrh **     SELECT c FROM t3
1267e78e8284Sdrh **      |
1268e78e8284Sdrh **      `----->  SELECT b FROM t2
1269e78e8284Sdrh **                |
12704b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1271e78e8284Sdrh **
1272e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1273e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1274e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1275e78e8284Sdrh **
1276e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1277e78e8284Sdrh ** individual selects always group from left to right.
127882c3d636Sdrh */
127982c3d636Sdrh static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
128010e5e3cfSdrh   int rc;             /* Success code from a subroutine */
128110e5e3cfSdrh   Select *pPrior;     /* Another SELECT immediately to our left */
128210e5e3cfSdrh   Vdbe *v;            /* Generate code to this VDBE */
128382c3d636Sdrh 
12847b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
12857b58daeaSdrh   ** the last SELECT in the series may have an ORDER BY or LIMIT.
128682c3d636Sdrh   */
1287daffd0e5Sdrh   if( p==0 || p->pPrior==0 ) return 1;
1288d8bc7086Sdrh   pPrior = p->pPrior;
1289d8bc7086Sdrh   if( pPrior->pOrderBy ){
12904adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1291da93d238Sdrh       selectOpName(p->op));
129282c3d636Sdrh     return 1;
129382c3d636Sdrh   }
12947b58daeaSdrh   if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
12954adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
12967b58daeaSdrh       selectOpName(p->op));
12977b58daeaSdrh     return 1;
12987b58daeaSdrh   }
129982c3d636Sdrh 
1300d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
1301d8bc7086Sdrh   */
13024adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
1303d8bc7086Sdrh   if( v==0 ) return 1;
1304d8bc7086Sdrh 
13051cc3d75fSdrh   /* Create the destination temporary table if necessary
13061cc3d75fSdrh   */
13071cc3d75fSdrh   if( eDest==SRT_TempTable ){
13084adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
13091cc3d75fSdrh     eDest = SRT_Table;
13101cc3d75fSdrh   }
13111cc3d75fSdrh 
1312f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1313d8bc7086Sdrh   */
131482c3d636Sdrh   switch( p->op ){
1315f46f905aSdrh     case TK_ALL: {
1316f46f905aSdrh       if( p->pOrderBy==0 ){
13177b58daeaSdrh         pPrior->nLimit = p->nLimit;
13187b58daeaSdrh         pPrior->nOffset = p->nOffset;
13194adee20fSdanielk1977         rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0);
1320f46f905aSdrh         if( rc ) return rc;
1321f46f905aSdrh         p->pPrior = 0;
13227b58daeaSdrh         p->iLimit = pPrior->iLimit;
13237b58daeaSdrh         p->iOffset = pPrior->iOffset;
13247b58daeaSdrh         p->nLimit = -1;
13257b58daeaSdrh         p->nOffset = 0;
13264adee20fSdanielk1977         rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0);
1327f46f905aSdrh         p->pPrior = pPrior;
1328f46f905aSdrh         if( rc ) return rc;
1329f46f905aSdrh         break;
1330f46f905aSdrh       }
1331f46f905aSdrh       /* For UNION ALL ... ORDER BY fall through to the next case */
1332f46f905aSdrh     }
133382c3d636Sdrh     case TK_EXCEPT:
133482c3d636Sdrh     case TK_UNION: {
1335d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1336d8bc7086Sdrh       int op;          /* One of the SRT_ operations to apply to self */
1337d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
13387b58daeaSdrh       int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
1339c926afbcSdrh       ExprList *pOrderBy;  /* The ORDER BY clause for the right SELECT */
134082c3d636Sdrh 
1341d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
13427b58daeaSdrh       if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
1343d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1344c926afbcSdrh         ** right.
1345d8bc7086Sdrh         */
134682c3d636Sdrh         unionTab = iParm;
134782c3d636Sdrh       }else{
1348d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1349d8bc7086Sdrh         ** intermediate results.
1350d8bc7086Sdrh         */
135182c3d636Sdrh         unionTab = pParse->nTab++;
1352d8bc7086Sdrh         if( p->pOrderBy
1353d8bc7086Sdrh         && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
1354d8bc7086Sdrh           return 1;
1355d8bc7086Sdrh         }
1356d8bc7086Sdrh         if( p->op!=TK_ALL ){
13574adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 1);
13584adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_KeyAsData, unionTab, 1);
1359345fda3eSdrh         }else{
13604adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
136182c3d636Sdrh         }
1362d8bc7086Sdrh       }
1363d8bc7086Sdrh 
1364d8bc7086Sdrh       /* Code the SELECT statements to our left
1365d8bc7086Sdrh       */
13664adee20fSdanielk1977       rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
136782c3d636Sdrh       if( rc ) return rc;
1368d8bc7086Sdrh 
1369d8bc7086Sdrh       /* Code the current SELECT statement
1370d8bc7086Sdrh       */
1371d8bc7086Sdrh       switch( p->op ){
1372d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
1373d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
1374d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
1375d8bc7086Sdrh       }
137682c3d636Sdrh       p->pPrior = 0;
1377c926afbcSdrh       pOrderBy = p->pOrderBy;
1378c926afbcSdrh       p->pOrderBy = 0;
13797b58daeaSdrh       nLimit = p->nLimit;
13807b58daeaSdrh       p->nLimit = -1;
13817b58daeaSdrh       nOffset = p->nOffset;
13827b58daeaSdrh       p->nOffset = 0;
13834adee20fSdanielk1977       rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0);
138482c3d636Sdrh       p->pPrior = pPrior;
1385c926afbcSdrh       p->pOrderBy = pOrderBy;
13867b58daeaSdrh       p->nLimit = nLimit;
13877b58daeaSdrh       p->nOffset = nOffset;
138882c3d636Sdrh       if( rc ) return rc;
1389d8bc7086Sdrh 
1390d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1391d8bc7086Sdrh       ** it is that we currently need.
1392d8bc7086Sdrh       */
1393c926afbcSdrh       if( eDest!=priorOp || unionTab!=iParm ){
13946b56344dSdrh         int iCont, iBreak, iStart;
139582c3d636Sdrh         assert( p->pEList );
139641202ccaSdrh         if( eDest==SRT_Callback ){
13976a3ea0e6Sdrh           generateColumnNames(pParse, 0, p->pEList);
13986a3ea0e6Sdrh           generateColumnTypes(pParse, p->pSrc, p->pEList);
139941202ccaSdrh         }
14004adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
14014adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
14024adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
14037b58daeaSdrh         computeLimitRegisters(pParse, p);
14044adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
1405fcb78a49Sdrh         multiSelectSortOrder(p, p->pOrderBy);
140638640e15Sdrh         rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
1407d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
140882c3d636Sdrh                              iCont, iBreak);
140982c3d636Sdrh         if( rc ) return 1;
14104adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
14114adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
14124adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
14134adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
1414d8bc7086Sdrh         if( p->pOrderBy ){
1415c926afbcSdrh           generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
1416d8bc7086Sdrh         }
141782c3d636Sdrh       }
141882c3d636Sdrh       break;
141982c3d636Sdrh     }
142082c3d636Sdrh     case TK_INTERSECT: {
142182c3d636Sdrh       int tab1, tab2;
14226b56344dSdrh       int iCont, iBreak, iStart;
14237b58daeaSdrh       int nLimit, nOffset;
142482c3d636Sdrh 
1425d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
14266206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
1427d8bc7086Sdrh       ** by allocating the tables we will need.
1428d8bc7086Sdrh       */
142982c3d636Sdrh       tab1 = pParse->nTab++;
143082c3d636Sdrh       tab2 = pParse->nTab++;
1431d8bc7086Sdrh       if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
1432d8bc7086Sdrh         return 1;
1433d8bc7086Sdrh       }
14344adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_OpenTemp, tab1, 1);
14354adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_KeyAsData, tab1, 1);
1436d8bc7086Sdrh 
1437d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1438d8bc7086Sdrh       */
14394adee20fSdanielk1977       rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
144082c3d636Sdrh       if( rc ) return rc;
1441d8bc7086Sdrh 
1442d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1443d8bc7086Sdrh       */
14444adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 1);
14454adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_KeyAsData, tab2, 1);
144682c3d636Sdrh       p->pPrior = 0;
14477b58daeaSdrh       nLimit = p->nLimit;
14487b58daeaSdrh       p->nLimit = -1;
14497b58daeaSdrh       nOffset = p->nOffset;
14507b58daeaSdrh       p->nOffset = 0;
14514adee20fSdanielk1977       rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0);
145282c3d636Sdrh       p->pPrior = pPrior;
14537b58daeaSdrh       p->nLimit = nLimit;
14547b58daeaSdrh       p->nOffset = nOffset;
145582c3d636Sdrh       if( rc ) return rc;
1456d8bc7086Sdrh 
1457d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1458d8bc7086Sdrh       ** tables.
1459d8bc7086Sdrh       */
146082c3d636Sdrh       assert( p->pEList );
146141202ccaSdrh       if( eDest==SRT_Callback ){
14626a3ea0e6Sdrh         generateColumnNames(pParse, 0, p->pEList);
14636a3ea0e6Sdrh         generateColumnTypes(pParse, p->pSrc, p->pEList);
146441202ccaSdrh       }
14654adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
14664adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
14674adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
14687b58daeaSdrh       computeLimitRegisters(pParse, p);
14694adee20fSdanielk1977       iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
14704adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
1471fcb78a49Sdrh       multiSelectSortOrder(p, p->pOrderBy);
147238640e15Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
1473d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
147482c3d636Sdrh                              iCont, iBreak);
147582c3d636Sdrh       if( rc ) return 1;
14764adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
14774adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
14784adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
14794adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
14804adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
1481d8bc7086Sdrh       if( p->pOrderBy ){
1482c926afbcSdrh         generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
1483d8bc7086Sdrh       }
148482c3d636Sdrh       break;
148582c3d636Sdrh     }
148682c3d636Sdrh   }
148782c3d636Sdrh   assert( p->pEList && pPrior->pEList );
148882c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
14894adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
1490da93d238Sdrh       " do not have the same number of result columns", selectOpName(p->op));
149182c3d636Sdrh     return 1;
14922282792aSdrh   }
14932282792aSdrh   return 0;
14942282792aSdrh }
14952282792aSdrh 
14962282792aSdrh /*
1497832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
14986a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
149984e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
15006a3ea0e6Sdrh ** unchanged.)
1501832508b7Sdrh **
1502832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
1503832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
1504832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
1505832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
1506832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
1507832508b7Sdrh ** of the subquery rather the result set of the subquery.
1508832508b7Sdrh */
15096a3ea0e6Sdrh static void substExprList(ExprList*,int,ExprList*);  /* Forward Decl */
15106a3ea0e6Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
1511832508b7Sdrh   if( pExpr==0 ) return;
151250350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
151350350a15Sdrh     if( pExpr->iColumn<0 ){
151450350a15Sdrh       pExpr->op = TK_NULL;
151550350a15Sdrh     }else{
1516832508b7Sdrh       Expr *pNew;
151784e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1518832508b7Sdrh       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1519832508b7Sdrh       pNew = pEList->a[pExpr->iColumn].pExpr;
1520832508b7Sdrh       assert( pNew!=0 );
1521832508b7Sdrh       pExpr->op = pNew->op;
1522fcb78a49Sdrh       pExpr->dataType = pNew->dataType;
1523d94a6698Sdrh       assert( pExpr->pLeft==0 );
15244adee20fSdanielk1977       pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
1525d94a6698Sdrh       assert( pExpr->pRight==0 );
15264adee20fSdanielk1977       pExpr->pRight = sqlite3ExprDup(pNew->pRight);
1527d94a6698Sdrh       assert( pExpr->pList==0 );
15284adee20fSdanielk1977       pExpr->pList = sqlite3ExprListDup(pNew->pList);
1529832508b7Sdrh       pExpr->iTable = pNew->iTable;
1530832508b7Sdrh       pExpr->iColumn = pNew->iColumn;
1531832508b7Sdrh       pExpr->iAgg = pNew->iAgg;
15324adee20fSdanielk1977       sqlite3TokenCopy(&pExpr->token, &pNew->token);
15334adee20fSdanielk1977       sqlite3TokenCopy(&pExpr->span, &pNew->span);
153450350a15Sdrh     }
1535832508b7Sdrh   }else{
15366a3ea0e6Sdrh     substExpr(pExpr->pLeft, iTable, pEList);
15376a3ea0e6Sdrh     substExpr(pExpr->pRight, iTable, pEList);
15386a3ea0e6Sdrh     substExprList(pExpr->pList, iTable, pEList);
1539832508b7Sdrh   }
1540832508b7Sdrh }
1541832508b7Sdrh static void
15426a3ea0e6Sdrh substExprList(ExprList *pList, int iTable, ExprList *pEList){
1543832508b7Sdrh   int i;
1544832508b7Sdrh   if( pList==0 ) return;
1545832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
15466a3ea0e6Sdrh     substExpr(pList->a[i].pExpr, iTable, pEList);
1547832508b7Sdrh   }
1548832508b7Sdrh }
1549832508b7Sdrh 
1550832508b7Sdrh /*
15511350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
15521350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
15531350b030Sdrh ** occurs.
15541350b030Sdrh **
15551350b030Sdrh ** To understand the concept of flattening, consider the following
15561350b030Sdrh ** query:
15571350b030Sdrh **
15581350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
15591350b030Sdrh **
15601350b030Sdrh ** The default way of implementing this query is to execute the
15611350b030Sdrh ** subquery first and store the results in a temporary table, then
15621350b030Sdrh ** run the outer query on that temporary table.  This requires two
15631350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
15641350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
1565832508b7Sdrh ** optimized.
15661350b030Sdrh **
1567832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
15681350b030Sdrh ** a single flat select, like this:
15691350b030Sdrh **
15701350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
15711350b030Sdrh **
15721350b030Sdrh ** The code generated for this simpification gives the same result
1573832508b7Sdrh ** but only has to scan the data once.  And because indices might
1574832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
1575832508b7Sdrh ** avoided.
15761350b030Sdrh **
1577832508b7Sdrh ** Flattening is only attempted if all of the following are true:
15781350b030Sdrh **
1579832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
15801350b030Sdrh **
1581832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
1582832508b7Sdrh **
15838af4d3acSdrh **   (3)  The subquery is not the right operand of a left outer join, or
15848af4d3acSdrh **        the subquery is not itself a join.  (Ticket #306)
1585832508b7Sdrh **
1586832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
1587832508b7Sdrh **
1588832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
1589832508b7Sdrh **        aggregates.
1590832508b7Sdrh **
1591832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
1592832508b7Sdrh **        DISTINCT.
1593832508b7Sdrh **
159408192d5fSdrh **   (7)  The subquery has a FROM clause.
159508192d5fSdrh **
1596df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
1597df199a25Sdrh **
1598df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
1599df199a25Sdrh **        aggregates.
1600df199a25Sdrh **
1601df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
1602df199a25Sdrh **        use LIMIT.
1603df199a25Sdrh **
1604174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
1605174b6195Sdrh **
16063fc673e6Sdrh **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
16073fc673e6Sdrh **        subquery has no WHERE clause.  (added by ticket #350)
16083fc673e6Sdrh **
1609832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
1610832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
1611832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1612832508b7Sdrh **
1613665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
1614832508b7Sdrh ** If flattening is attempted this routine returns 1.
1615832508b7Sdrh **
1616832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
1617832508b7Sdrh ** the subquery before this routine runs.
16181350b030Sdrh */
16198c74a8caSdrh static int flattenSubquery(
16208c74a8caSdrh   Parse *pParse,       /* The parsing context */
16218c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
16228c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
16238c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
16248c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
16258c74a8caSdrh ){
16260bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
1627ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
1628ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
16290bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
16306a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
1631832508b7Sdrh   int i;
1632832508b7Sdrh   Expr *pWhere;
16331350b030Sdrh 
1634832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
1635832508b7Sdrh   */
1636832508b7Sdrh   if( p==0 ) return 0;
1637832508b7Sdrh   pSrc = p->pSrc;
1638ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
1639832508b7Sdrh   pSub = pSrc->a[iFrom].pSelect;
1640832508b7Sdrh   assert( pSub!=0 );
1641832508b7Sdrh   if( isAgg && subqueryIsAgg ) return 0;
1642ad3cab52Sdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
1643832508b7Sdrh   pSubSrc = pSub->pSrc;
1644832508b7Sdrh   assert( pSubSrc );
1645c31c2eb8Sdrh   if( pSubSrc->nSrc==0 ) return 0;
1646df199a25Sdrh   if( (pSub->isDistinct || pSub->nLimit>=0) &&  (pSrc->nSrc>1 || isAgg) ){
1647df199a25Sdrh      return 0;
1648df199a25Sdrh   }
1649d11d382cSdrh   if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
1650174b6195Sdrh   if( p->pOrderBy && pSub->pOrderBy ) return 0;
1651832508b7Sdrh 
16528af4d3acSdrh   /* Restriction 3:  If the subquery is a join, make sure the subquery is
16538af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
16548af4d3acSdrh   ** is not allowed:
16558af4d3acSdrh   **
16568af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
16578af4d3acSdrh   **
16588af4d3acSdrh   ** If we flatten the above, we would get
16598af4d3acSdrh   **
16608af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
16618af4d3acSdrh   **
16628af4d3acSdrh   ** which is not at all the same thing.
16638af4d3acSdrh   */
16648af4d3acSdrh   if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
16658af4d3acSdrh     return 0;
16668af4d3acSdrh   }
16678af4d3acSdrh 
16683fc673e6Sdrh   /* Restriction 12:  If the subquery is the right operand of a left outer
16693fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
16703fc673e6Sdrh   ** An examples of why this is not allowed:
16713fc673e6Sdrh   **
16723fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
16733fc673e6Sdrh   **
16743fc673e6Sdrh   ** If we flatten the above, we would get
16753fc673e6Sdrh   **
16763fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
16773fc673e6Sdrh   **
16783fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
16793fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
16803fc673e6Sdrh   */
16813fc673e6Sdrh   if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
16823fc673e6Sdrh       && pSub->pWhere!=0 ){
16833fc673e6Sdrh     return 0;
16843fc673e6Sdrh   }
16853fc673e6Sdrh 
16860bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
168763eb5f29Sdrh   ** iFrom-th entry of the FROM clause in the outer query.
1688832508b7Sdrh   */
1689c31c2eb8Sdrh 
1690c31c2eb8Sdrh   /* Move all of the FROM elements of the subquery into the
1691c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
1692c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
1693c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
1694c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
1695c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
1696c31c2eb8Sdrh   ** elements we are now copying in.
1697c31c2eb8Sdrh   */
16986a3ea0e6Sdrh   iParent = pSrc->a[iFrom].iCursor;
1699c31c2eb8Sdrh   {
1700c31c2eb8Sdrh     int nSubSrc = pSubSrc->nSrc;
17018af4d3acSdrh     int jointype = pSrc->a[iFrom].jointype;
1702c31c2eb8Sdrh 
1703c31c2eb8Sdrh     if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
17044adee20fSdanielk1977       sqlite3DeleteTable(0, pSrc->a[iFrom].pTab);
1705c31c2eb8Sdrh     }
1706f26e09c8Sdrh     sqliteFree(pSrc->a[iFrom].zDatabase);
1707c31c2eb8Sdrh     sqliteFree(pSrc->a[iFrom].zName);
1708c31c2eb8Sdrh     sqliteFree(pSrc->a[iFrom].zAlias);
1709c31c2eb8Sdrh     if( nSubSrc>1 ){
1710c31c2eb8Sdrh       int extra = nSubSrc - 1;
1711c31c2eb8Sdrh       for(i=1; i<nSubSrc; i++){
17124adee20fSdanielk1977         pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
1713c31c2eb8Sdrh       }
1714c31c2eb8Sdrh       p->pSrc = pSrc;
1715c31c2eb8Sdrh       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1716c31c2eb8Sdrh         pSrc->a[i] = pSrc->a[i-extra];
1717c31c2eb8Sdrh       }
1718c31c2eb8Sdrh     }
1719c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
1720c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
1721c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1722c31c2eb8Sdrh     }
17238af4d3acSdrh     pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
1724c31c2eb8Sdrh   }
1725c31c2eb8Sdrh 
1726c31c2eb8Sdrh   /* Now begin substituting subquery result set expressions for
1727c31c2eb8Sdrh   ** references to the iParent in the outer query.
1728c31c2eb8Sdrh   **
1729c31c2eb8Sdrh   ** Example:
1730c31c2eb8Sdrh   **
1731c31c2eb8Sdrh   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1732c31c2eb8Sdrh   **   \                     \_____________ subquery __________/          /
1733c31c2eb8Sdrh   **    \_____________________ outer query ______________________________/
1734c31c2eb8Sdrh   **
1735c31c2eb8Sdrh   ** We look at every expression in the outer query and every place we see
1736c31c2eb8Sdrh   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1737c31c2eb8Sdrh   */
17386a3ea0e6Sdrh   substExprList(p->pEList, iParent, pSub->pEList);
1739832508b7Sdrh   pList = p->pEList;
1740832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
17416977fea8Sdrh     Expr *pExpr;
17426977fea8Sdrh     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
17436977fea8Sdrh       pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
1744832508b7Sdrh     }
1745832508b7Sdrh   }
17461b2e0329Sdrh   if( isAgg ){
17476a3ea0e6Sdrh     substExprList(p->pGroupBy, iParent, pSub->pEList);
17486a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
17491b2e0329Sdrh   }
1750174b6195Sdrh   if( pSub->pOrderBy ){
1751174b6195Sdrh     assert( p->pOrderBy==0 );
1752174b6195Sdrh     p->pOrderBy = pSub->pOrderBy;
1753174b6195Sdrh     pSub->pOrderBy = 0;
1754174b6195Sdrh   }else if( p->pOrderBy ){
17556a3ea0e6Sdrh     substExprList(p->pOrderBy, iParent, pSub->pEList);
1756174b6195Sdrh   }
1757832508b7Sdrh   if( pSub->pWhere ){
17584adee20fSdanielk1977     pWhere = sqlite3ExprDup(pSub->pWhere);
1759832508b7Sdrh   }else{
1760832508b7Sdrh     pWhere = 0;
1761832508b7Sdrh   }
1762832508b7Sdrh   if( subqueryIsAgg ){
1763832508b7Sdrh     assert( p->pHaving==0 );
17641b2e0329Sdrh     p->pHaving = p->pWhere;
17651b2e0329Sdrh     p->pWhere = pWhere;
17666a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
17671b2e0329Sdrh     if( pSub->pHaving ){
17684adee20fSdanielk1977       Expr *pHaving = sqlite3ExprDup(pSub->pHaving);
17691b2e0329Sdrh       if( p->pHaving ){
17704adee20fSdanielk1977         p->pHaving = sqlite3Expr(TK_AND, p->pHaving, pHaving, 0);
17711b2e0329Sdrh       }else{
17721b2e0329Sdrh         p->pHaving = pHaving;
17731b2e0329Sdrh       }
17741b2e0329Sdrh     }
17751b2e0329Sdrh     assert( p->pGroupBy==0 );
17764adee20fSdanielk1977     p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
1777832508b7Sdrh   }else if( p->pWhere==0 ){
1778832508b7Sdrh     p->pWhere = pWhere;
1779832508b7Sdrh   }else{
17806a3ea0e6Sdrh     substExpr(p->pWhere, iParent, pSub->pEList);
1781832508b7Sdrh     if( pWhere ){
17824adee20fSdanielk1977       p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pWhere, 0);
1783832508b7Sdrh     }
1784832508b7Sdrh   }
1785c31c2eb8Sdrh 
1786c31c2eb8Sdrh   /* The flattened query is distinct if either the inner or the
1787c31c2eb8Sdrh   ** outer query is distinct.
1788c31c2eb8Sdrh   */
1789832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
17908c74a8caSdrh 
1791c31c2eb8Sdrh   /* Transfer the limit expression from the subquery to the outer
1792c31c2eb8Sdrh   ** query.
1793c31c2eb8Sdrh   */
1794df199a25Sdrh   if( pSub->nLimit>=0 ){
1795df199a25Sdrh     if( p->nLimit<0 ){
1796df199a25Sdrh       p->nLimit = pSub->nLimit;
1797df199a25Sdrh     }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1798df199a25Sdrh       p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1799df199a25Sdrh     }
1800df199a25Sdrh   }
1801df199a25Sdrh   p->nOffset += pSub->nOffset;
18028c74a8caSdrh 
1803c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
1804c31c2eb8Sdrh   ** success.
1805c31c2eb8Sdrh   */
18064adee20fSdanielk1977   sqlite3SelectDelete(pSub);
1807832508b7Sdrh   return 1;
18081350b030Sdrh }
18091350b030Sdrh 
18101350b030Sdrh /*
18119562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it
18129562b551Sdrh ** is a simple min() or max() query.  If it is and this query can be
18139562b551Sdrh ** satisfied using a single seek to the beginning or end of an index,
1814e78e8284Sdrh ** then generate the code for this SELECT and return 1.  If this is not a
18159562b551Sdrh ** simple min() or max() query, then return 0;
18169562b551Sdrh **
18179562b551Sdrh ** A simply min() or max() query looks like this:
18189562b551Sdrh **
18199562b551Sdrh **    SELECT min(a) FROM table;
18209562b551Sdrh **    SELECT max(a) FROM table;
18219562b551Sdrh **
18229562b551Sdrh ** The query may have only a single table in its FROM argument.  There
18239562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
18249562b551Sdrh ** be the min() or max() of a single column of the table.  The column
18259562b551Sdrh ** in the min() or max() function must be indexed.
18269562b551Sdrh **
18274adee20fSdanielk1977 ** The parameters to this routine are the same as for sqlite3Select().
18289562b551Sdrh ** See the header comment on that routine for additional information.
18299562b551Sdrh */
18309562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
18319562b551Sdrh   Expr *pExpr;
18329562b551Sdrh   int iCol;
18339562b551Sdrh   Table *pTab;
18349562b551Sdrh   Index *pIdx;
18359562b551Sdrh   int base;
18369562b551Sdrh   Vdbe *v;
18379562b551Sdrh   int seekOp;
18389562b551Sdrh   int cont;
18396e17529eSdrh   ExprList *pEList, *pList, eList;
18409562b551Sdrh   struct ExprList_item eListItem;
18416e17529eSdrh   SrcList *pSrc;
18426e17529eSdrh 
18439562b551Sdrh 
18449562b551Sdrh   /* Check to see if this query is a simple min() or max() query.  Return
18459562b551Sdrh   ** zero if it is  not.
18469562b551Sdrh   */
18479562b551Sdrh   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
18486e17529eSdrh   pSrc = p->pSrc;
18496e17529eSdrh   if( pSrc->nSrc!=1 ) return 0;
18506e17529eSdrh   pEList = p->pEList;
18516e17529eSdrh   if( pEList->nExpr!=1 ) return 0;
18526e17529eSdrh   pExpr = pEList->a[0].pExpr;
18539562b551Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
18546e17529eSdrh   pList = pExpr->pList;
18556e17529eSdrh   if( pList==0 || pList->nExpr!=1 ) return 0;
18566977fea8Sdrh   if( pExpr->token.n!=3 ) return 0;
18574adee20fSdanielk1977   if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
18580bce8354Sdrh     seekOp = OP_Rewind;
18594adee20fSdanielk1977   }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
18600bce8354Sdrh     seekOp = OP_Last;
18610bce8354Sdrh   }else{
18620bce8354Sdrh     return 0;
18630bce8354Sdrh   }
18646e17529eSdrh   pExpr = pList->a[0].pExpr;
18659562b551Sdrh   if( pExpr->op!=TK_COLUMN ) return 0;
18669562b551Sdrh   iCol = pExpr->iColumn;
18676e17529eSdrh   pTab = pSrc->a[0].pTab;
18689562b551Sdrh 
18699562b551Sdrh   /* If we get to here, it means the query is of the correct form.
187017f71934Sdrh   ** Check to make sure we have an index and make pIdx point to the
187117f71934Sdrh   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
187217f71934Sdrh   ** key column, no index is necessary so set pIdx to NULL.  If no
187317f71934Sdrh   ** usable index is found, return 0.
18749562b551Sdrh   */
18759562b551Sdrh   if( iCol<0 ){
18769562b551Sdrh     pIdx = 0;
18779562b551Sdrh   }else{
18789562b551Sdrh     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
18799562b551Sdrh       assert( pIdx->nColumn>=1 );
18809562b551Sdrh       if( pIdx->aiColumn[0]==iCol ) break;
18819562b551Sdrh     }
18829562b551Sdrh     if( pIdx==0 ) return 0;
18839562b551Sdrh   }
18849562b551Sdrh 
1885e5f50722Sdrh   /* Identify column types if we will be using the callback.  This
18869562b551Sdrh   ** step is skipped if the output is going to a table or a memory cell.
1887e5f50722Sdrh   ** The column names have already been generated in the calling function.
18889562b551Sdrh   */
18894adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
18909562b551Sdrh   if( v==0 ) return 0;
18919562b551Sdrh   if( eDest==SRT_Callback ){
18926a3ea0e6Sdrh     generateColumnTypes(pParse, p->pSrc, p->pEList);
18939562b551Sdrh   }
18949562b551Sdrh 
18950c37e630Sdrh   /* If the output is destined for a temporary table, open that table.
18960c37e630Sdrh   */
18970c37e630Sdrh   if( eDest==SRT_TempTable ){
18984adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
18990c37e630Sdrh   }
19000c37e630Sdrh 
190117f71934Sdrh   /* Generating code to find the min or the max.  Basically all we have
190217f71934Sdrh   ** to do is find the first or the last entry in the chosen index.  If
190317f71934Sdrh   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
190417f71934Sdrh   ** or last entry in the main table.
19059562b551Sdrh   */
19064adee20fSdanielk1977   sqlite3CodeVerifySchema(pParse, pTab->iDb);
19076e17529eSdrh   base = pSrc->a[0].iCursor;
19087b58daeaSdrh   computeLimitRegisters(pParse, p);
19096e17529eSdrh   if( pSrc->a[0].pSelect==0 ){
19104adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
19114adee20fSdanielk1977     sqlite3VdbeOp3(v, OP_OpenRead, base, pTab->tnum, pTab->zName, 0);
19126e17529eSdrh   }
19134adee20fSdanielk1977   cont = sqlite3VdbeMakeLabel(v);
19149562b551Sdrh   if( pIdx==0 ){
19154adee20fSdanielk1977     sqlite3VdbeAddOp(v, seekOp, base, 0);
19169562b551Sdrh   }else{
19174adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
19184adee20fSdanielk1977     sqlite3VdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum, pIdx->zName, P3_STATIC);
19194adee20fSdanielk1977     sqlite3VdbeAddOp(v, seekOp, base+1, 0);
19204adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_IdxRecno, base+1, 0);
19214adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Close, base+1, 0);
19224adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MoveTo, base, 0);
19239562b551Sdrh   }
19245cf8e8c7Sdrh   eList.nExpr = 1;
19255cf8e8c7Sdrh   memset(&eListItem, 0, sizeof(eListItem));
19265cf8e8c7Sdrh   eList.a = &eListItem;
19275cf8e8c7Sdrh   eList.a[0].pExpr = pExpr;
192838640e15Sdrh   selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont);
19294adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, cont);
19304adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Close, base, 0);
19316e17529eSdrh 
19329562b551Sdrh   return 1;
19339562b551Sdrh }
19349562b551Sdrh 
19359562b551Sdrh /*
19369bb61fe7Sdrh ** Generate code for the given SELECT statement.
19379bb61fe7Sdrh **
1938fef5208cSdrh ** The results are distributed in various ways depending on the
1939fef5208cSdrh ** value of eDest and iParm.
1940fef5208cSdrh **
1941fef5208cSdrh **     eDest Value       Result
1942fef5208cSdrh **     ------------    -------------------------------------------
1943fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
1944fef5208cSdrh **
1945fef5208cSdrh **     SRT_Mem         Store first result in memory cell iParm
1946fef5208cSdrh **
1947fef5208cSdrh **     SRT_Set         Store results as keys of a table with cursor iParm
1948fef5208cSdrh **
194982c3d636Sdrh **     SRT_Union       Store results as a key in a temporary table iParm
195082c3d636Sdrh **
19514b11c6d3Sjplyon **     SRT_Except      Remove results from the temporary table iParm.
1952c4a3c779Sdrh **
1953c4a3c779Sdrh **     SRT_Table       Store results in temporary table iParm
19549bb61fe7Sdrh **
1955e78e8284Sdrh ** The table above is incomplete.  Additional eDist value have be added
1956e78e8284Sdrh ** since this comment was written.  See the selectInnerLoop() function for
1957e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings.
1958e78e8284Sdrh **
19599bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
19609bb61fe7Sdrh ** encountered, then an appropriate error message is left in
19619bb61fe7Sdrh ** pParse->zErrMsg.
19629bb61fe7Sdrh **
19639bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
19649bb61fe7Sdrh ** calling function needs to do that.
19651b2e0329Sdrh **
19661b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
19671b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
19681b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
19691b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
19701b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
19711b2e0329Sdrh ** can be changed.
1972e78e8284Sdrh **
1973e78e8284Sdrh ** Example 1:   The meaning of the pParent parameter.
1974e78e8284Sdrh **
1975e78e8284Sdrh **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
1976e78e8284Sdrh **    \                      \_______ subquery _______/        /
1977e78e8284Sdrh **     \                                                      /
1978e78e8284Sdrh **      \____________________ outer query ___________________/
1979e78e8284Sdrh **
1980e78e8284Sdrh ** This routine is called for the outer query first.   For that call,
1981e78e8284Sdrh ** pParent will be NULL.  During the processing of the outer query, this
1982e78e8284Sdrh ** routine is called recursively to handle the subquery.  For the recursive
1983e78e8284Sdrh ** call, pParent will point to the outer query.  Because the subquery is
1984e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will
1985e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.)
19869bb61fe7Sdrh */
19874adee20fSdanielk1977 int sqlite3Select(
1988cce7d176Sdrh   Parse *pParse,         /* The parser context */
19899bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
1990e78e8284Sdrh   int eDest,             /* How to dispose of the results */
1991e78e8284Sdrh   int iParm,             /* A parameter used by the eDest disposal method */
1992832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
1993832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
19941b2e0329Sdrh   int *pParentAgg        /* True if pParent uses aggregate functions */
1995cce7d176Sdrh ){
1996d8bc7086Sdrh   int i;
1997cce7d176Sdrh   WhereInfo *pWInfo;
1998cce7d176Sdrh   Vdbe *v;
1999cce7d176Sdrh   int isAgg = 0;         /* True for select lists like "count(*)" */
2000a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
2001ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
20029bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
20039bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
20042282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
20052282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
200619a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
200719a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
20081d83f052Sdrh   int rc = 1;            /* Value to return from this function */
20099bb61fe7Sdrh 
2010*6f8a503dSdanielk1977   if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
20114adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
2012daffd0e5Sdrh 
201382c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
201482c3d636Sdrh   */
201582c3d636Sdrh   if( p->pPrior ){
201682c3d636Sdrh     return multiSelect(pParse, p, eDest, iParm);
201782c3d636Sdrh   }
201882c3d636Sdrh 
201982c3d636Sdrh   /* Make local copies of the parameters for this query.
202082c3d636Sdrh   */
20219bb61fe7Sdrh   pTabList = p->pSrc;
20229bb61fe7Sdrh   pWhere = p->pWhere;
20239bb61fe7Sdrh   pOrderBy = p->pOrderBy;
20242282792aSdrh   pGroupBy = p->pGroupBy;
20252282792aSdrh   pHaving = p->pHaving;
202619a775c2Sdrh   isDistinct = p->isDistinct;
20279bb61fe7Sdrh 
20286a3ea0e6Sdrh   /* Allocate VDBE cursors for each table in the FROM clause
202910e5e3cfSdrh   */
20304adee20fSdanielk1977   sqlite3SrcListAssignCursors(pParse, pTabList);
203110e5e3cfSdrh 
20329bb61fe7Sdrh   /*
20339bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
20349bb61fe7Sdrh   ** errors before this routine starts.
20359bb61fe7Sdrh   */
20361d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
2037cce7d176Sdrh 
2038e78e8284Sdrh   /* Expand any "*" terms in the result set.  (For example the "*" in
2039e78e8284Sdrh   ** "SELECT * FROM t1")  The fillInColumnlist() routine also does some
2040e78e8284Sdrh   ** other housekeeping - see the header comment for details.
2041cce7d176Sdrh   */
2042d8bc7086Sdrh   if( fillInColumnList(pParse, p) ){
20431d83f052Sdrh     goto select_end;
2044cce7d176Sdrh   }
2045ad2d8307Sdrh   pWhere = p->pWhere;
2046d8bc7086Sdrh   pEList = p->pEList;
20471d83f052Sdrh   if( pEList==0 ) goto select_end;
2048cce7d176Sdrh 
20492282792aSdrh   /* If writing to memory or generating a set
20502282792aSdrh   ** only a single column may be output.
205119a775c2Sdrh   */
2052fef5208cSdrh   if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
20534adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "only a single result allowed for "
2054da93d238Sdrh        "a SELECT that is part of an expression");
20551d83f052Sdrh     goto select_end;
205619a775c2Sdrh   }
205719a775c2Sdrh 
2058c926afbcSdrh   /* ORDER BY is ignored for some destinations.
20592282792aSdrh   */
2060c926afbcSdrh   switch( eDest ){
2061c926afbcSdrh     case SRT_Union:
2062c926afbcSdrh     case SRT_Except:
2063c926afbcSdrh     case SRT_Discard:
2064acd4c695Sdrh       pOrderBy = 0;
2065c926afbcSdrh       break;
2066c926afbcSdrh     default:
2067c926afbcSdrh       break;
20682282792aSdrh   }
20692282792aSdrh 
207010e5e3cfSdrh   /* At this point, we should have allocated all the cursors that we
2071832508b7Sdrh   ** need to handle subquerys and temporary tables.
207210e5e3cfSdrh   **
2073967e8b73Sdrh   ** Resolve the column names and do a semantics check on all the expressions.
20742282792aSdrh   */
20754794b980Sdrh   for(i=0; i<pEList->nExpr; i++){
20764adee20fSdanielk1977     if( sqlite3ExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
20771d83f052Sdrh       goto select_end;
2078cce7d176Sdrh     }
20794adee20fSdanielk1977     if( sqlite3ExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
20801d83f052Sdrh       goto select_end;
2081cce7d176Sdrh     }
2082cce7d176Sdrh   }
2083cce7d176Sdrh   if( pWhere ){
20844adee20fSdanielk1977     if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pWhere) ){
20851d83f052Sdrh       goto select_end;
2086cce7d176Sdrh     }
20874adee20fSdanielk1977     if( sqlite3ExprCheck(pParse, pWhere, 0, 0) ){
20881d83f052Sdrh       goto select_end;
2089cce7d176Sdrh     }
2090cce7d176Sdrh   }
2091c66c5a26Sdrh   if( pHaving ){
2092c66c5a26Sdrh     if( pGroupBy==0 ){
20934adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2094c66c5a26Sdrh       goto select_end;
2095c66c5a26Sdrh     }
20964adee20fSdanielk1977     if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pHaving) ){
2097c66c5a26Sdrh       goto select_end;
2098c66c5a26Sdrh     }
20994adee20fSdanielk1977     if( sqlite3ExprCheck(pParse, pHaving, 1, &isAgg) ){
2100c66c5a26Sdrh       goto select_end;
2101c66c5a26Sdrh     }
2102c66c5a26Sdrh   }
2103cce7d176Sdrh   if( pOrderBy ){
2104cce7d176Sdrh     for(i=0; i<pOrderBy->nExpr; i++){
2105e4de1febSdrh       int iCol;
210688eee38aSdrh       Expr *pE = pOrderBy->a[i].pExpr;
21074adee20fSdanielk1977       if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
21084adee20fSdanielk1977         sqlite3ExprDelete(pE);
21094adee20fSdanielk1977         pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
211088eee38aSdrh       }
21114adee20fSdanielk1977       if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
211288eee38aSdrh         goto select_end;
211388eee38aSdrh       }
21144adee20fSdanielk1977       if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
211588eee38aSdrh         goto select_end;
211688eee38aSdrh       }
21174adee20fSdanielk1977       if( sqlite3ExprIsConstant(pE) ){
21184adee20fSdanielk1977         if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
21194adee20fSdanielk1977           sqlite3ErrorMsg(pParse,
2120da93d238Sdrh              "ORDER BY terms must not be non-integer constants");
21211d83f052Sdrh           goto select_end;
2122e4de1febSdrh         }else if( iCol<=0 || iCol>pEList->nExpr ){
21234adee20fSdanielk1977           sqlite3ErrorMsg(pParse,
2124da93d238Sdrh              "ORDER BY column number %d out of range - should be "
2125e4de1febSdrh              "between 1 and %d", iCol, pEList->nExpr);
2126e4de1febSdrh           goto select_end;
2127e4de1febSdrh         }
2128cce7d176Sdrh       }
2129cce7d176Sdrh     }
2130cce7d176Sdrh   }
21312282792aSdrh   if( pGroupBy ){
21322282792aSdrh     for(i=0; i<pGroupBy->nExpr; i++){
213388eee38aSdrh       int iCol;
21342282792aSdrh       Expr *pE = pGroupBy->a[i].pExpr;
21354adee20fSdanielk1977       if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
21364adee20fSdanielk1977         sqlite3ExprDelete(pE);
21374adee20fSdanielk1977         pE = pGroupBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
21389208643dSdrh       }
21394adee20fSdanielk1977       if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
21401d83f052Sdrh         goto select_end;
21412282792aSdrh       }
21424adee20fSdanielk1977       if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
21431d83f052Sdrh         goto select_end;
21442282792aSdrh       }
21454adee20fSdanielk1977       if( sqlite3ExprIsConstant(pE) ){
21464adee20fSdanielk1977         if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
21474adee20fSdanielk1977           sqlite3ErrorMsg(pParse,
2148da93d238Sdrh             "GROUP BY terms must not be non-integer constants");
214988eee38aSdrh           goto select_end;
215088eee38aSdrh         }else if( iCol<=0 || iCol>pEList->nExpr ){
21514adee20fSdanielk1977           sqlite3ErrorMsg(pParse,
2152da93d238Sdrh              "GROUP BY column number %d out of range - should be "
215388eee38aSdrh              "between 1 and %d", iCol, pEList->nExpr);
215488eee38aSdrh           goto select_end;
215588eee38aSdrh         }
215688eee38aSdrh       }
21572282792aSdrh     }
21582282792aSdrh   }
2159cce7d176Sdrh 
2160d820cb1bSdrh   /* Begin generating code.
2161d820cb1bSdrh   */
21624adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
2163d820cb1bSdrh   if( v==0 ) goto select_end;
2164d820cb1bSdrh 
2165e78e8284Sdrh   /* Identify column names if we will be using them in a callback.  This
2166e78e8284Sdrh   ** step is skipped if the output is going to some other destination.
21670bb28106Sdrh   */
21680bb28106Sdrh   if( eDest==SRT_Callback ){
21696a3ea0e6Sdrh     generateColumnNames(pParse, pTabList, pEList);
21700bb28106Sdrh   }
21710bb28106Sdrh 
2172d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
2173d820cb1bSdrh   */
2174ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
21755cf590c1Sdrh     const char *zSavedAuthContext;
2176c31c2eb8Sdrh     int needRestoreContext;
2177c31c2eb8Sdrh 
2178a76b5dfcSdrh     if( pTabList->a[i].pSelect==0 ) continue;
21795cf590c1Sdrh     if( pTabList->a[i].zName!=0 ){
21805cf590c1Sdrh       zSavedAuthContext = pParse->zAuthContext;
21815cf590c1Sdrh       pParse->zAuthContext = pTabList->a[i].zName;
2182c31c2eb8Sdrh       needRestoreContext = 1;
2183c31c2eb8Sdrh     }else{
2184c31c2eb8Sdrh       needRestoreContext = 0;
21855cf590c1Sdrh     }
21864adee20fSdanielk1977     sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
21876a3ea0e6Sdrh                  pTabList->a[i].iCursor, p, i, &isAgg);
2188c31c2eb8Sdrh     if( needRestoreContext ){
21895cf590c1Sdrh       pParse->zAuthContext = zSavedAuthContext;
21905cf590c1Sdrh     }
2191832508b7Sdrh     pTabList = p->pSrc;
2192832508b7Sdrh     pWhere = p->pWhere;
2193c31c2eb8Sdrh     if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
2194832508b7Sdrh       pOrderBy = p->pOrderBy;
2195acd4c695Sdrh     }
2196832508b7Sdrh     pGroupBy = p->pGroupBy;
2197832508b7Sdrh     pHaving = p->pHaving;
2198832508b7Sdrh     isDistinct = p->isDistinct;
21991b2e0329Sdrh   }
22001b2e0329Sdrh 
22016e17529eSdrh   /* Check for the special case of a min() or max() function by itself
22026e17529eSdrh   ** in the result set.
22036e17529eSdrh   */
22046e17529eSdrh   if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
22056e17529eSdrh     rc = 0;
22066e17529eSdrh     goto select_end;
22076e17529eSdrh   }
22086e17529eSdrh 
22091b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
22101b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
22111b2e0329Sdrh   */
22121b2e0329Sdrh   if( pParent && pParentAgg &&
22138c74a8caSdrh       flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
22141b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
22151b2e0329Sdrh     return rc;
22161b2e0329Sdrh   }
2217832508b7Sdrh 
22187b58daeaSdrh   /* Set the limiter.
22197b58daeaSdrh   */
22207b58daeaSdrh   computeLimitRegisters(pParse, p);
22217b58daeaSdrh 
2222e78e8284Sdrh   /* Identify column types if we will be using a callback.  This
2223e78e8284Sdrh   ** step is skipped if the output is going to a destination other
2224e78e8284Sdrh   ** than a callback.
2225e5f50722Sdrh   **
2226e5f50722Sdrh   ** We have to do this separately from the creation of column names
2227e5f50722Sdrh   ** above because if the pTabList contains views then they will not
2228e5f50722Sdrh   ** have been resolved and we will not know the column types until
2229e5f50722Sdrh   ** now.
2230fcb78a49Sdrh   */
2231fcb78a49Sdrh   if( eDest==SRT_Callback ){
22326a3ea0e6Sdrh     generateColumnTypes(pParse, pTabList, pEList);
2233fcb78a49Sdrh   }
2234fcb78a49Sdrh 
22352d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
22362d0794e3Sdrh   */
22372d0794e3Sdrh   if( eDest==SRT_TempTable ){
22384adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
22392d0794e3Sdrh   }
22402d0794e3Sdrh 
22412282792aSdrh   /* Do an analysis of aggregate expressions.
2242efb7251dSdrh   */
2243d820cb1bSdrh   sqliteAggregateInfoReset(pParse);
2244bb999ef6Sdrh   if( isAgg || pGroupBy ){
22450bce8354Sdrh     assert( pParse->nAgg==0 );
2246bb999ef6Sdrh     isAgg = 1;
22472282792aSdrh     for(i=0; i<pEList->nExpr; i++){
22484adee20fSdanielk1977       if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
22491d83f052Sdrh         goto select_end;
22502282792aSdrh       }
22512282792aSdrh     }
22522282792aSdrh     if( pGroupBy ){
22532282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
22544adee20fSdanielk1977         if( sqlite3ExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
22551d83f052Sdrh           goto select_end;
22562282792aSdrh         }
22572282792aSdrh       }
22582282792aSdrh     }
22594adee20fSdanielk1977     if( pHaving && sqlite3ExprAnalyzeAggregates(pParse, pHaving) ){
22601d83f052Sdrh       goto select_end;
22612282792aSdrh     }
2262191b690eSdrh     if( pOrderBy ){
2263191b690eSdrh       for(i=0; i<pOrderBy->nExpr; i++){
22644adee20fSdanielk1977         if( sqlite3ExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
22651d83f052Sdrh           goto select_end;
2266191b690eSdrh         }
2267191b690eSdrh       }
2268191b690eSdrh     }
2269efb7251dSdrh   }
2270efb7251dSdrh 
22712282792aSdrh   /* Reset the aggregator
2272cce7d176Sdrh   */
2273cce7d176Sdrh   if( isAgg ){
22744adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
2275e5095355Sdrh     for(i=0; i<pParse->nAgg; i++){
22760bce8354Sdrh       FuncDef *pFunc;
22770bce8354Sdrh       if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
22784adee20fSdanielk1977         sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_POINTER);
2279e5095355Sdrh       }
2280e5095355Sdrh     }
22811bee3d7bSdrh     if( pGroupBy==0 ){
22824adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_String, 0, 0);
22834adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AggFocus, 0, 0);
22841bee3d7bSdrh     }
2285cce7d176Sdrh   }
2286cce7d176Sdrh 
228719a775c2Sdrh   /* Initialize the memory cell to NULL
228819a775c2Sdrh   */
2289fef5208cSdrh   if( eDest==SRT_Mem ){
22904adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_String, 0, 0);
22914adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
229219a775c2Sdrh   }
229319a775c2Sdrh 
2294832508b7Sdrh   /* Open a temporary table to use for the distinct set.
2295cce7d176Sdrh   */
229619a775c2Sdrh   if( isDistinct ){
2297832508b7Sdrh     distinct = pParse->nTab++;
22984adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenTemp, distinct, 1);
2299832508b7Sdrh   }else{
2300832508b7Sdrh     distinct = -1;
2301efb7251dSdrh   }
2302832508b7Sdrh 
2303832508b7Sdrh   /* Begin the database scan
2304832508b7Sdrh   */
23054adee20fSdanielk1977   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
230668d2e591Sdrh                             pGroupBy ? 0 : &pOrderBy);
23071d83f052Sdrh   if( pWInfo==0 ) goto select_end;
2308cce7d176Sdrh 
23092282792aSdrh   /* Use the standard inner loop if we are not dealing with
23102282792aSdrh   ** aggregates
2311cce7d176Sdrh   */
2312da9d6c45Sdrh   if( !isAgg ){
2313df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2314df199a25Sdrh                     iParm, pWInfo->iContinue, pWInfo->iBreak) ){
23151d83f052Sdrh        goto select_end;
2316cce7d176Sdrh     }
2317da9d6c45Sdrh   }
2318cce7d176Sdrh 
2319e3184744Sdrh   /* If we are dealing with aggregates, then do the special aggregate
23202282792aSdrh   ** processing.
2321efb7251dSdrh   */
23222282792aSdrh   else{
2323268380caSdrh     AggExpr *pAgg;
23242282792aSdrh     if( pGroupBy ){
23251bee3d7bSdrh       int lbl1;
23262282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
23274adee20fSdanielk1977         sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
2328efb7251dSdrh       }
23294adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
23304adee20fSdanielk1977       if( pParse->db->file_format>=4 ) sqlite3AddKeyType(v, pGroupBy);
23314adee20fSdanielk1977       lbl1 = sqlite3VdbeMakeLabel(v);
23324adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
2333268380caSdrh       for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2334268380caSdrh         if( pAgg->isAgg ) continue;
23354adee20fSdanielk1977         sqlite3ExprCode(pParse, pAgg->pExpr);
23364adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
23372282792aSdrh       }
23384adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, lbl1);
23392282792aSdrh     }
2340268380caSdrh     for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
23412282792aSdrh       Expr *pE;
2342268380caSdrh       int nExpr;
2343268380caSdrh       FuncDef *pDef;
2344268380caSdrh       if( !pAgg->isAgg ) continue;
2345268380caSdrh       assert( pAgg->pFunc!=0 );
2346268380caSdrh       assert( pAgg->pFunc->xStep!=0 );
2347268380caSdrh       pDef = pAgg->pFunc;
2348268380caSdrh       pE = pAgg->pExpr;
2349268380caSdrh       assert( pE!=0 );
23502282792aSdrh       assert( pE->op==TK_AGG_FUNCTION );
23514adee20fSdanielk1977       nExpr = sqlite3ExprCodeExprList(pParse, pE->pList, pDef->includeTypes);
23524adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, i, 0);
23534adee20fSdanielk1977       sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
23542282792aSdrh     }
23552282792aSdrh   }
23562282792aSdrh 
2357cce7d176Sdrh   /* End the database scan loop.
2358cce7d176Sdrh   */
23594adee20fSdanielk1977   sqlite3WhereEnd(pWInfo);
2360cce7d176Sdrh 
23612282792aSdrh   /* If we are processing aggregates, we need to set up a second loop
23622282792aSdrh   ** over all of the aggregate values and process them.
23632282792aSdrh   */
23642282792aSdrh   if( isAgg ){
23654adee20fSdanielk1977     int endagg = sqlite3VdbeMakeLabel(v);
23662282792aSdrh     int startagg;
23674adee20fSdanielk1977     startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
23682282792aSdrh     pParse->useAgg = 1;
23692282792aSdrh     if( pHaving ){
23704adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
23712282792aSdrh     }
2372df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2373df199a25Sdrh                     iParm, startagg, endagg) ){
23741d83f052Sdrh       goto select_end;
23752282792aSdrh     }
23764adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
23774adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, endagg);
23784adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
23792282792aSdrh     pParse->useAgg = 0;
23802282792aSdrh   }
23812282792aSdrh 
2382cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
2383cce7d176Sdrh   ** and send them to the callback one by one.
2384cce7d176Sdrh   */
2385cce7d176Sdrh   if( pOrderBy ){
2386c926afbcSdrh     generateSortTail(p, v, pEList->nExpr, eDest, iParm);
2387cce7d176Sdrh   }
23886a535340Sdrh 
2389f620b4e2Sdrh   /* If this was a subquery, we have now converted the subquery into a
2390f620b4e2Sdrh   ** temporary table.  So delete the subquery structure from the parent
2391f620b4e2Sdrh   ** to prevent this subquery from being evaluated again and to force the
2392f620b4e2Sdrh   ** the use of the temporary table.
2393f620b4e2Sdrh   */
2394f620b4e2Sdrh   if( pParent ){
2395f620b4e2Sdrh     assert( pParent->pSrc->nSrc>parentTab );
2396f620b4e2Sdrh     assert( pParent->pSrc->a[parentTab].pSelect==p );
23974adee20fSdanielk1977     sqlite3SelectDelete(p);
2398f620b4e2Sdrh     pParent->pSrc->a[parentTab].pSelect = 0;
2399f620b4e2Sdrh   }
2400f620b4e2Sdrh 
24011d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
24021d83f052Sdrh   ** to indicate no errors.
24031d83f052Sdrh   */
24041d83f052Sdrh   rc = 0;
24051d83f052Sdrh 
24061d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
24071d83f052Sdrh   ** successful coding of the SELECT.
24081d83f052Sdrh   */
24091d83f052Sdrh select_end:
24101d83f052Sdrh   sqliteAggregateInfoReset(pParse);
24111d83f052Sdrh   return rc;
2412cce7d176Sdrh }
24134adee20fSdanielk1977 
24144adee20fSdanielk1977 
24154adee20fSdanielk1977 
2416