xref: /sqlite-3.40.0/src/select.c (revision bf5cd97e)
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*bf5cd97eSdrh ** $Id: select.c,v 1.98 2002/06/24 12:20:23 drh Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19cce7d176Sdrh /*
209bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that
219bb61fe7Sdrh ** structure.
22cce7d176Sdrh */
239bb61fe7Sdrh Select *sqliteSelectNew(
24daffd0e5Sdrh   ExprList *pEList,     /* which columns to include in the result */
25ad3cab52Sdrh   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
26daffd0e5Sdrh   Expr *pWhere,         /* the WHERE clause */
27daffd0e5Sdrh   ExprList *pGroupBy,   /* the GROUP BY clause */
28daffd0e5Sdrh   Expr *pHaving,        /* the HAVING clause */
29daffd0e5Sdrh   ExprList *pOrderBy,   /* the ORDER BY clause */
309bbca4c1Sdrh   int isDistinct,       /* true if the DISTINCT keyword is present */
319bbca4c1Sdrh   int nLimit,           /* LIMIT value.  -1 means not used */
329bbca4c1Sdrh   int nOffset           /* OFFSET value.  -1 means not used */
339bb61fe7Sdrh ){
349bb61fe7Sdrh   Select *pNew;
359bb61fe7Sdrh   pNew = sqliteMalloc( sizeof(*pNew) );
36daffd0e5Sdrh   if( pNew==0 ){
37daffd0e5Sdrh     sqliteExprListDelete(pEList);
38ad3cab52Sdrh     sqliteSrcListDelete(pSrc);
39daffd0e5Sdrh     sqliteExprDelete(pWhere);
40daffd0e5Sdrh     sqliteExprListDelete(pGroupBy);
41daffd0e5Sdrh     sqliteExprDelete(pHaving);
42daffd0e5Sdrh     sqliteExprListDelete(pOrderBy);
43daffd0e5Sdrh   }else{
449bb61fe7Sdrh     pNew->pEList = pEList;
459bb61fe7Sdrh     pNew->pSrc = pSrc;
469bb61fe7Sdrh     pNew->pWhere = pWhere;
479bb61fe7Sdrh     pNew->pGroupBy = pGroupBy;
489bb61fe7Sdrh     pNew->pHaving = pHaving;
499bb61fe7Sdrh     pNew->pOrderBy = pOrderBy;
509bb61fe7Sdrh     pNew->isDistinct = isDistinct;
5182c3d636Sdrh     pNew->op = TK_SELECT;
529bbca4c1Sdrh     pNew->nLimit = nLimit;
539bbca4c1Sdrh     pNew->nOffset = nOffset;
54daffd0e5Sdrh   }
559bb61fe7Sdrh   return pNew;
569bb61fe7Sdrh }
579bb61fe7Sdrh 
589bb61fe7Sdrh /*
5901f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
6001f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
6101f3f253Sdrh ** in terms of the following bit values:
6201f3f253Sdrh **
6301f3f253Sdrh **     JT_INNER
6401f3f253Sdrh **     JT_OUTER
6501f3f253Sdrh **     JT_NATURAL
6601f3f253Sdrh **     JT_LEFT
6701f3f253Sdrh **     JT_RIGHT
6801f3f253Sdrh **
6901f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
7001f3f253Sdrh **
7101f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
7201f3f253Sdrh ** a join type, but put an error in the pParse structure.
7301f3f253Sdrh */
7401f3f253Sdrh int sqliteJoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
7501f3f253Sdrh   int jointype = 0;
7601f3f253Sdrh   Token *apAll[3];
7701f3f253Sdrh   Token *p;
7801f3f253Sdrh   static struct {
7901f3f253Sdrh     const char *zKeyword;
8001f3f253Sdrh     int nChar;
8101f3f253Sdrh     int code;
8201f3f253Sdrh   } keywords[] = {
8301f3f253Sdrh     { "natural", 7, JT_NATURAL },
84195e6967Sdrh     { "left",    4, JT_LEFT|JT_OUTER },
85195e6967Sdrh     { "right",   5, JT_RIGHT|JT_OUTER },
86195e6967Sdrh     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
8701f3f253Sdrh     { "outer",   5, JT_OUTER },
8801f3f253Sdrh     { "inner",   5, JT_INNER },
8901f3f253Sdrh     { "cross",   5, JT_INNER },
9001f3f253Sdrh   };
9101f3f253Sdrh   int i, j;
9201f3f253Sdrh   apAll[0] = pA;
9301f3f253Sdrh   apAll[1] = pB;
9401f3f253Sdrh   apAll[2] = pC;
95195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
9601f3f253Sdrh     p = apAll[i];
9701f3f253Sdrh     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
9801f3f253Sdrh       if( p->n==keywords[j].nChar
9901f3f253Sdrh           && sqliteStrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
10001f3f253Sdrh         jointype |= keywords[j].code;
10101f3f253Sdrh         break;
10201f3f253Sdrh       }
10301f3f253Sdrh     }
10401f3f253Sdrh     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
10501f3f253Sdrh       jointype |= JT_ERROR;
10601f3f253Sdrh       break;
10701f3f253Sdrh     }
10801f3f253Sdrh   }
109ad2d8307Sdrh   if(
110ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
111195e6967Sdrh      (jointype & JT_ERROR)!=0
112ad2d8307Sdrh   ){
11301f3f253Sdrh     static Token dummy = { 0, 0 };
11401f3f253Sdrh     char *zSp1 = " ", *zSp2 = " ";
11501f3f253Sdrh     if( pB==0 ){ pB = &dummy; zSp1 = 0; }
11601f3f253Sdrh     if( pC==0 ){ pC = &dummy; zSp2 = 0; }
11701f3f253Sdrh     sqliteSetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
11801f3f253Sdrh        pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0);
11901f3f253Sdrh     pParse->nErr++;
12001f3f253Sdrh     jointype = JT_INNER;
121195e6967Sdrh   }else if( jointype & JT_RIGHT ){
122195e6967Sdrh     sqliteSetString(&pParse->zErrMsg,
123195e6967Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported", 0);
124195e6967Sdrh     pParse->nErr++;
125195e6967Sdrh     jointype = JT_INNER;
12601f3f253Sdrh   }
12701f3f253Sdrh   return jointype;
12801f3f253Sdrh }
12901f3f253Sdrh 
13001f3f253Sdrh /*
131ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
132ad2d8307Sdrh ** is not contained in the table.
133ad2d8307Sdrh */
134ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
135ad2d8307Sdrh   int i;
136ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
137ad2d8307Sdrh     if( sqliteStrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
138ad2d8307Sdrh   }
139ad2d8307Sdrh   return -1;
140ad2d8307Sdrh }
141ad2d8307Sdrh 
142ad2d8307Sdrh /*
143ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the
144ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2.
145ad2d8307Sdrh */
146ad2d8307Sdrh static void addWhereTerm(
147ad2d8307Sdrh   const char *zCol,        /* Name of the column */
148ad2d8307Sdrh   const Table *pTab1,      /* First table */
149ad2d8307Sdrh   const Table *pTab2,      /* Second table */
150ad2d8307Sdrh   Expr **ppExpr            /* Add the equality term to this expression */
151ad2d8307Sdrh ){
152ad2d8307Sdrh   Token dummy;
153ad2d8307Sdrh   Expr *pE1a, *pE1b, *pE1c;
154ad2d8307Sdrh   Expr *pE2a, *pE2b, *pE2c;
155ad2d8307Sdrh   Expr *pE;
156ad2d8307Sdrh 
157ad2d8307Sdrh   dummy.z = zCol;
158ad2d8307Sdrh   dummy.n = strlen(zCol);
159ad2d8307Sdrh   pE1a = sqliteExpr(TK_ID, 0, 0, &dummy);
160ad2d8307Sdrh   pE2a = sqliteExpr(TK_ID, 0, 0, &dummy);
161ad2d8307Sdrh   dummy.z = pTab1->zName;
162ad2d8307Sdrh   dummy.n = strlen(dummy.z);
163ad2d8307Sdrh   pE1b = sqliteExpr(TK_ID, 0, 0, &dummy);
164ad2d8307Sdrh   dummy.z = pTab2->zName;
165ad2d8307Sdrh   dummy.n = strlen(dummy.z);
166ad2d8307Sdrh   pE2b = sqliteExpr(TK_ID, 0, 0, &dummy);
167ad2d8307Sdrh   pE1c = sqliteExpr(TK_DOT, pE1b, pE1a, 0);
168ad2d8307Sdrh   pE2c = sqliteExpr(TK_DOT, pE2b, pE2a, 0);
169ad2d8307Sdrh   pE = sqliteExpr(TK_EQ, pE1c, pE2c, 0);
170ad2d8307Sdrh   if( *ppExpr ){
171ad2d8307Sdrh     *ppExpr = sqliteExpr(TK_AND, *ppExpr, pE, 0);
172ad2d8307Sdrh   }else{
173ad2d8307Sdrh     *ppExpr = pE;
174ad2d8307Sdrh   }
175ad2d8307Sdrh }
176ad2d8307Sdrh 
177ad2d8307Sdrh /*
178ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
179ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
180ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
181ad2d8307Sdrh **
182ad2d8307Sdrh ** This routine returns the number of errors encountered.
183ad2d8307Sdrh */
184ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
185ad2d8307Sdrh   SrcList *pSrc;
186ad2d8307Sdrh   int i, j;
187ad2d8307Sdrh   pSrc = p->pSrc;
188ad2d8307Sdrh   for(i=0; i<pSrc->nSrc-1; i++){
189ad2d8307Sdrh     struct SrcList_item *pTerm = &pSrc->a[i];
190ad2d8307Sdrh     struct SrcList_item *pOther = &pSrc->a[i+1];
191ad2d8307Sdrh 
192ad2d8307Sdrh     if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
193ad2d8307Sdrh 
194ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
195ad2d8307Sdrh     ** every column that the two tables have in common.
196ad2d8307Sdrh     */
197ad2d8307Sdrh     if( pTerm->jointype & JT_NATURAL ){
198ad2d8307Sdrh       Table *pTab;
199ad2d8307Sdrh       if( pTerm->pOn || pTerm->pUsing ){
200ad2d8307Sdrh         sqliteSetString(&pParse->zErrMsg, "a NATURAL join may not have "
201ad2d8307Sdrh            "an ON or USING clause", 0);
202ad2d8307Sdrh         pParse->nErr++;
203ad2d8307Sdrh         return 1;
204ad2d8307Sdrh       }
205ad2d8307Sdrh       pTab = pTerm->pTab;
206ad2d8307Sdrh       for(j=0; j<pTab->nCol; j++){
207ad2d8307Sdrh         if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
208ad2d8307Sdrh           addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
209ad2d8307Sdrh         }
210ad2d8307Sdrh       }
211ad2d8307Sdrh     }
212ad2d8307Sdrh 
213ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
214ad2d8307Sdrh     */
215ad2d8307Sdrh     if( pTerm->pOn && pTerm->pUsing ){
216ad2d8307Sdrh       sqliteSetString(&pParse->zErrMsg, "cannot have both ON and USING "
217ad2d8307Sdrh         "clauses in the same join", 0);
218ad2d8307Sdrh       pParse->nErr++;
219ad2d8307Sdrh       return 1;
220ad2d8307Sdrh     }
221ad2d8307Sdrh 
222ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
223ad2d8307Sdrh     ** and AND operator.
224ad2d8307Sdrh     */
225ad2d8307Sdrh     if( pTerm->pOn ){
226ad2d8307Sdrh       if( p->pWhere==0 ){
227ad2d8307Sdrh         p->pWhere = pTerm->pOn;
228ad2d8307Sdrh       }else{
229ad2d8307Sdrh         p->pWhere = sqliteExpr(TK_AND, p->pWhere, pTerm->pOn, 0);
230ad2d8307Sdrh       }
231ad2d8307Sdrh       pTerm->pOn = 0;
232ad2d8307Sdrh     }
233ad2d8307Sdrh 
234ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
235ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
236ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
237ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
238ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
239ad2d8307Sdrh     ** not contained in both tables to be joined.
240ad2d8307Sdrh     */
241ad2d8307Sdrh     if( pTerm->pUsing ){
242ad2d8307Sdrh       IdList *pList;
243ad2d8307Sdrh       int j;
244ad2d8307Sdrh       assert( i<pSrc->nSrc-1 );
245ad2d8307Sdrh       pList = pTerm->pUsing;
246ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
247*bf5cd97eSdrh         if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
248*bf5cd97eSdrh             columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
249ad2d8307Sdrh           sqliteSetString(&pParse->zErrMsg, "cannot join using column ",
250*bf5cd97eSdrh             pList->a[j].zName, " - column not present in both tables", 0);
251ad2d8307Sdrh           pParse->nErr++;
252ad2d8307Sdrh           return 1;
253ad2d8307Sdrh         }
254*bf5cd97eSdrh         addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
255ad2d8307Sdrh       }
256ad2d8307Sdrh     }
257ad2d8307Sdrh   }
258ad2d8307Sdrh   return 0;
259ad2d8307Sdrh }
260ad2d8307Sdrh 
261ad2d8307Sdrh /*
2629bb61fe7Sdrh ** Delete the given Select structure and all of its substructures.
2639bb61fe7Sdrh */
2649bb61fe7Sdrh void sqliteSelectDelete(Select *p){
26582c3d636Sdrh   if( p==0 ) return;
2669bb61fe7Sdrh   sqliteExprListDelete(p->pEList);
267ad3cab52Sdrh   sqliteSrcListDelete(p->pSrc);
2689bb61fe7Sdrh   sqliteExprDelete(p->pWhere);
2699bb61fe7Sdrh   sqliteExprListDelete(p->pGroupBy);
2709bb61fe7Sdrh   sqliteExprDelete(p->pHaving);
2719bb61fe7Sdrh   sqliteExprListDelete(p->pOrderBy);
27282c3d636Sdrh   sqliteSelectDelete(p->pPrior);
273a76b5dfcSdrh   sqliteFree(p->zSelect);
2749bb61fe7Sdrh   sqliteFree(p);
2759bb61fe7Sdrh }
2769bb61fe7Sdrh 
2779bb61fe7Sdrh /*
2782282792aSdrh ** Delete the aggregate information from the parse structure.
2792282792aSdrh */
2801d83f052Sdrh static void sqliteAggregateInfoReset(Parse *pParse){
2812282792aSdrh   sqliteFree(pParse->aAgg);
2822282792aSdrh   pParse->aAgg = 0;
2832282792aSdrh   pParse->nAgg = 0;
2842282792aSdrh   pParse->useAgg = 0;
2852282792aSdrh }
2862282792aSdrh 
2872282792aSdrh /*
288c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
289c926afbcSdrh ** stack into the sorter.
290c926afbcSdrh */
291c926afbcSdrh static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
292c926afbcSdrh   char *zSortOrder;
293c926afbcSdrh   int i;
294c926afbcSdrh   zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
295c926afbcSdrh   if( zSortOrder==0 ) return;
296c926afbcSdrh   for(i=0; i<pOrderBy->nExpr; i++){
297c926afbcSdrh     zSortOrder[i] = pOrderBy->a[i].sortOrder ? '-' : '+';
298c926afbcSdrh     sqliteExprCode(pParse, pOrderBy->a[i].pExpr);
299c926afbcSdrh   }
300c926afbcSdrh   zSortOrder[pOrderBy->nExpr] = 0;
301c926afbcSdrh   sqliteVdbeAddOp(v, OP_SortMakeKey, pOrderBy->nExpr, 0);
302c926afbcSdrh   sqliteVdbeChangeP3(v, -1, zSortOrder, strlen(zSortOrder));
303c926afbcSdrh   sqliteFree(zSortOrder);
304c926afbcSdrh   sqliteVdbeAddOp(v, OP_SortPut, 0, 0);
305c926afbcSdrh }
306c926afbcSdrh 
307c926afbcSdrh /*
3082282792aSdrh ** This routine generates the code for the inside of the inner loop
3092282792aSdrh ** of a SELECT.
31082c3d636Sdrh **
31182c3d636Sdrh ** The pEList is used to determine the values for each column in the
312967e8b73Sdrh ** result row.  Except  if pEList==NULL, then we just read nColumn
31382c3d636Sdrh ** elements from the srcTab table.
3142282792aSdrh */
3152282792aSdrh static int selectInnerLoop(
3162282792aSdrh   Parse *pParse,          /* The parser context */
317df199a25Sdrh   Select *p,              /* The complete select statement being coded */
3182282792aSdrh   ExprList *pEList,       /* List of values being extracted */
31982c3d636Sdrh   int srcTab,             /* Pull data from this table */
320967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
3212282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
3222282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
3232282792aSdrh   int eDest,              /* How to dispose of the results */
3242282792aSdrh   int iParm,              /* An argument to the disposal method */
3252282792aSdrh   int iContinue,          /* Jump here to continue with next row */
3262282792aSdrh   int iBreak              /* Jump here to break out of the inner loop */
3272282792aSdrh ){
3282282792aSdrh   Vdbe *v = pParse->pVdbe;
3292282792aSdrh   int i;
330daffd0e5Sdrh   if( v==0 ) return 0;
3312282792aSdrh 
332df199a25Sdrh   /* If there was a LIMIT clause on the SELECT statement, then do the check
333df199a25Sdrh   ** to see if this row should be output.
334df199a25Sdrh   */
335df199a25Sdrh   if( pOrderBy==0 ){
336df199a25Sdrh     if( p->nOffset>0 ){
337d11d382cSdrh       int addr = sqliteVdbeCurrentAddr(v);
338d11d382cSdrh       sqliteVdbeAddOp(v, OP_MemIncr, p->nOffset, addr+2);
339d11d382cSdrh       sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
340df199a25Sdrh     }
341d11d382cSdrh     if( p->nLimit>=0 ){
342d11d382cSdrh       sqliteVdbeAddOp(v, OP_MemIncr, p->nLimit, iBreak);
343df199a25Sdrh     }
344df199a25Sdrh   }
345df199a25Sdrh 
346967e8b73Sdrh   /* Pull the requested columns.
3472282792aSdrh   */
34882c3d636Sdrh   if( pEList ){
3492282792aSdrh     for(i=0; i<pEList->nExpr; i++){
3502282792aSdrh       sqliteExprCode(pParse, pEList->a[i].pExpr);
3512282792aSdrh     }
352967e8b73Sdrh     nColumn = pEList->nExpr;
35382c3d636Sdrh   }else{
354967e8b73Sdrh     for(i=0; i<nColumn; i++){
35599fcd718Sdrh       sqliteVdbeAddOp(v, OP_Column, srcTab, i);
35682c3d636Sdrh     }
35782c3d636Sdrh   }
3582282792aSdrh 
359daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
360daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
361daffd0e5Sdrh   ** part of the result.
3622282792aSdrh   */
363f5905aa7Sdrh   if( distinct>=0 && pEList && pEList->nExpr>0 ){
3640bd1f4eaSdrh #if NULL_ALWAYS_DISTINCT
3650bd1f4eaSdrh     sqliteVdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqliteVdbeCurrentAddr(v)+7);
3660bd1f4eaSdrh #endif
36799fcd718Sdrh     sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
368f5905aa7Sdrh     sqliteVdbeAddOp(v, OP_Distinct, distinct, sqliteVdbeCurrentAddr(v)+3);
36999fcd718Sdrh     sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
37099fcd718Sdrh     sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
37199fcd718Sdrh     sqliteVdbeAddOp(v, OP_String, 0, 0);
3726b12545fSdrh     sqliteVdbeAddOp(v, OP_PutStrKey, distinct, 0);
3732282792aSdrh   }
37482c3d636Sdrh 
375c926afbcSdrh   switch( eDest ){
37682c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
37782c3d636Sdrh     ** table iParm.
3782282792aSdrh     */
379c926afbcSdrh     case SRT_Union: {
3800bd1f4eaSdrh       sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
381f5905aa7Sdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
3826b12545fSdrh       sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
383c926afbcSdrh       break;
384c926afbcSdrh     }
38582c3d636Sdrh 
3865974a30fSdrh     /* Store the result as data using a unique key.
3875974a30fSdrh     */
388c926afbcSdrh     case SRT_Table:
389c926afbcSdrh     case SRT_TempTable: {
39099fcd718Sdrh       sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
391c926afbcSdrh       if( pOrderBy ){
392c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
393c926afbcSdrh       }else{
39499fcd718Sdrh         sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
39599fcd718Sdrh         sqliteVdbeAddOp(v, OP_Pull, 1, 0);
3966b12545fSdrh         sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
397c926afbcSdrh       }
398c926afbcSdrh       break;
399c926afbcSdrh     }
4005974a30fSdrh 
40182c3d636Sdrh     /* Construct a record from the query result, but instead of
40282c3d636Sdrh     ** saving that record, use it as a key to delete elements from
40382c3d636Sdrh     ** the temporary table iParm.
40482c3d636Sdrh     */
405c926afbcSdrh     case SRT_Except: {
4060bd1f4eaSdrh       int addr;
4070bd1f4eaSdrh       addr = sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
40899fcd718Sdrh       sqliteVdbeAddOp(v, OP_NotFound, iParm, addr+3);
40999fcd718Sdrh       sqliteVdbeAddOp(v, OP_Delete, iParm, 0);
410c926afbcSdrh       break;
411c926afbcSdrh     }
4122282792aSdrh 
4132282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
4142282792aSdrh     ** then there should be a single item on the stack.  Write this
4152282792aSdrh     ** item into the set table with bogus data.
4162282792aSdrh     */
417c926afbcSdrh     case SRT_Set: {
418967e8b73Sdrh       assert( nColumn==1 );
419f5905aa7Sdrh       sqliteVdbeAddOp(v, OP_IsNull, -1, sqliteVdbeCurrentAddr(v)+3);
42099fcd718Sdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
421c926afbcSdrh       if( pOrderBy ){
422c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
423c926afbcSdrh       }else{
4246b12545fSdrh         sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
425c926afbcSdrh       }
426c926afbcSdrh       break;
427c926afbcSdrh     }
42882c3d636Sdrh 
4292282792aSdrh     /* If this is a scalar select that is part of an expression, then
4302282792aSdrh     ** store the results in the appropriate memory cell and break out
4312282792aSdrh     ** of the scan loop.
4322282792aSdrh     */
433c926afbcSdrh     case SRT_Mem: {
434967e8b73Sdrh       assert( nColumn==1 );
435c926afbcSdrh       if( pOrderBy ){
436c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
437c926afbcSdrh       }else{
4388721ce4aSdrh         sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
43999fcd718Sdrh         sqliteVdbeAddOp(v, OP_Goto, 0, iBreak);
440c926afbcSdrh       }
441c926afbcSdrh       break;
442c926afbcSdrh     }
4432282792aSdrh 
444f46f905aSdrh     /* Send the data to the callback function.
445f46f905aSdrh     */
446f46f905aSdrh     case SRT_Callback:
447f46f905aSdrh     case SRT_Sorter: {
448f46f905aSdrh       if( pOrderBy ){
449f46f905aSdrh         sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
450f46f905aSdrh         pushOntoSorter(pParse, v, pOrderBy);
451f46f905aSdrh       }else{
452f46f905aSdrh         assert( eDest==SRT_Callback );
453f46f905aSdrh         sqliteVdbeAddOp(v, OP_Callback, nColumn, 0);
454f46f905aSdrh       }
455f46f905aSdrh       break;
456f46f905aSdrh     }
457f46f905aSdrh 
458d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
459d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
460d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
461d7489c39Sdrh     ** about the actual results of the select.
462d7489c39Sdrh     */
463c926afbcSdrh     default: {
464f46f905aSdrh       assert( eDest==SRT_Discard );
465f46f905aSdrh       sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
466c926afbcSdrh       break;
467c926afbcSdrh     }
468c926afbcSdrh   }
46982c3d636Sdrh   return 0;
47082c3d636Sdrh }
47182c3d636Sdrh 
47282c3d636Sdrh /*
473d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
474d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
475d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
476d8bc7086Sdrh ** routine generates the code needed to do that.
477d8bc7086Sdrh */
478c926afbcSdrh static void generateSortTail(
479c926afbcSdrh   Select *p,       /* The SELECT statement */
480c926afbcSdrh   Vdbe *v,         /* Generate code into this VDBE */
481c926afbcSdrh   int nColumn,     /* Number of columns of data */
482c926afbcSdrh   int eDest,       /* Write the sorted results here */
483c926afbcSdrh   int iParm        /* Optional parameter associated with eDest */
484c926afbcSdrh ){
485d8bc7086Sdrh   int end = sqliteVdbeMakeLabel(v);
486d8bc7086Sdrh   int addr;
487f46f905aSdrh   if( eDest==SRT_Sorter ) return;
48899fcd718Sdrh   sqliteVdbeAddOp(v, OP_Sort, 0, 0);
48999fcd718Sdrh   addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end);
490df199a25Sdrh   if( p->nOffset>0 ){
491d11d382cSdrh     sqliteVdbeAddOp(v, OP_MemIncr, p->nOffset, addr+4);
492d11d382cSdrh     sqliteVdbeAddOp(v, OP_Pop, 1, 0);
493d11d382cSdrh     sqliteVdbeAddOp(v, OP_Goto, 0, addr);
494df199a25Sdrh   }
495d11d382cSdrh   if( p->nLimit>=0 ){
496d11d382cSdrh     sqliteVdbeAddOp(v, OP_MemIncr, p->nLimit, end);
497df199a25Sdrh   }
498c926afbcSdrh   switch( eDest ){
499c926afbcSdrh     case SRT_Callback: {
500df199a25Sdrh       sqliteVdbeAddOp(v, OP_SortCallback, nColumn, 0);
501c926afbcSdrh       break;
502c926afbcSdrh     }
503c926afbcSdrh     case SRT_Table:
504c926afbcSdrh     case SRT_TempTable: {
505c926afbcSdrh       sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
506c926afbcSdrh       sqliteVdbeAddOp(v, OP_Pull, 1, 0);
507c926afbcSdrh       sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
508c926afbcSdrh       break;
509c926afbcSdrh     }
510c926afbcSdrh     case SRT_Set: {
511c926afbcSdrh       assert( nColumn==1 );
512c926afbcSdrh       sqliteVdbeAddOp(v, OP_IsNull, -1, sqliteVdbeCurrentAddr(v)+3);
513c926afbcSdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
514c926afbcSdrh       sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
515c926afbcSdrh       break;
516c926afbcSdrh     }
517c926afbcSdrh     case SRT_Mem: {
518c926afbcSdrh       assert( nColumn==1 );
519c926afbcSdrh       sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
520c926afbcSdrh       sqliteVdbeAddOp(v, OP_Goto, 0, end);
521c926afbcSdrh       break;
522c926afbcSdrh     }
523c926afbcSdrh     default: {
524f46f905aSdrh       /* Do nothing */
525c926afbcSdrh       break;
526c926afbcSdrh     }
527c926afbcSdrh   }
52899fcd718Sdrh   sqliteVdbeAddOp(v, OP_Goto, 0, addr);
52999fcd718Sdrh   sqliteVdbeResolveLabel(v, end);
530a8b38d28Sdrh   sqliteVdbeAddOp(v, OP_SortReset, 0, 0);
531d8bc7086Sdrh }
532d8bc7086Sdrh 
533d8bc7086Sdrh /*
53482c3d636Sdrh ** Generate code that will tell the VDBE how many columns there
53582c3d636Sdrh ** are in the result and the name for each column.  This information
53682c3d636Sdrh ** is used to provide "argc" and "azCol[]" values in the callback.
53782c3d636Sdrh */
538832508b7Sdrh static void generateColumnNames(
539832508b7Sdrh   Parse *pParse,      /* Parser context */
540832508b7Sdrh   int base,           /* VDBE cursor corresponding to first entry in pTabList */
541ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
542832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
543832508b7Sdrh ){
544d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
54582c3d636Sdrh   int i;
546daffd0e5Sdrh   if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return;
547d8bc7086Sdrh   pParse->colNamesSet = 1;
54899fcd718Sdrh   sqliteVdbeAddOp(v, OP_ColumnCount, pEList->nExpr, 0);
54982c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
55082c3d636Sdrh     Expr *p;
5511bee3d7bSdrh     int showFullNames;
55282c3d636Sdrh     if( pEList->a[i].zName ){
55382c3d636Sdrh       char *zName = pEList->a[i].zName;
55499fcd718Sdrh       sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
55599fcd718Sdrh       sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
55682c3d636Sdrh       continue;
55782c3d636Sdrh     }
55882c3d636Sdrh     p = pEList->a[i].pExpr;
559daffd0e5Sdrh     if( p==0 ) continue;
5601bee3d7bSdrh     showFullNames = (pParse->db->flags & SQLITE_FullColNames)!=0;
5611bee3d7bSdrh     if( p->span.z && p->span.z[0] && !showFullNames ){
56299fcd718Sdrh       int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
56399fcd718Sdrh       sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
564e1b6a5b8Sdrh       sqliteVdbeCompressSpace(v, addr);
5651bee3d7bSdrh     }else if( p->op==TK_COLUMN && pTabList ){
566832508b7Sdrh       Table *pTab = pTabList->a[p->iTable - base].pTab;
56797665873Sdrh       char *zCol;
5688aff1015Sdrh       int iCol = p->iColumn;
5698aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
57097665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
57197665873Sdrh       zCol = iCol<0 ? "_ROWID_" : pTab->aCol[iCol].zName;
572ad3cab52Sdrh       if( pTabList->nSrc>1 || showFullNames ){
57382c3d636Sdrh         char *zName = 0;
57482c3d636Sdrh         char *zTab;
57582c3d636Sdrh 
576832508b7Sdrh         zTab = pTabList->a[p->iTable - base].zAlias;
57701a34661Sdrh         if( showFullNames || zTab==0 ) zTab = pTab->zName;
57897665873Sdrh         sqliteSetString(&zName, zTab, ".", zCol, 0);
57999fcd718Sdrh         sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
58099fcd718Sdrh         sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
58182c3d636Sdrh         sqliteFree(zName);
58282c3d636Sdrh       }else{
58399fcd718Sdrh         sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
58422f70c32Sdrh         sqliteVdbeChangeP3(v, -1, zCol, 0);
58582c3d636Sdrh       }
5861bee3d7bSdrh     }else if( p->span.z && p->span.z[0] ){
5871bee3d7bSdrh       int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
5881bee3d7bSdrh       sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
5891bee3d7bSdrh       sqliteVdbeCompressSpace(v, addr);
5901bee3d7bSdrh     }else{
5911bee3d7bSdrh       char zName[30];
5921bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
5931bee3d7bSdrh       sprintf(zName, "column%d", i+1);
5941bee3d7bSdrh       sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
5951bee3d7bSdrh       sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
59682c3d636Sdrh     }
59782c3d636Sdrh   }
59882c3d636Sdrh }
59982c3d636Sdrh 
60082c3d636Sdrh /*
601d8bc7086Sdrh ** Name of the connection operator, used for error messages.
602d8bc7086Sdrh */
603d8bc7086Sdrh static const char *selectOpName(int id){
604d8bc7086Sdrh   char *z;
605d8bc7086Sdrh   switch( id ){
606d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
607d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
608d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
609d8bc7086Sdrh     default:           z = "UNION";       break;
610d8bc7086Sdrh   }
611d8bc7086Sdrh   return z;
612d8bc7086Sdrh }
613d8bc7086Sdrh 
614d8bc7086Sdrh /*
61522f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
61622f70c32Sdrh ** the result set of that SELECT.
61722f70c32Sdrh */
61822f70c32Sdrh Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
61922f70c32Sdrh   Table *pTab;
62022f70c32Sdrh   int i;
62122f70c32Sdrh   ExprList *pEList;
62222f70c32Sdrh   static int fillInColumnList(Parse*, Select*);
62322f70c32Sdrh 
62422f70c32Sdrh   if( fillInColumnList(pParse, pSelect) ){
62522f70c32Sdrh     return 0;
62622f70c32Sdrh   }
62722f70c32Sdrh   pTab = sqliteMalloc( sizeof(Table) );
62822f70c32Sdrh   if( pTab==0 ){
62922f70c32Sdrh     return 0;
63022f70c32Sdrh   }
63122f70c32Sdrh   pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
63222f70c32Sdrh   pEList = pSelect->pEList;
63322f70c32Sdrh   pTab->nCol = pEList->nExpr;
634417be79cSdrh   assert( pTab->nCol>0 );
63522f70c32Sdrh   pTab->aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
63622f70c32Sdrh   for(i=0; i<pTab->nCol; i++){
63722f70c32Sdrh     Expr *p;
63822f70c32Sdrh     if( pEList->a[i].zName ){
63922f70c32Sdrh       pTab->aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
64022f70c32Sdrh     }else if( (p=pEList->a[i].pExpr)->span.z && p->span.z[0] ){
64122f70c32Sdrh       sqliteSetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
642d820cb1bSdrh     }else if( p->op==TK_DOT && p->pRight && p->pRight->token.z &&
643d820cb1bSdrh            p->pRight->token.z[0] ){
644d820cb1bSdrh       sqliteSetNString(&pTab->aCol[i].zName,
645d820cb1bSdrh            p->pRight->token.z, p->pRight->token.n, 0);
64622f70c32Sdrh     }else{
64722f70c32Sdrh       char zBuf[30];
64822f70c32Sdrh       sprintf(zBuf, "column%d", i+1);
64922f70c32Sdrh       pTab->aCol[i].zName = sqliteStrDup(zBuf);
65022f70c32Sdrh     }
65122f70c32Sdrh   }
65222f70c32Sdrh   pTab->iPKey = -1;
65322f70c32Sdrh   return pTab;
65422f70c32Sdrh }
65522f70c32Sdrh 
65622f70c32Sdrh /*
657ad2d8307Sdrh ** For the given SELECT statement, do three things.
658d8bc7086Sdrh **
659ad3cab52Sdrh **    (1)  Fill in the pTabList->a[].pTab fields in the SrcList that
660967e8b73Sdrh **         defines the set of tables that should be scanned.
661d8bc7086Sdrh **
662ad2d8307Sdrh **    (2)  Add terms to the WHERE clause to accomodate the NATURAL keyword
663ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
664ad2d8307Sdrh **
665ad2d8307Sdrh **    (3)  Scan the list of columns in the result set (pEList) looking
66654473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
66754473229Sdrh **         If found, expand each "*" to be every column in every table
66854473229Sdrh **         and TABLE.* to be every column in TABLE.
669d8bc7086Sdrh **
670d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
671d8bc7086Sdrh ** in pParse and return non-zero.
672d8bc7086Sdrh */
673d8bc7086Sdrh static int fillInColumnList(Parse *pParse, Select *p){
67454473229Sdrh   int i, j, k, rc;
675ad3cab52Sdrh   SrcList *pTabList;
676daffd0e5Sdrh   ExprList *pEList;
677a76b5dfcSdrh   Table *pTab;
678daffd0e5Sdrh 
679daffd0e5Sdrh   if( p==0 || p->pSrc==0 ) return 1;
680daffd0e5Sdrh   pTabList = p->pSrc;
681daffd0e5Sdrh   pEList = p->pEList;
682d8bc7086Sdrh 
683d8bc7086Sdrh   /* Look up every table in the table list.
684d8bc7086Sdrh   */
685ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
686d8bc7086Sdrh     if( pTabList->a[i].pTab ){
687d8bc7086Sdrh       /* This routine has run before!  No need to continue */
688d8bc7086Sdrh       return 0;
689d8bc7086Sdrh     }
690daffd0e5Sdrh     if( pTabList->a[i].zName==0 ){
69122f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
69222f70c32Sdrh       assert( pTabList->a[i].pSelect!=0 );
693ad2d8307Sdrh       if( pTabList->a[i].zAlias==0 ){
694ad2d8307Sdrh         char zFakeName[60];
695ad2d8307Sdrh         sprintf(zFakeName, "sqlite_subquery_%p_",
696ad2d8307Sdrh            (void*)pTabList->a[i].pSelect);
697ad2d8307Sdrh         sqliteSetString(&pTabList->a[i].zAlias, zFakeName, 0);
698ad2d8307Sdrh       }
69922f70c32Sdrh       pTabList->a[i].pTab = pTab =
70022f70c32Sdrh         sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias,
70122f70c32Sdrh                                         pTabList->a[i].pSelect);
70222f70c32Sdrh       if( pTab==0 ){
703daffd0e5Sdrh         return 1;
704daffd0e5Sdrh       }
70522f70c32Sdrh       pTab->isTransient = 1;
70622f70c32Sdrh     }else{
707a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
708a76b5dfcSdrh       pTabList->a[i].pTab = pTab =
709a76b5dfcSdrh         sqliteFindTable(pParse->db, pTabList->a[i].zName);
710a76b5dfcSdrh       if( pTab==0 ){
711d8bc7086Sdrh         sqliteSetString(&pParse->zErrMsg, "no such table: ",
712d8bc7086Sdrh            pTabList->a[i].zName, 0);
713d8bc7086Sdrh         pParse->nErr++;
714d8bc7086Sdrh         return 1;
715d8bc7086Sdrh       }
716a76b5dfcSdrh       if( pTab->pSelect ){
717417be79cSdrh         if( sqliteViewGetColumnNames(pParse, pTab) ){
718417be79cSdrh           return 1;
719417be79cSdrh         }
720ff78bd2fSdrh         pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect);
721a76b5dfcSdrh       }
722d8bc7086Sdrh     }
72322f70c32Sdrh   }
724d8bc7086Sdrh 
725ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
726ad2d8307Sdrh   */
727ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
728ad2d8307Sdrh 
7297c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
73054473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
73154473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
7327c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
7337c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
7347c917d19Sdrh   ** each one to the list of all columns in all tables.
73554473229Sdrh   **
73654473229Sdrh   ** The first loop just checks to see if there are any "*" operators
73754473229Sdrh   ** that need expanding.
738d8bc7086Sdrh   */
7397c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
74054473229Sdrh     Expr *pE = pEList->a[k].pExpr;
74154473229Sdrh     if( pE->op==TK_ALL ) break;
74254473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
74354473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
7447c917d19Sdrh   }
74554473229Sdrh   rc = 0;
7467c917d19Sdrh   if( k<pEList->nExpr ){
74754473229Sdrh     /*
74854473229Sdrh     ** If we get here it means the result set contains one or more "*"
74954473229Sdrh     ** operators that need to be expanded.  Loop through each expression
75054473229Sdrh     ** in the result set and expand them one by one.
75154473229Sdrh     */
7527c917d19Sdrh     struct ExprList_item *a = pEList->a;
7537c917d19Sdrh     ExprList *pNew = 0;
7547c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
75554473229Sdrh       Expr *pE = a[k].pExpr;
75654473229Sdrh       if( pE->op!=TK_ALL &&
75754473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
75854473229Sdrh         /* This particular expression does not need to be expanded.
75954473229Sdrh         */
7607c917d19Sdrh         pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
7617c917d19Sdrh         pNew->a[pNew->nExpr-1].zName = a[k].zName;
7627c917d19Sdrh         a[k].pExpr = 0;
7637c917d19Sdrh         a[k].zName = 0;
7647c917d19Sdrh       }else{
76554473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
76654473229Sdrh         ** expanded. */
76754473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
76854473229Sdrh         Token *pName;           /* text of name of TABLE */
76954473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
77054473229Sdrh           pName = &pE->pLeft->token;
77154473229Sdrh         }else{
77254473229Sdrh           pName = 0;
77354473229Sdrh         }
774ad3cab52Sdrh         for(i=0; i<pTabList->nSrc; i++){
775d8bc7086Sdrh           Table *pTab = pTabList->a[i].pTab;
77654473229Sdrh           char *zTabName = pTabList->a[i].zAlias;
77754473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
77854473229Sdrh             zTabName = pTab->zName;
77954473229Sdrh           }
78054473229Sdrh           if( pName && (zTabName==0 || zTabName[0]==0 ||
781c754fa54Sdrh                  sqliteStrNICmp(pName->z, zTabName, pName->n)!=0 ||
782c754fa54Sdrh                  zTabName[pName->n]!=0) ){
78354473229Sdrh             continue;
78454473229Sdrh           }
78554473229Sdrh           tableSeen = 1;
786d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
78722f70c32Sdrh             Expr *pExpr, *pLeft, *pRight;
788ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
789ad2d8307Sdrh 
790ad2d8307Sdrh             if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
791ad2d8307Sdrh                 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
792ad2d8307Sdrh               /* In a NATURAL join, omit the join columns from the
793ad2d8307Sdrh               ** table on the right */
794ad2d8307Sdrh               continue;
795ad2d8307Sdrh             }
796ad2d8307Sdrh             if( i>0 && sqliteIdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
797ad2d8307Sdrh               /* In a join with a USING clause, omit columns in the
798ad2d8307Sdrh               ** using clause from the table on the right. */
799ad2d8307Sdrh               continue;
800ad2d8307Sdrh             }
80122f70c32Sdrh             pRight = sqliteExpr(TK_ID, 0, 0, 0);
80222f70c32Sdrh             if( pRight==0 ) break;
803ad2d8307Sdrh             pRight->token.z = zName;
804ad2d8307Sdrh             pRight->token.n = strlen(zName);
80554473229Sdrh             if( zTabName ){
80622f70c32Sdrh               pLeft = sqliteExpr(TK_ID, 0, 0, 0);
80722f70c32Sdrh               if( pLeft==0 ) break;
80854473229Sdrh               pLeft->token.z = zTabName;
80954473229Sdrh               pLeft->token.n = strlen(zTabName);
81022f70c32Sdrh               pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
81122f70c32Sdrh               if( pExpr==0 ) break;
81222f70c32Sdrh             }else{
81322f70c32Sdrh               pExpr = pRight;
81422f70c32Sdrh               pExpr->span = pExpr->token;
81522f70c32Sdrh             }
8167c917d19Sdrh             pNew = sqliteExprListAppend(pNew, pExpr, 0);
817d8bc7086Sdrh           }
818d8bc7086Sdrh         }
81954473229Sdrh         if( !tableSeen ){
820f5db2d3eSdrh           if( pName ){
82154473229Sdrh             sqliteSetNString(&pParse->zErrMsg, "no such table: ", -1,
82254473229Sdrh               pName->z, pName->n, 0);
823f5db2d3eSdrh           }else{
824f5db2d3eSdrh             sqliteSetString(&pParse->zErrMsg, "no tables specified", 0);
825f5db2d3eSdrh           }
82654473229Sdrh           rc = 1;
82754473229Sdrh         }
8287c917d19Sdrh       }
8297c917d19Sdrh     }
8307c917d19Sdrh     sqliteExprListDelete(pEList);
8317c917d19Sdrh     p->pEList = pNew;
832d8bc7086Sdrh   }
83354473229Sdrh   return rc;
834d8bc7086Sdrh }
835d8bc7086Sdrh 
836d8bc7086Sdrh /*
837ff78bd2fSdrh ** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
838ff78bd2fSdrh ** in a select structure.  It just sets the pointers to NULL.  This
839ff78bd2fSdrh ** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
840ff78bd2fSdrh ** pointer is not NULL, this routine is called recursively on that pointer.
841ff78bd2fSdrh **
842ff78bd2fSdrh ** This routine is called on the Select structure that defines a
843ff78bd2fSdrh ** VIEW in order to undo any bindings to tables.  This is necessary
844ff78bd2fSdrh ** because those tables might be DROPed by a subsequent SQL command.
845ff78bd2fSdrh */
846ff78bd2fSdrh void sqliteSelectUnbind(Select *p){
847ff78bd2fSdrh   int i;
848ad3cab52Sdrh   SrcList *pSrc = p->pSrc;
849ff78bd2fSdrh   Table *pTab;
850ff78bd2fSdrh   if( p==0 ) return;
851ad3cab52Sdrh   for(i=0; i<pSrc->nSrc; i++){
852ff78bd2fSdrh     if( (pTab = pSrc->a[i].pTab)!=0 ){
853ff78bd2fSdrh       if( pTab->isTransient ){
854ff78bd2fSdrh         sqliteDeleteTable(0, pTab);
855ff78bd2fSdrh         sqliteSelectDelete(pSrc->a[i].pSelect);
856ff78bd2fSdrh         pSrc->a[i].pSelect = 0;
857ff78bd2fSdrh       }
858ff78bd2fSdrh       pSrc->a[i].pTab = 0;
859ff78bd2fSdrh       if( pSrc->a[i].pSelect ){
860ff78bd2fSdrh         sqliteSelectUnbind(pSrc->a[i].pSelect);
861ff78bd2fSdrh       }
862ff78bd2fSdrh     }
863ff78bd2fSdrh   }
864ff78bd2fSdrh }
865ff78bd2fSdrh 
866ff78bd2fSdrh /*
867d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with
868d8bc7086Sdrh ** columns in a result.  For each ORDER BY expression, the opcode of
869967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of
870d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable
871d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter.
872d8bc7086Sdrh **
873d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first.  A match
874d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT.
875d8bc7086Sdrh **
876d8bc7086Sdrh ** Any entry that does not match is flagged as an error.  The number
877d8bc7086Sdrh ** of errors is returned.
878d8bc7086Sdrh */
879d8bc7086Sdrh static int matchOrderbyToColumn(
880d8bc7086Sdrh   Parse *pParse,          /* A place to leave error messages */
881d8bc7086Sdrh   Select *pSelect,        /* Match to result columns of this SELECT */
882d8bc7086Sdrh   ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
883e4de1febSdrh   int iTable,             /* Insert this value in iTable */
884d8bc7086Sdrh   int mustComplete        /* If TRUE all ORDER BYs must match */
885d8bc7086Sdrh ){
886d8bc7086Sdrh   int nErr = 0;
887d8bc7086Sdrh   int i, j;
888d8bc7086Sdrh   ExprList *pEList;
889d8bc7086Sdrh 
890daffd0e5Sdrh   if( pSelect==0 || pOrderBy==0 ) return 1;
891d8bc7086Sdrh   if( mustComplete ){
892d8bc7086Sdrh     for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
893d8bc7086Sdrh   }
894d8bc7086Sdrh   if( fillInColumnList(pParse, pSelect) ){
895d8bc7086Sdrh     return 1;
896d8bc7086Sdrh   }
897d8bc7086Sdrh   if( pSelect->pPrior ){
89892cd52f5Sdrh     if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
89992cd52f5Sdrh       return 1;
90092cd52f5Sdrh     }
901d8bc7086Sdrh   }
902d8bc7086Sdrh   pEList = pSelect->pEList;
903d8bc7086Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
904d8bc7086Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
905e4de1febSdrh     int iCol = -1;
906d8bc7086Sdrh     if( pOrderBy->a[i].done ) continue;
907e4de1febSdrh     if( sqliteExprIsInteger(pE, &iCol) ){
908e4de1febSdrh       if( iCol<=0 || iCol>pEList->nExpr ){
909e4de1febSdrh         char zBuf[200];
910e4de1febSdrh         sprintf(zBuf,"ORDER BY position %d should be between 1 and %d",
911e4de1febSdrh            iCol, pEList->nExpr);
912e4de1febSdrh         sqliteSetString(&pParse->zErrMsg, zBuf, 0);
913e4de1febSdrh         pParse->nErr++;
914e4de1febSdrh         nErr++;
915e4de1febSdrh         break;
916e4de1febSdrh       }
917e4de1febSdrh       iCol--;
918e4de1febSdrh     }
919e4de1febSdrh     for(j=0; iCol<0 && j<pEList->nExpr; j++){
9204cfa7934Sdrh       if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
921a76b5dfcSdrh         char *zName, *zLabel;
922a76b5dfcSdrh         zName = pEList->a[j].zName;
923a76b5dfcSdrh         assert( pE->token.z );
924a76b5dfcSdrh         zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
925d8bc7086Sdrh         sqliteDequote(zLabel);
926d8bc7086Sdrh         if( sqliteStrICmp(zName, zLabel)==0 ){
927e4de1febSdrh           iCol = j;
928d8bc7086Sdrh         }
9296e142f54Sdrh         sqliteFree(zLabel);
930d8bc7086Sdrh       }
931e4de1febSdrh       if( iCol<0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
932e4de1febSdrh         iCol = j;
933d8bc7086Sdrh       }
934e4de1febSdrh     }
935e4de1febSdrh     if( iCol>=0 ){
936967e8b73Sdrh       pE->op = TK_COLUMN;
937e4de1febSdrh       pE->iColumn = iCol;
938d8bc7086Sdrh       pE->iTable = iTable;
939d8bc7086Sdrh       pOrderBy->a[i].done = 1;
940d8bc7086Sdrh     }
941e4de1febSdrh     if( iCol<0 && mustComplete ){
942d8bc7086Sdrh       char zBuf[30];
943d8bc7086Sdrh       sprintf(zBuf,"%d",i+1);
944d8bc7086Sdrh       sqliteSetString(&pParse->zErrMsg, "ORDER BY term number ", zBuf,
945d8bc7086Sdrh         " does not match any result column", 0);
946d8bc7086Sdrh       pParse->nErr++;
947d8bc7086Sdrh       nErr++;
948d8bc7086Sdrh       break;
949d8bc7086Sdrh     }
950d8bc7086Sdrh   }
951d8bc7086Sdrh   return nErr;
952d8bc7086Sdrh }
953d8bc7086Sdrh 
954d8bc7086Sdrh /*
955d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
956d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
957d8bc7086Sdrh */
958d8bc7086Sdrh Vdbe *sqliteGetVdbe(Parse *pParse){
959d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
960d8bc7086Sdrh   if( v==0 ){
9614c504391Sdrh     v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
962d8bc7086Sdrh   }
963d8bc7086Sdrh   return v;
964d8bc7086Sdrh }
965d8bc7086Sdrh 
966d8bc7086Sdrh 
967d8bc7086Sdrh /*
96882c3d636Sdrh ** This routine is called to process a query that is really the union
96982c3d636Sdrh ** or intersection of two or more separate queries.
970c926afbcSdrh **
971c926afbcSdrh ** "p" points to the right-most of the two queries.  The results should
972c926afbcSdrh ** be stored in eDest with parameter iParm.
97382c3d636Sdrh */
97482c3d636Sdrh static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
97510e5e3cfSdrh   int rc;             /* Success code from a subroutine */
97610e5e3cfSdrh   Select *pPrior;     /* Another SELECT immediately to our left */
97710e5e3cfSdrh   Vdbe *v;            /* Generate code to this VDBE */
97810e5e3cfSdrh   int base;           /* Baseline value for pParse->nTab */
97982c3d636Sdrh 
980d8bc7086Sdrh   /* Make sure there is no ORDER BY clause on prior SELECTs.  Only the
981d8bc7086Sdrh   ** last SELECT in the series may have an ORDER BY.
98282c3d636Sdrh   */
983daffd0e5Sdrh   if( p==0 || p->pPrior==0 ) return 1;
984d8bc7086Sdrh   pPrior = p->pPrior;
985d8bc7086Sdrh   if( pPrior->pOrderBy ){
986d8bc7086Sdrh     sqliteSetString(&pParse->zErrMsg,"ORDER BY clause should come after ",
987d8bc7086Sdrh       selectOpName(p->op), " not before", 0);
98882c3d636Sdrh     pParse->nErr++;
98982c3d636Sdrh     return 1;
99082c3d636Sdrh   }
99182c3d636Sdrh 
992d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
993d8bc7086Sdrh   */
994d8bc7086Sdrh   v = sqliteGetVdbe(pParse);
995d8bc7086Sdrh   if( v==0 ) return 1;
996d8bc7086Sdrh 
9971cc3d75fSdrh   /* Create the destination temporary table if necessary
9981cc3d75fSdrh   */
9991cc3d75fSdrh   if( eDest==SRT_TempTable ){
10001cc3d75fSdrh     sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
10011cc3d75fSdrh     eDest = SRT_Table;
10021cc3d75fSdrh   }
10031cc3d75fSdrh 
1004f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1005d8bc7086Sdrh   */
100610e5e3cfSdrh   base = pParse->nTab;
100782c3d636Sdrh   switch( p->op ){
1008f46f905aSdrh     case TK_ALL: {
1009f46f905aSdrh       if( p->pOrderBy==0 ){
1010f46f905aSdrh         rc = sqliteSelect(pParse, pPrior, eDest, iParm, 0, 0, 0);
1011f46f905aSdrh         if( rc ) return rc;
1012f46f905aSdrh         p->pPrior = 0;
1013f46f905aSdrh         rc = sqliteSelect(pParse, p, eDest, iParm, 0, 0, 0);
1014f46f905aSdrh         p->pPrior = pPrior;
1015f46f905aSdrh         if( rc ) return rc;
1016f46f905aSdrh         break;
1017f46f905aSdrh       }
1018f46f905aSdrh       /* For UNION ALL ... ORDER BY fall through to the next case */
1019f46f905aSdrh     }
102082c3d636Sdrh     case TK_EXCEPT:
102182c3d636Sdrh     case TK_UNION: {
1022d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1023d8bc7086Sdrh       int op;          /* One of the SRT_ operations to apply to self */
1024d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
1025c926afbcSdrh       ExprList *pOrderBy;  /* The ORDER BY clause for the right SELECT */
102682c3d636Sdrh 
1027d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
1028c926afbcSdrh       if( eDest==priorOp && p->pOrderBy==0 ){
1029d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1030c926afbcSdrh         ** right.
1031d8bc7086Sdrh         */
103282c3d636Sdrh         unionTab = iParm;
103382c3d636Sdrh       }else{
1034d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1035d8bc7086Sdrh         ** intermediate results.
1036d8bc7086Sdrh         */
103782c3d636Sdrh         unionTab = pParse->nTab++;
1038d8bc7086Sdrh         if( p->pOrderBy
1039d8bc7086Sdrh         && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
1040d8bc7086Sdrh           return 1;
1041d8bc7086Sdrh         }
1042d8bc7086Sdrh         if( p->op!=TK_ALL ){
1043c6b52df3Sdrh           sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
104499fcd718Sdrh           sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
1045345fda3eSdrh         }else{
104699fcd718Sdrh           sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
104782c3d636Sdrh         }
1048d8bc7086Sdrh       }
1049d8bc7086Sdrh 
1050d8bc7086Sdrh       /* Code the SELECT statements to our left
1051d8bc7086Sdrh       */
1052832508b7Sdrh       rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
105382c3d636Sdrh       if( rc ) return rc;
1054d8bc7086Sdrh 
1055d8bc7086Sdrh       /* Code the current SELECT statement
1056d8bc7086Sdrh       */
1057d8bc7086Sdrh       switch( p->op ){
1058d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
1059d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
1060d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
1061d8bc7086Sdrh       }
106282c3d636Sdrh       p->pPrior = 0;
1063c926afbcSdrh       pOrderBy = p->pOrderBy;
1064c926afbcSdrh       p->pOrderBy = 0;
1065832508b7Sdrh       rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0);
106682c3d636Sdrh       p->pPrior = pPrior;
1067c926afbcSdrh       p->pOrderBy = pOrderBy;
106882c3d636Sdrh       if( rc ) return rc;
1069d8bc7086Sdrh 
1070d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1071d8bc7086Sdrh       ** it is that we currently need.
1072d8bc7086Sdrh       */
1073c926afbcSdrh       if( eDest!=priorOp || unionTab!=iParm ){
10746b56344dSdrh         int iCont, iBreak, iStart;
107582c3d636Sdrh         assert( p->pEList );
107641202ccaSdrh         if( eDest==SRT_Callback ){
1077832508b7Sdrh           generateColumnNames(pParse, p->base, 0, p->pEList);
107841202ccaSdrh         }
107982c3d636Sdrh         iBreak = sqliteVdbeMakeLabel(v);
10806b56344dSdrh         iCont = sqliteVdbeMakeLabel(v);
10816b56344dSdrh         sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
10826b56344dSdrh         iStart = sqliteVdbeCurrentAddr(v);
1083df199a25Sdrh         rc = selectInnerLoop(pParse, p, 0, unionTab, p->pEList->nExpr,
1084d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
108582c3d636Sdrh                              iCont, iBreak);
108682c3d636Sdrh         if( rc ) return 1;
10876b56344dSdrh         sqliteVdbeResolveLabel(v, iCont);
10886b56344dSdrh         sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
108999fcd718Sdrh         sqliteVdbeResolveLabel(v, iBreak);
109099fcd718Sdrh         sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
1091d8bc7086Sdrh         if( p->pOrderBy ){
1092c926afbcSdrh           generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
1093d8bc7086Sdrh         }
109482c3d636Sdrh       }
109582c3d636Sdrh       break;
109682c3d636Sdrh     }
109782c3d636Sdrh     case TK_INTERSECT: {
109882c3d636Sdrh       int tab1, tab2;
10996b56344dSdrh       int iCont, iBreak, iStart;
110082c3d636Sdrh 
1101d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
11026206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
1103d8bc7086Sdrh       ** by allocating the tables we will need.
1104d8bc7086Sdrh       */
110582c3d636Sdrh       tab1 = pParse->nTab++;
110682c3d636Sdrh       tab2 = pParse->nTab++;
1107d8bc7086Sdrh       if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
1108d8bc7086Sdrh         return 1;
1109d8bc7086Sdrh       }
1110c6b52df3Sdrh       sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
111199fcd718Sdrh       sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
1112d8bc7086Sdrh 
1113d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1114d8bc7086Sdrh       */
1115832508b7Sdrh       rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
111682c3d636Sdrh       if( rc ) return rc;
1117d8bc7086Sdrh 
1118d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1119d8bc7086Sdrh       */
1120c6b52df3Sdrh       sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
112199fcd718Sdrh       sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
112282c3d636Sdrh       p->pPrior = 0;
1123832508b7Sdrh       rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0);
112482c3d636Sdrh       p->pPrior = pPrior;
112582c3d636Sdrh       if( rc ) return rc;
1126d8bc7086Sdrh 
1127d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1128d8bc7086Sdrh       ** tables.
1129d8bc7086Sdrh       */
113082c3d636Sdrh       assert( p->pEList );
113141202ccaSdrh       if( eDest==SRT_Callback ){
1132832508b7Sdrh         generateColumnNames(pParse, p->base, 0, p->pEList);
113341202ccaSdrh       }
113482c3d636Sdrh       iBreak = sqliteVdbeMakeLabel(v);
11356b56344dSdrh       iCont = sqliteVdbeMakeLabel(v);
11366b56344dSdrh       sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
11376b56344dSdrh       iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
113899fcd718Sdrh       sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
1139df199a25Sdrh       rc = selectInnerLoop(pParse, p, 0, tab1, p->pEList->nExpr,
1140d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
114182c3d636Sdrh                              iCont, iBreak);
114282c3d636Sdrh       if( rc ) return 1;
11436b56344dSdrh       sqliteVdbeResolveLabel(v, iCont);
11446b56344dSdrh       sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
114599fcd718Sdrh       sqliteVdbeResolveLabel(v, iBreak);
114699fcd718Sdrh       sqliteVdbeAddOp(v, OP_Close, tab2, 0);
114799fcd718Sdrh       sqliteVdbeAddOp(v, OP_Close, tab1, 0);
1148d8bc7086Sdrh       if( p->pOrderBy ){
1149c926afbcSdrh         generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
1150d8bc7086Sdrh       }
115182c3d636Sdrh       break;
115282c3d636Sdrh     }
115382c3d636Sdrh   }
115482c3d636Sdrh   assert( p->pEList && pPrior->pEList );
115582c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
1156d8bc7086Sdrh     sqliteSetString(&pParse->zErrMsg, "SELECTs to the left and right of ",
1157d8bc7086Sdrh       selectOpName(p->op), " do not have the same number of result columns", 0);
115882c3d636Sdrh     pParse->nErr++;
115982c3d636Sdrh     return 1;
11602282792aSdrh   }
116110e5e3cfSdrh   pParse->nTab = base;
11622282792aSdrh   return 0;
11632282792aSdrh }
11642282792aSdrh 
11652282792aSdrh /*
1166832508b7Sdrh ** Recursively scan through an expression tree.  For every reference
1167832508b7Sdrh ** to a column in table number iFrom, change that reference to the
1168832508b7Sdrh ** same column in table number iTo.
1169832508b7Sdrh */
1170832508b7Sdrh static void changeTables(Expr *pExpr, int iFrom, int iTo){
1171832508b7Sdrh   if( pExpr==0 ) return;
1172832508b7Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iFrom ){
1173832508b7Sdrh     pExpr->iTable = iTo;
1174832508b7Sdrh   }else{
11751b2e0329Sdrh     static void changeTablesInList(ExprList*, int, int);
1176832508b7Sdrh     changeTables(pExpr->pLeft, iFrom, iTo);
1177832508b7Sdrh     changeTables(pExpr->pRight, iFrom, iTo);
11781b2e0329Sdrh     changeTablesInList(pExpr->pList, iFrom, iTo);
1179832508b7Sdrh   }
1180832508b7Sdrh }
11811b2e0329Sdrh static void changeTablesInList(ExprList *pList, int iFrom, int iTo){
11821b2e0329Sdrh   if( pList ){
11831b2e0329Sdrh     int i;
11841b2e0329Sdrh     for(i=0; i<pList->nExpr; i++){
11851b2e0329Sdrh       changeTables(pList->a[i].pExpr, iFrom, iTo);
11861b2e0329Sdrh     }
1187832508b7Sdrh   }
1188832508b7Sdrh }
1189832508b7Sdrh 
1190832508b7Sdrh /*
1191832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
1192832508b7Sdrh ** a column in table number iTable with a copy of the corresponding
119384e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
119484e59207Sdrh ** unchanged.)  When making a copy of an expression in pEList, change
119584e59207Sdrh ** references to columns in table iSub into references to table iTable.
1196832508b7Sdrh **
1197832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
1198832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
1199832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
1200832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
1201832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
1202832508b7Sdrh ** of the subquery rather the result set of the subquery.
1203832508b7Sdrh */
1204832508b7Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList, int iSub){
1205832508b7Sdrh   if( pExpr==0 ) return;
120684e59207Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable && pExpr->iColumn>=0 ){
1207832508b7Sdrh     Expr *pNew;
120884e59207Sdrh     assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1209832508b7Sdrh     assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1210832508b7Sdrh     pNew = pEList->a[pExpr->iColumn].pExpr;
1211832508b7Sdrh     assert( pNew!=0 );
1212832508b7Sdrh     pExpr->op = pNew->op;
1213832508b7Sdrh     pExpr->pLeft = sqliteExprDup(pNew->pLeft);
1214832508b7Sdrh     pExpr->pRight = sqliteExprDup(pNew->pRight);
1215832508b7Sdrh     pExpr->pList = sqliteExprListDup(pNew->pList);
1216832508b7Sdrh     pExpr->iTable = pNew->iTable;
1217832508b7Sdrh     pExpr->iColumn = pNew->iColumn;
1218832508b7Sdrh     pExpr->iAgg = pNew->iAgg;
12191b2e0329Sdrh     pExpr->token = pNew->token;
1220832508b7Sdrh     if( iSub!=iTable ){
1221832508b7Sdrh       changeTables(pExpr, iSub, iTable);
1222832508b7Sdrh     }
1223832508b7Sdrh   }else{
1224832508b7Sdrh     static void substExprList(ExprList*,int,ExprList*,int);
1225832508b7Sdrh     substExpr(pExpr->pLeft, iTable, pEList, iSub);
1226832508b7Sdrh     substExpr(pExpr->pRight, iTable, pEList, iSub);
1227832508b7Sdrh     substExprList(pExpr->pList, iTable, pEList, iSub);
1228832508b7Sdrh   }
1229832508b7Sdrh }
1230832508b7Sdrh static void
1231832508b7Sdrh substExprList(ExprList *pList, int iTable, ExprList *pEList, int iSub){
1232832508b7Sdrh   int i;
1233832508b7Sdrh   if( pList==0 ) return;
1234832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
1235832508b7Sdrh     substExpr(pList->a[i].pExpr, iTable, pEList, iSub);
1236832508b7Sdrh   }
1237832508b7Sdrh }
1238832508b7Sdrh 
1239832508b7Sdrh /*
12401350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
12411350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
12421350b030Sdrh ** occurs.
12431350b030Sdrh **
12441350b030Sdrh ** To understand the concept of flattening, consider the following
12451350b030Sdrh ** query:
12461350b030Sdrh **
12471350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
12481350b030Sdrh **
12491350b030Sdrh ** The default way of implementing this query is to execute the
12501350b030Sdrh ** subquery first and store the results in a temporary table, then
12511350b030Sdrh ** run the outer query on that temporary table.  This requires two
12521350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
12531350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
1254832508b7Sdrh ** optimized.
12551350b030Sdrh **
1256832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
12571350b030Sdrh ** a single flat select, like this:
12581350b030Sdrh **
12591350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
12601350b030Sdrh **
12611350b030Sdrh ** The code generated for this simpification gives the same result
1262832508b7Sdrh ** but only has to scan the data once.  And because indices might
1263832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
1264832508b7Sdrh ** avoided.
12651350b030Sdrh **
1266832508b7Sdrh ** Flattening is only attempted if all of the following are true:
12671350b030Sdrh **
1268832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
12691350b030Sdrh **
1270832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
1271832508b7Sdrh **
1272832508b7Sdrh **   (3)  The subquery is not a join.
1273832508b7Sdrh **
1274832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
1275832508b7Sdrh **
1276832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
1277832508b7Sdrh **        aggregates.
1278832508b7Sdrh **
1279832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
1280832508b7Sdrh **        DISTINCT.
1281832508b7Sdrh **
128208192d5fSdrh **   (7)  The subquery has a FROM clause.
128308192d5fSdrh **
1284df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
1285df199a25Sdrh **
1286df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
1287df199a25Sdrh **        aggregates.
1288df199a25Sdrh **
1289df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
1290df199a25Sdrh **        use LIMIT.
1291df199a25Sdrh **
1292832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
1293832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
1294832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1295832508b7Sdrh **
1296832508b7Sdrh ** If flattening is not attempted, this routine is a no-op and return 0.
1297832508b7Sdrh ** If flattening is attempted this routine returns 1.
1298832508b7Sdrh **
1299832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
1300832508b7Sdrh ** the subquery before this routine runs.
13011350b030Sdrh */
1302832508b7Sdrh int flattenSubquery(Select *p, int iFrom, int isAgg, int subqueryIsAgg){
13030bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
1304ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
1305ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
13060bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
1307832508b7Sdrh   int i;
1308832508b7Sdrh   int iParent, iSub;
1309832508b7Sdrh   Expr *pWhere;
13101350b030Sdrh 
1311832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
1312832508b7Sdrh   */
1313832508b7Sdrh   if( p==0 ) return 0;
1314832508b7Sdrh   pSrc = p->pSrc;
1315ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
1316832508b7Sdrh   pSub = pSrc->a[iFrom].pSelect;
1317832508b7Sdrh   assert( pSub!=0 );
1318832508b7Sdrh   if( isAgg && subqueryIsAgg ) return 0;
1319ad3cab52Sdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
1320832508b7Sdrh   pSubSrc = pSub->pSrc;
1321832508b7Sdrh   assert( pSubSrc );
1322ad3cab52Sdrh   if( pSubSrc->nSrc!=1 ) return 0;
1323df199a25Sdrh   if( (pSub->isDistinct || pSub->nLimit>=0) &&  (pSrc->nSrc>1 || isAgg) ){
1324df199a25Sdrh      return 0;
1325df199a25Sdrh   }
1326d11d382cSdrh   if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
1327832508b7Sdrh 
13280bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
1329832508b7Sdrh   ** i-th entry of the FROM clause in the outer query.
1330832508b7Sdrh   */
1331832508b7Sdrh   iParent = p->base + iFrom;
1332832508b7Sdrh   iSub = pSub->base;
1333832508b7Sdrh   substExprList(p->pEList, iParent, pSub->pEList, iSub);
1334832508b7Sdrh   pList = p->pEList;
1335832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
1336832508b7Sdrh     if( pList->a[i].zName==0 ){
1337832508b7Sdrh       Expr *pExpr = pList->a[i].pExpr;
1338832508b7Sdrh       pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
1339832508b7Sdrh     }
1340832508b7Sdrh   }
13411b2e0329Sdrh   if( isAgg ){
1342832508b7Sdrh     substExprList(p->pGroupBy, iParent, pSub->pEList, iSub);
1343832508b7Sdrh     substExpr(p->pHaving, iParent, pSub->pEList, iSub);
13441b2e0329Sdrh   }
1345832508b7Sdrh   substExprList(p->pOrderBy, iParent, pSub->pEList, iSub);
1346832508b7Sdrh   if( pSub->pWhere ){
1347832508b7Sdrh     pWhere = sqliteExprDup(pSub->pWhere);
1348832508b7Sdrh     if( iParent!=iSub ){
1349832508b7Sdrh       changeTables(pWhere, iSub, iParent);
1350832508b7Sdrh     }
1351832508b7Sdrh   }else{
1352832508b7Sdrh     pWhere = 0;
1353832508b7Sdrh   }
1354832508b7Sdrh   if( subqueryIsAgg ){
1355832508b7Sdrh     assert( p->pHaving==0 );
13561b2e0329Sdrh     p->pHaving = p->pWhere;
13571b2e0329Sdrh     p->pWhere = pWhere;
1358832508b7Sdrh     substExpr(p->pHaving, iParent, pSub->pEList, iSub);
13591b2e0329Sdrh     if( pSub->pHaving ){
13601b2e0329Sdrh       Expr *pHaving = sqliteExprDup(pSub->pHaving);
13611b2e0329Sdrh       if( iParent!=iSub ){
13621b2e0329Sdrh         changeTables(pHaving, iSub, iParent);
13631b2e0329Sdrh       }
13641b2e0329Sdrh       if( p->pHaving ){
13651b2e0329Sdrh         p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0);
13661b2e0329Sdrh       }else{
13671b2e0329Sdrh         p->pHaving = pHaving;
13681b2e0329Sdrh       }
13691b2e0329Sdrh     }
13701b2e0329Sdrh     assert( p->pGroupBy==0 );
13711b2e0329Sdrh     p->pGroupBy = sqliteExprListDup(pSub->pGroupBy);
13721b2e0329Sdrh     if( iParent!=iSub ){
13731b2e0329Sdrh       changeTablesInList(p->pGroupBy, iSub, iParent);
13741b2e0329Sdrh     }
1375832508b7Sdrh   }else if( p->pWhere==0 ){
1376832508b7Sdrh     p->pWhere = pWhere;
1377832508b7Sdrh   }else{
1378832508b7Sdrh     substExpr(p->pWhere, iParent, pSub->pEList, iSub);
1379832508b7Sdrh     if( pWhere ){
1380832508b7Sdrh       p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0);
1381832508b7Sdrh     }
1382832508b7Sdrh   }
1383832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
1384df199a25Sdrh   if( pSub->nLimit>=0 ){
1385df199a25Sdrh     if( p->nLimit<0 ){
1386df199a25Sdrh       p->nLimit = pSub->nLimit;
1387df199a25Sdrh     }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1388df199a25Sdrh       p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1389df199a25Sdrh     }
1390df199a25Sdrh   }
1391df199a25Sdrh   p->nOffset += pSub->nOffset;
1392832508b7Sdrh   if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
1393832508b7Sdrh     sqliteDeleteTable(0, pSrc->a[iFrom].pTab);
1394832508b7Sdrh   }
1395832508b7Sdrh   pSrc->a[iFrom].pTab = pSubSrc->a[0].pTab;
1396832508b7Sdrh   pSubSrc->a[0].pTab = 0;
1397832508b7Sdrh   pSrc->a[iFrom].pSelect = pSubSrc->a[0].pSelect;
1398832508b7Sdrh   pSubSrc->a[0].pSelect = 0;
1399832508b7Sdrh   sqliteSelectDelete(pSub);
1400832508b7Sdrh   return 1;
14011350b030Sdrh }
14021350b030Sdrh 
14031350b030Sdrh /*
14049562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it
14059562b551Sdrh ** is a simple min() or max() query.  If it is and this query can be
14069562b551Sdrh ** satisfied using a single seek to the beginning or end of an index,
14079562b551Sdrh ** then generate the code for this SELECT return 1.  If this is not a
14089562b551Sdrh ** simple min() or max() query, then return 0;
14099562b551Sdrh **
14109562b551Sdrh ** A simply min() or max() query looks like this:
14119562b551Sdrh **
14129562b551Sdrh **    SELECT min(a) FROM table;
14139562b551Sdrh **    SELECT max(a) FROM table;
14149562b551Sdrh **
14159562b551Sdrh ** The query may have only a single table in its FROM argument.  There
14169562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
14179562b551Sdrh ** be the min() or max() of a single column of the table.  The column
14189562b551Sdrh ** in the min() or max() function must be indexed.
14199562b551Sdrh **
14209562b551Sdrh ** The parameters to this routine are the same as for sqliteSelect().
14219562b551Sdrh ** See the header comment on that routine for additional information.
14229562b551Sdrh */
14239562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
14249562b551Sdrh   Expr *pExpr;
14259562b551Sdrh   int iCol;
14269562b551Sdrh   Table *pTab;
14279562b551Sdrh   Index *pIdx;
14289562b551Sdrh   int base;
14299562b551Sdrh   Vdbe *v;
14309562b551Sdrh   int openOp;
14319562b551Sdrh   int seekOp;
14329562b551Sdrh   int cont;
14339562b551Sdrh   ExprList eList;
14349562b551Sdrh   struct ExprList_item eListItem;
14359562b551Sdrh 
14369562b551Sdrh   /* Check to see if this query is a simple min() or max() query.  Return
14379562b551Sdrh   ** zero if it is  not.
14389562b551Sdrh   */
14399562b551Sdrh   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
1440ad3cab52Sdrh   if( p->pSrc->nSrc!=1 ) return 0;
14419562b551Sdrh   if( p->pEList->nExpr!=1 ) return 0;
14429562b551Sdrh   pExpr = p->pEList->a[0].pExpr;
14439562b551Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
14449562b551Sdrh   if( pExpr->pList==0 || pExpr->pList->nExpr!=1 ) return 0;
14450bce8354Sdrh   if( pExpr->token.n!=3 ) return 0;
14460bce8354Sdrh   if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){
14470bce8354Sdrh     seekOp = OP_Rewind;
14480bce8354Sdrh   }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){
14490bce8354Sdrh     seekOp = OP_Last;
14500bce8354Sdrh   }else{
14510bce8354Sdrh     return 0;
14520bce8354Sdrh   }
14539562b551Sdrh   pExpr = pExpr->pList->a[0].pExpr;
14549562b551Sdrh   if( pExpr->op!=TK_COLUMN ) return 0;
14559562b551Sdrh   iCol = pExpr->iColumn;
14569562b551Sdrh   pTab = p->pSrc->a[0].pTab;
14579562b551Sdrh 
14589562b551Sdrh   /* If we get to here, it means the query is of the correct form.
145917f71934Sdrh   ** Check to make sure we have an index and make pIdx point to the
146017f71934Sdrh   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
146117f71934Sdrh   ** key column, no index is necessary so set pIdx to NULL.  If no
146217f71934Sdrh   ** usable index is found, return 0.
14639562b551Sdrh   */
14649562b551Sdrh   if( iCol<0 ){
14659562b551Sdrh     pIdx = 0;
14669562b551Sdrh   }else{
14679562b551Sdrh     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
14689562b551Sdrh       assert( pIdx->nColumn>=1 );
14699562b551Sdrh       if( pIdx->aiColumn[0]==iCol ) break;
14709562b551Sdrh     }
14719562b551Sdrh     if( pIdx==0 ) return 0;
14729562b551Sdrh   }
14739562b551Sdrh 
147417f71934Sdrh   /* Identify column names if we will be using the callback.  This
14759562b551Sdrh   ** step is skipped if the output is going to a table or a memory cell.
14769562b551Sdrh   */
14779562b551Sdrh   v = sqliteGetVdbe(pParse);
14789562b551Sdrh   if( v==0 ) return 0;
14799562b551Sdrh   if( eDest==SRT_Callback ){
1480832508b7Sdrh     generateColumnNames(pParse, p->base, p->pSrc, p->pEList);
14819562b551Sdrh   }
14829562b551Sdrh 
148317f71934Sdrh   /* Generating code to find the min or the max.  Basically all we have
148417f71934Sdrh   ** to do is find the first or the last entry in the chosen index.  If
148517f71934Sdrh   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
148617f71934Sdrh   ** or last entry in the main table.
14879562b551Sdrh   */
14885cf8e8c7Sdrh   if( !pParse->schemaVerified && (pParse->db->flags & SQLITE_InTrans)==0 ){
14895cf8e8c7Sdrh     sqliteVdbeAddOp(v, OP_VerifyCookie, pParse->db->schema_cookie, 0);
14905cf8e8c7Sdrh     pParse->schemaVerified = 1;
14915cf8e8c7Sdrh   }
14929562b551Sdrh   openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
1493832508b7Sdrh   base = p->base;
14949562b551Sdrh   sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
14955cf8e8c7Sdrh   sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
14969562b551Sdrh   if( pIdx==0 ){
14979562b551Sdrh     sqliteVdbeAddOp(v, seekOp, base, 0);
14989562b551Sdrh   }else{
14999562b551Sdrh     sqliteVdbeAddOp(v, openOp, base+1, pIdx->tnum);
15005cf8e8c7Sdrh     sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
15019562b551Sdrh     sqliteVdbeAddOp(v, seekOp, base+1, 0);
15029562b551Sdrh     sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
15039562b551Sdrh     sqliteVdbeAddOp(v, OP_Close, base+1, 0);
15049562b551Sdrh     sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
15059562b551Sdrh   }
15065cf8e8c7Sdrh   eList.nExpr = 1;
15075cf8e8c7Sdrh   memset(&eListItem, 0, sizeof(eListItem));
15085cf8e8c7Sdrh   eList.a = &eListItem;
15095cf8e8c7Sdrh   eList.a[0].pExpr = pExpr;
15109562b551Sdrh   cont = sqliteVdbeMakeLabel(v);
1511df199a25Sdrh   selectInnerLoop(pParse, p, &eList, base, 1, 0, -1, eDest, iParm, cont, cont);
15129562b551Sdrh   sqliteVdbeResolveLabel(v, cont);
15139562b551Sdrh   sqliteVdbeAddOp(v, OP_Close, base, 0);
15149562b551Sdrh   return 1;
15159562b551Sdrh }
15169562b551Sdrh 
15179562b551Sdrh /*
15189bb61fe7Sdrh ** Generate code for the given SELECT statement.
15199bb61fe7Sdrh **
1520fef5208cSdrh ** The results are distributed in various ways depending on the
1521fef5208cSdrh ** value of eDest and iParm.
1522fef5208cSdrh **
1523fef5208cSdrh **     eDest Value       Result
1524fef5208cSdrh **     ------------    -------------------------------------------
1525fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
1526fef5208cSdrh **
1527fef5208cSdrh **     SRT_Mem         Store first result in memory cell iParm
1528fef5208cSdrh **
1529fef5208cSdrh **     SRT_Set         Store results as keys of a table with cursor iParm
1530fef5208cSdrh **
153182c3d636Sdrh **     SRT_Union       Store results as a key in a temporary table iParm
153282c3d636Sdrh **
1533c4a3c779Sdrh **     SRT_Except      Remove results form the temporary table iParm.
1534c4a3c779Sdrh **
1535c4a3c779Sdrh **     SRT_Table       Store results in temporary table iParm
15369bb61fe7Sdrh **
15379bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
15389bb61fe7Sdrh ** encountered, then an appropriate error message is left in
15399bb61fe7Sdrh ** pParse->zErrMsg.
15409bb61fe7Sdrh **
15419bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
15429bb61fe7Sdrh ** calling function needs to do that.
15431b2e0329Sdrh **
15441b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
15451b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
15461b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
15471b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
15481b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
15491b2e0329Sdrh ** can be changed.
15509bb61fe7Sdrh */
15519bb61fe7Sdrh int sqliteSelect(
1552cce7d176Sdrh   Parse *pParse,         /* The parser context */
15539bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
155482c3d636Sdrh   int eDest,             /* One of: SRT_Callback Mem Set Union Except */
1555832508b7Sdrh   int iParm,             /* Save result in this memory location, if >=0 */
1556832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
1557832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
15581b2e0329Sdrh   int *pParentAgg        /* True if pParent uses aggregate functions */
1559cce7d176Sdrh ){
1560d8bc7086Sdrh   int i;
1561cce7d176Sdrh   WhereInfo *pWInfo;
1562cce7d176Sdrh   Vdbe *v;
1563cce7d176Sdrh   int isAgg = 0;         /* True for select lists like "count(*)" */
1564a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
1565ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
15669bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
15679bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
15682282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
15692282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
157019a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
157119a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
157210e5e3cfSdrh   int base;              /* First cursor available for use */
15731d83f052Sdrh   int rc = 1;            /* Value to return from this function */
15749bb61fe7Sdrh 
1575daffd0e5Sdrh   if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
1576daffd0e5Sdrh 
157782c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
157882c3d636Sdrh   */
157982c3d636Sdrh   if( p->pPrior ){
158082c3d636Sdrh     return multiSelect(pParse, p, eDest, iParm);
158182c3d636Sdrh   }
158282c3d636Sdrh 
158382c3d636Sdrh   /* Make local copies of the parameters for this query.
158482c3d636Sdrh   */
15859bb61fe7Sdrh   pTabList = p->pSrc;
15869bb61fe7Sdrh   pWhere = p->pWhere;
15879bb61fe7Sdrh   pOrderBy = p->pOrderBy;
15882282792aSdrh   pGroupBy = p->pGroupBy;
15892282792aSdrh   pHaving = p->pHaving;
159019a775c2Sdrh   isDistinct = p->isDistinct;
15919bb61fe7Sdrh 
1592832508b7Sdrh   /* Allocate a block of VDBE cursors, one for each table in the FROM clause.
1593832508b7Sdrh   ** The WHERE processing requires that the cursors for the tables in the
1594832508b7Sdrh   ** FROM clause be consecutive.
159510e5e3cfSdrh   */
1596832508b7Sdrh   base = p->base = pParse->nTab;
1597ad3cab52Sdrh   pParse->nTab += pTabList->nSrc;
159810e5e3cfSdrh 
15999bb61fe7Sdrh   /*
16009bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
16019bb61fe7Sdrh   ** errors before this routine starts.
16029bb61fe7Sdrh   */
16031d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
1604cce7d176Sdrh 
1605d8bc7086Sdrh   /* Look up every table in the table list and create an appropriate
1606d8bc7086Sdrh   ** columnlist in pEList if there isn't one already.  (The parser leaves
1607967e8b73Sdrh   ** a NULL in the p->pEList if the SQL said "SELECT * FROM ...")
1608cce7d176Sdrh   */
1609d8bc7086Sdrh   if( fillInColumnList(pParse, p) ){
16101d83f052Sdrh     goto select_end;
1611cce7d176Sdrh   }
1612ad2d8307Sdrh   pWhere = p->pWhere;
1613d8bc7086Sdrh   pEList = p->pEList;
16141d83f052Sdrh   if( pEList==0 ) goto select_end;
1615cce7d176Sdrh 
16162282792aSdrh   /* If writing to memory or generating a set
16172282792aSdrh   ** only a single column may be output.
161819a775c2Sdrh   */
1619fef5208cSdrh   if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
162019a775c2Sdrh     sqliteSetString(&pParse->zErrMsg, "only a single result allowed for "
162119a775c2Sdrh        "a SELECT that is part of an expression", 0);
162219a775c2Sdrh     pParse->nErr++;
16231d83f052Sdrh     goto select_end;
162419a775c2Sdrh   }
162519a775c2Sdrh 
1626c926afbcSdrh   /* ORDER BY is ignored for some destinations.
16272282792aSdrh   */
1628c926afbcSdrh   switch( eDest ){
1629c926afbcSdrh     case SRT_Union:
1630c926afbcSdrh     case SRT_Except:
1631c926afbcSdrh     case SRT_Discard:
1632acd4c695Sdrh       pOrderBy = 0;
1633c926afbcSdrh       break;
1634c926afbcSdrh     default:
1635c926afbcSdrh       break;
16362282792aSdrh   }
16372282792aSdrh 
163810e5e3cfSdrh   /* At this point, we should have allocated all the cursors that we
1639832508b7Sdrh   ** need to handle subquerys and temporary tables.
164010e5e3cfSdrh   **
1641967e8b73Sdrh   ** Resolve the column names and do a semantics check on all the expressions.
16422282792aSdrh   */
16434794b980Sdrh   for(i=0; i<pEList->nExpr; i++){
1644832508b7Sdrh     if( sqliteExprResolveIds(pParse, base, pTabList, 0, pEList->a[i].pExpr) ){
16451d83f052Sdrh       goto select_end;
1646cce7d176Sdrh     }
16472282792aSdrh     if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
16481d83f052Sdrh       goto select_end;
1649cce7d176Sdrh     }
1650cce7d176Sdrh   }
1651cce7d176Sdrh   if( pWhere ){
1652832508b7Sdrh     if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pWhere) ){
16531d83f052Sdrh       goto select_end;
1654cce7d176Sdrh     }
1655cce7d176Sdrh     if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
16561d83f052Sdrh       goto select_end;
1657cce7d176Sdrh     }
1658cce7d176Sdrh   }
1659cce7d176Sdrh   if( pOrderBy ){
1660cce7d176Sdrh     for(i=0; i<pOrderBy->nExpr; i++){
16612282792aSdrh       Expr *pE = pOrderBy->a[i].pExpr;
16629208643dSdrh       if( sqliteExprIsConstant(pE) ){
1663e4de1febSdrh         int iCol;
1664e4de1febSdrh         if( sqliteExprIsInteger(pE, &iCol)==0 ){
16659208643dSdrh           sqliteSetString(&pParse->zErrMsg,
1666e4de1febSdrh                "ORDER BY terms must not be non-integer constants", 0);
16679208643dSdrh           pParse->nErr++;
16681d83f052Sdrh           goto select_end;
1669e4de1febSdrh         }else if( iCol<=0 || iCol>pEList->nExpr ){
1670e4de1febSdrh           char zBuf[2000];
1671e4de1febSdrh           sprintf(zBuf,"ORDER BY column number %d out of range - should be "
1672e4de1febSdrh              "between 1 and %d", iCol, pEList->nExpr);
1673e4de1febSdrh           sqliteSetString(&pParse->zErrMsg, zBuf, 0);
1674e4de1febSdrh           pParse->nErr++;
1675e4de1febSdrh           goto select_end;
1676e4de1febSdrh         }
1677e4de1febSdrh         sqliteExprDelete(pE);
1678e4de1febSdrh         pE = pOrderBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
16799208643dSdrh       }
1680832508b7Sdrh       if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
16811d83f052Sdrh         goto select_end;
1682cce7d176Sdrh       }
16832282792aSdrh       if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
16841d83f052Sdrh         goto select_end;
1685cce7d176Sdrh       }
1686cce7d176Sdrh     }
1687cce7d176Sdrh   }
16882282792aSdrh   if( pGroupBy ){
16892282792aSdrh     for(i=0; i<pGroupBy->nExpr; i++){
16902282792aSdrh       Expr *pE = pGroupBy->a[i].pExpr;
16919208643dSdrh       if( sqliteExprIsConstant(pE) ){
16929208643dSdrh         sqliteSetString(&pParse->zErrMsg,
16939208643dSdrh              "GROUP BY expressions should not be constant", 0);
16949208643dSdrh         pParse->nErr++;
16951d83f052Sdrh         goto select_end;
16969208643dSdrh       }
1697832508b7Sdrh       if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
16981d83f052Sdrh         goto select_end;
16992282792aSdrh       }
17002282792aSdrh       if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
17011d83f052Sdrh         goto select_end;
17022282792aSdrh       }
17032282792aSdrh     }
17042282792aSdrh   }
17052282792aSdrh   if( pHaving ){
17062282792aSdrh     if( pGroupBy==0 ){
1707da93281eSdrh       sqliteSetString(&pParse->zErrMsg, "a GROUP BY clause is required "
1708da93281eSdrh          "before HAVING", 0);
17092282792aSdrh       pParse->nErr++;
17101d83f052Sdrh       goto select_end;
17112282792aSdrh     }
1712832508b7Sdrh     if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pHaving) ){
17131d83f052Sdrh       goto select_end;
17142282792aSdrh     }
1715da93281eSdrh     if( sqliteExprCheck(pParse, pHaving, isAgg, 0) ){
17161d83f052Sdrh       goto select_end;
17172282792aSdrh     }
1718cce7d176Sdrh   }
1719cce7d176Sdrh 
17209562b551Sdrh   /* Check for the special case of a min() or max() function by itself
17219562b551Sdrh   ** in the result set.
17229562b551Sdrh   */
17239562b551Sdrh   if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
17245cf8e8c7Sdrh     rc = 0;
17259562b551Sdrh     goto select_end;
17269562b551Sdrh   }
17279562b551Sdrh 
1728d820cb1bSdrh   /* Begin generating code.
1729d820cb1bSdrh   */
1730d820cb1bSdrh   v = sqliteGetVdbe(pParse);
1731d820cb1bSdrh   if( v==0 ) goto select_end;
1732d820cb1bSdrh 
17330bb28106Sdrh   /* Identify column names if we will be using in the callback.  This
17340bb28106Sdrh   ** step is skipped if the output is going to a table or a memory cell.
17350bb28106Sdrh   */
17360bb28106Sdrh   if( eDest==SRT_Callback ){
17370bb28106Sdrh     generateColumnNames(pParse, p->base, pTabList, pEList);
17380bb28106Sdrh   }
17390bb28106Sdrh 
17400bb28106Sdrh   /* Set the limiter
17410bb28106Sdrh   */
17420bb28106Sdrh   if( p->nLimit<=0 ){
1743d11d382cSdrh     p->nLimit = -1;
17440bb28106Sdrh     p->nOffset = 0;
17450bb28106Sdrh   }else{
1746d11d382cSdrh     int iMem = pParse->nMem++;
1747d11d382cSdrh     sqliteVdbeAddOp(v, OP_Integer, -p->nLimit, 0);
1748*bf5cd97eSdrh     sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
1749d11d382cSdrh     p->nLimit = iMem;
1750d11d382cSdrh     if( p->nOffset<=0 ){
1751d11d382cSdrh       p->nOffset = 0;
1752d11d382cSdrh     }else{
1753d11d382cSdrh       iMem = pParse->nMem++;
1754d11d382cSdrh       sqliteVdbeAddOp(v, OP_Integer, -p->nOffset, 0);
1755*bf5cd97eSdrh       sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
1756d11d382cSdrh       p->nOffset = iMem;
1757d11d382cSdrh     }
17580bb28106Sdrh   }
17590bb28106Sdrh 
1760d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
1761d820cb1bSdrh   */
1762ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
1763a76b5dfcSdrh     if( pTabList->a[i].pSelect==0 ) continue;
17642d0794e3Sdrh     sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable, base+i,
17651b2e0329Sdrh                  p, i, &isAgg);
1766832508b7Sdrh     pTabList = p->pSrc;
1767832508b7Sdrh     pWhere = p->pWhere;
1768acd4c695Sdrh     if( eDest==SRT_Callback ){
1769832508b7Sdrh       pOrderBy = p->pOrderBy;
1770acd4c695Sdrh     }
1771832508b7Sdrh     pGroupBy = p->pGroupBy;
1772832508b7Sdrh     pHaving = p->pHaving;
1773832508b7Sdrh     isDistinct = p->isDistinct;
17741b2e0329Sdrh   }
17751b2e0329Sdrh 
17761b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
17771b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
17781b2e0329Sdrh   */
17791b2e0329Sdrh   if( pParent && pParentAgg &&
17801b2e0329Sdrh       flattenSubquery(pParent, parentTab, *pParentAgg, isAgg) ){
17811b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
17821b2e0329Sdrh     return rc;
17831b2e0329Sdrh   }
1784832508b7Sdrh 
17852d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
17862d0794e3Sdrh   */
17872d0794e3Sdrh   if( eDest==SRT_TempTable ){
17882d0794e3Sdrh     sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
17892d0794e3Sdrh   }
17902d0794e3Sdrh 
17912282792aSdrh   /* Do an analysis of aggregate expressions.
1792efb7251dSdrh   */
1793d820cb1bSdrh   sqliteAggregateInfoReset(pParse);
17942282792aSdrh   if( isAgg ){
17950bce8354Sdrh     assert( pParse->nAgg==0 );
17962282792aSdrh     for(i=0; i<pEList->nExpr; i++){
17972282792aSdrh       if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
17981d83f052Sdrh         goto select_end;
17992282792aSdrh       }
18002282792aSdrh     }
18012282792aSdrh     if( pGroupBy ){
18022282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
18032282792aSdrh         if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
18041d83f052Sdrh           goto select_end;
18052282792aSdrh         }
18062282792aSdrh       }
18072282792aSdrh     }
18082282792aSdrh     if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
18091d83f052Sdrh       goto select_end;
18102282792aSdrh     }
1811191b690eSdrh     if( pOrderBy ){
1812191b690eSdrh       for(i=0; i<pOrderBy->nExpr; i++){
1813191b690eSdrh         if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
18141d83f052Sdrh           goto select_end;
1815191b690eSdrh         }
1816191b690eSdrh       }
1817191b690eSdrh     }
1818efb7251dSdrh   }
1819efb7251dSdrh 
18202282792aSdrh   /* Reset the aggregator
1821cce7d176Sdrh   */
1822cce7d176Sdrh   if( isAgg ){
182399fcd718Sdrh     sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
1824e5095355Sdrh     for(i=0; i<pParse->nAgg; i++){
18250bce8354Sdrh       FuncDef *pFunc;
18260bce8354Sdrh       if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
18271350b030Sdrh         sqliteVdbeAddOp(v, OP_AggInit, 0, i);
18280bce8354Sdrh         sqliteVdbeChangeP3(v, -1, (char*)pFunc, P3_POINTER);
1829e5095355Sdrh       }
1830e5095355Sdrh     }
18311bee3d7bSdrh     if( pGroupBy==0 ){
18321bee3d7bSdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
18331bee3d7bSdrh       sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
18341bee3d7bSdrh     }
1835cce7d176Sdrh   }
1836cce7d176Sdrh 
183719a775c2Sdrh   /* Initialize the memory cell to NULL
183819a775c2Sdrh   */
1839fef5208cSdrh   if( eDest==SRT_Mem ){
184099fcd718Sdrh     sqliteVdbeAddOp(v, OP_String, 0, 0);
18418721ce4aSdrh     sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
184219a775c2Sdrh   }
184319a775c2Sdrh 
1844832508b7Sdrh   /* Open a temporary table to use for the distinct set.
1845cce7d176Sdrh   */
184619a775c2Sdrh   if( isDistinct ){
1847832508b7Sdrh     distinct = pParse->nTab++;
1848c6b52df3Sdrh     sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
1849832508b7Sdrh   }else{
1850832508b7Sdrh     distinct = -1;
1851efb7251dSdrh   }
1852832508b7Sdrh 
1853832508b7Sdrh   /* Begin the database scan
1854832508b7Sdrh   */
1855e3184744Sdrh   pWInfo = sqliteWhereBegin(pParse, p->base, pTabList, pWhere, 0, &pOrderBy);
18561d83f052Sdrh   if( pWInfo==0 ) goto select_end;
1857cce7d176Sdrh 
18582282792aSdrh   /* Use the standard inner loop if we are not dealing with
18592282792aSdrh   ** aggregates
1860cce7d176Sdrh   */
1861da9d6c45Sdrh   if( !isAgg ){
1862df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
1863df199a25Sdrh                     iParm, pWInfo->iContinue, pWInfo->iBreak) ){
18641d83f052Sdrh        goto select_end;
1865cce7d176Sdrh     }
1866da9d6c45Sdrh   }
1867cce7d176Sdrh 
1868e3184744Sdrh   /* If we are dealing with aggregates, then do the special aggregate
18692282792aSdrh   ** processing.
1870efb7251dSdrh   */
18712282792aSdrh   else{
18722282792aSdrh     if( pGroupBy ){
18731bee3d7bSdrh       int lbl1;
18742282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
18752282792aSdrh         sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
1876efb7251dSdrh       }
187799fcd718Sdrh       sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
18781bee3d7bSdrh       lbl1 = sqliteVdbeMakeLabel(v);
187999fcd718Sdrh       sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
18802282792aSdrh       for(i=0; i<pParse->nAgg; i++){
18812282792aSdrh         if( pParse->aAgg[i].isAgg ) continue;
18822282792aSdrh         sqliteExprCode(pParse, pParse->aAgg[i].pExpr);
188399fcd718Sdrh         sqliteVdbeAddOp(v, OP_AggSet, 0, i);
18842282792aSdrh       }
18852282792aSdrh       sqliteVdbeResolveLabel(v, lbl1);
18862282792aSdrh     }
18872282792aSdrh     for(i=0; i<pParse->nAgg; i++){
18882282792aSdrh       Expr *pE;
18890bce8354Sdrh       int j;
18902282792aSdrh       if( !pParse->aAgg[i].isAgg ) continue;
18912282792aSdrh       pE = pParse->aAgg[i].pExpr;
18922282792aSdrh       assert( pE->op==TK_AGG_FUNCTION );
18930bce8354Sdrh       if( pE->pList ){
1894e5095355Sdrh         for(j=0; j<pE->pList->nExpr; j++){
1895e5095355Sdrh           sqliteExprCode(pParse, pE->pList->a[j].pExpr);
1896e5095355Sdrh         }
18972282792aSdrh       }
18981350b030Sdrh       sqliteVdbeAddOp(v, OP_Integer, i, 0);
1899f55f25f0Sdrh       sqliteVdbeAddOp(v, OP_AggFunc, 0, pE->pList ? pE->pList->nExpr : 0);
19000bce8354Sdrh       assert( pParse->aAgg[i].pFunc!=0 );
19010bce8354Sdrh       assert( pParse->aAgg[i].pFunc->xStep!=0 );
19020bce8354Sdrh       sqliteVdbeChangeP3(v, -1, (char*)pParse->aAgg[i].pFunc, P3_POINTER);
19032282792aSdrh     }
19042282792aSdrh   }
19052282792aSdrh 
1906cce7d176Sdrh   /* End the database scan loop.
1907cce7d176Sdrh   */
1908cce7d176Sdrh   sqliteWhereEnd(pWInfo);
1909cce7d176Sdrh 
19102282792aSdrh   /* If we are processing aggregates, we need to set up a second loop
19112282792aSdrh   ** over all of the aggregate values and process them.
19122282792aSdrh   */
19132282792aSdrh   if( isAgg ){
19142282792aSdrh     int endagg = sqliteVdbeMakeLabel(v);
19152282792aSdrh     int startagg;
191699fcd718Sdrh     startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
19172282792aSdrh     pParse->useAgg = 1;
19182282792aSdrh     if( pHaving ){
1919f5905aa7Sdrh       sqliteExprIfFalse(pParse, pHaving, startagg, 1);
19202282792aSdrh     }
1921df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
1922df199a25Sdrh                     iParm, startagg, endagg) ){
19231d83f052Sdrh       goto select_end;
19242282792aSdrh     }
192599fcd718Sdrh     sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
192699fcd718Sdrh     sqliteVdbeResolveLabel(v, endagg);
192799fcd718Sdrh     sqliteVdbeAddOp(v, OP_Noop, 0, 0);
19282282792aSdrh     pParse->useAgg = 0;
19292282792aSdrh   }
19302282792aSdrh 
1931cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
1932cce7d176Sdrh   ** and send them to the callback one by one.
1933cce7d176Sdrh   */
1934cce7d176Sdrh   if( pOrderBy ){
1935c926afbcSdrh     generateSortTail(p, v, pEList->nExpr, eDest, iParm);
1936cce7d176Sdrh   }
19376a535340Sdrh 
19386a535340Sdrh 
19396a535340Sdrh   /* Issue a null callback if that is what the user wants.
19406a535340Sdrh   */
19416a535340Sdrh   if( (pParse->db->flags & SQLITE_NullCallback)!=0 && eDest==SRT_Callback ){
19426a535340Sdrh     sqliteVdbeAddOp(v, OP_NullCallback, pEList->nExpr, 0);
19436a535340Sdrh   }
19446a535340Sdrh 
19451d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
19461d83f052Sdrh   ** to indicate no errors.
19471d83f052Sdrh   */
19481d83f052Sdrh   rc = 0;
19491d83f052Sdrh 
19501d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
19511d83f052Sdrh   ** successful coding of the SELECT.
19521d83f052Sdrh   */
19531d83f052Sdrh select_end:
1954832508b7Sdrh   pParse->nTab = base;
19551d83f052Sdrh   sqliteAggregateInfoReset(pParse);
19561d83f052Sdrh   return rc;
1957cce7d176Sdrh }
1958