xref: /sqlite-3.40.0/src/select.c (revision ef5ecb41)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains C code routines that are called by the parser
13 ** to handle SELECT statements in SQLite.
14 **
15 ** $Id: select.c,v 1.186 2004/06/10 10:50:25 danielk1977 Exp $
16 */
17 #include "sqliteInt.h"
18 
19 
20 /*
21 ** Allocate a new Select structure and return a pointer to that
22 ** structure.
23 */
24 Select *sqlite3SelectNew(
25   ExprList *pEList,     /* which columns to include in the result */
26   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
27   Expr *pWhere,         /* the WHERE clause */
28   ExprList *pGroupBy,   /* the GROUP BY clause */
29   Expr *pHaving,        /* the HAVING clause */
30   ExprList *pOrderBy,   /* the ORDER BY clause */
31   int isDistinct,       /* true if the DISTINCT keyword is present */
32   int nLimit,           /* LIMIT value.  -1 means not used */
33   int nOffset           /* OFFSET value.  0 means no offset */
34 ){
35   Select *pNew;
36   pNew = sqliteMalloc( sizeof(*pNew) );
37   if( pNew==0 ){
38     sqlite3ExprListDelete(pEList);
39     sqlite3SrcListDelete(pSrc);
40     sqlite3ExprDelete(pWhere);
41     sqlite3ExprListDelete(pGroupBy);
42     sqlite3ExprDelete(pHaving);
43     sqlite3ExprListDelete(pOrderBy);
44   }else{
45     if( pEList==0 ){
46       pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0);
47     }
48     pNew->pEList = pEList;
49     pNew->pSrc = pSrc;
50     pNew->pWhere = pWhere;
51     pNew->pGroupBy = pGroupBy;
52     pNew->pHaving = pHaving;
53     pNew->pOrderBy = pOrderBy;
54     pNew->isDistinct = isDistinct;
55     pNew->op = TK_SELECT;
56     pNew->nLimit = nLimit;
57     pNew->nOffset = nOffset;
58     pNew->iLimit = -1;
59     pNew->iOffset = -1;
60   }
61   return pNew;
62 }
63 
64 /*
65 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
66 ** type of join.  Return an integer constant that expresses that type
67 ** in terms of the following bit values:
68 **
69 **     JT_INNER
70 **     JT_OUTER
71 **     JT_NATURAL
72 **     JT_LEFT
73 **     JT_RIGHT
74 **
75 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
76 **
77 ** If an illegal or unsupported join type is seen, then still return
78 ** a join type, but put an error in the pParse structure.
79 */
80 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
81   int jointype = 0;
82   Token *apAll[3];
83   Token *p;
84   static struct {
85     const char *zKeyword;
86     int nChar;
87     int code;
88   } keywords[] = {
89     { "natural", 7, JT_NATURAL },
90     { "left",    4, JT_LEFT|JT_OUTER },
91     { "right",   5, JT_RIGHT|JT_OUTER },
92     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
93     { "outer",   5, JT_OUTER },
94     { "inner",   5, JT_INNER },
95     { "cross",   5, JT_INNER },
96   };
97   int i, j;
98   apAll[0] = pA;
99   apAll[1] = pB;
100   apAll[2] = pC;
101   for(i=0; i<3 && apAll[i]; i++){
102     p = apAll[i];
103     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
104       if( p->n==keywords[j].nChar
105           && sqlite3StrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
106         jointype |= keywords[j].code;
107         break;
108       }
109     }
110     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
111       jointype |= JT_ERROR;
112       break;
113     }
114   }
115   if(
116      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
117      (jointype & JT_ERROR)!=0
118   ){
119     static Token dummy = { 0, 0 };
120     char *zSp1 = " ", *zSp2 = " ";
121     if( pB==0 ){ pB = &dummy; zSp1 = 0; }
122     if( pC==0 ){ pC = &dummy; zSp2 = 0; }
123     sqlite3SetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
124        pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0);
125     pParse->nErr++;
126     jointype = JT_INNER;
127   }else if( jointype & JT_RIGHT ){
128     sqlite3ErrorMsg(pParse,
129       "RIGHT and FULL OUTER JOINs are not currently supported");
130     jointype = JT_INNER;
131   }
132   return jointype;
133 }
134 
135 /*
136 ** Return the index of a column in a table.  Return -1 if the column
137 ** is not contained in the table.
138 */
139 static int columnIndex(Table *pTab, const char *zCol){
140   int i;
141   for(i=0; i<pTab->nCol; i++){
142     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
143   }
144   return -1;
145 }
146 
147 /*
148 ** Add a term to the WHERE expression in *ppExpr that requires the
149 ** zCol column to be equal in the two tables pTab1 and pTab2.
150 */
151 static void addWhereTerm(
152   const char *zCol,        /* Name of the column */
153   const Table *pTab1,      /* First table */
154   const Table *pTab2,      /* Second table */
155   Expr **ppExpr            /* Add the equality term to this expression */
156 ){
157   Token dummy;
158   Expr *pE1a, *pE1b, *pE1c;
159   Expr *pE2a, *pE2b, *pE2c;
160   Expr *pE;
161 
162   dummy.z = zCol;
163   dummy.n = strlen(zCol);
164   dummy.dyn = 0;
165   pE1a = sqlite3Expr(TK_ID, 0, 0, &dummy);
166   pE2a = sqlite3Expr(TK_ID, 0, 0, &dummy);
167   dummy.z = pTab1->zName;
168   dummy.n = strlen(dummy.z);
169   pE1b = sqlite3Expr(TK_ID, 0, 0, &dummy);
170   dummy.z = pTab2->zName;
171   dummy.n = strlen(dummy.z);
172   pE2b = sqlite3Expr(TK_ID, 0, 0, &dummy);
173   pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
174   pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
175   pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
176   ExprSetProperty(pE, EP_FromJoin);
177   if( *ppExpr ){
178     *ppExpr = sqlite3Expr(TK_AND, *ppExpr, pE, 0);
179   }else{
180     *ppExpr = pE;
181   }
182 }
183 
184 /*
185 ** Set the EP_FromJoin property on all terms of the given expression.
186 **
187 ** The EP_FromJoin property is used on terms of an expression to tell
188 ** the LEFT OUTER JOIN processing logic that this term is part of the
189 ** join restriction specified in the ON or USING clause and not a part
190 ** of the more general WHERE clause.  These terms are moved over to the
191 ** WHERE clause during join processing but we need to remember that they
192 ** originated in the ON or USING clause.
193 */
194 static void setJoinExpr(Expr *p){
195   while( p ){
196     ExprSetProperty(p, EP_FromJoin);
197     setJoinExpr(p->pLeft);
198     p = p->pRight;
199   }
200 }
201 
202 /*
203 ** This routine processes the join information for a SELECT statement.
204 ** ON and USING clauses are converted into extra terms of the WHERE clause.
205 ** NATURAL joins also create extra WHERE clause terms.
206 **
207 ** This routine returns the number of errors encountered.
208 */
209 static int sqliteProcessJoin(Parse *pParse, Select *p){
210   SrcList *pSrc;
211   int i, j;
212   pSrc = p->pSrc;
213   for(i=0; i<pSrc->nSrc-1; i++){
214     struct SrcList_item *pTerm = &pSrc->a[i];
215     struct SrcList_item *pOther = &pSrc->a[i+1];
216 
217     if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
218 
219     /* When the NATURAL keyword is present, add WHERE clause terms for
220     ** every column that the two tables have in common.
221     */
222     if( pTerm->jointype & JT_NATURAL ){
223       Table *pTab;
224       if( pTerm->pOn || pTerm->pUsing ){
225         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
226            "an ON or USING clause", 0);
227         return 1;
228       }
229       pTab = pTerm->pTab;
230       for(j=0; j<pTab->nCol; j++){
231         if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
232           addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
233         }
234       }
235     }
236 
237     /* Disallow both ON and USING clauses in the same join
238     */
239     if( pTerm->pOn && pTerm->pUsing ){
240       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
241         "clauses in the same join");
242       return 1;
243     }
244 
245     /* Add the ON clause to the end of the WHERE clause, connected by
246     ** and AND operator.
247     */
248     if( pTerm->pOn ){
249       setJoinExpr(pTerm->pOn);
250       if( p->pWhere==0 ){
251         p->pWhere = pTerm->pOn;
252       }else{
253         p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pTerm->pOn, 0);
254       }
255       pTerm->pOn = 0;
256     }
257 
258     /* Create extra terms on the WHERE clause for each column named
259     ** in the USING clause.  Example: If the two tables to be joined are
260     ** A and B and the USING clause names X, Y, and Z, then add this
261     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
262     ** Report an error if any column mentioned in the USING clause is
263     ** not contained in both tables to be joined.
264     */
265     if( pTerm->pUsing ){
266       IdList *pList;
267       int j;
268       assert( i<pSrc->nSrc-1 );
269       pList = pTerm->pUsing;
270       for(j=0; j<pList->nId; j++){
271         if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
272             columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
273           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
274             "not present in both tables", pList->a[j].zName);
275           return 1;
276         }
277         addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
278       }
279     }
280   }
281   return 0;
282 }
283 
284 /*
285 ** Delete the given Select structure and all of its substructures.
286 */
287 void sqlite3SelectDelete(Select *p){
288   if( p==0 ) return;
289   sqlite3ExprListDelete(p->pEList);
290   sqlite3SrcListDelete(p->pSrc);
291   sqlite3ExprDelete(p->pWhere);
292   sqlite3ExprListDelete(p->pGroupBy);
293   sqlite3ExprDelete(p->pHaving);
294   sqlite3ExprListDelete(p->pOrderBy);
295   sqlite3SelectDelete(p->pPrior);
296   sqliteFree(p->zSelect);
297   sqliteFree(p);
298 }
299 
300 /*
301 ** Delete the aggregate information from the parse structure.
302 */
303 static void sqliteAggregateInfoReset(Parse *pParse){
304   sqliteFree(pParse->aAgg);
305   pParse->aAgg = 0;
306   pParse->nAgg = 0;
307   pParse->useAgg = 0;
308 }
309 
310 /*
311 ** Insert code into "v" that will push the record on the top of the
312 ** stack into the sorter.
313 */
314 static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
315   int i;
316   for(i=0; i<pOrderBy->nExpr; i++){
317     sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr);
318   }
319   sqlite3VdbeAddOp(v, OP_MakeKey, pOrderBy->nExpr, 0);
320   sqlite3VdbeAddOp(v, OP_SortPut, 0, 0);
321 }
322 
323 /*
324 ** This routine generates the code for the inside of the inner loop
325 ** of a SELECT.
326 **
327 ** If srcTab and nColumn are both zero, then the pEList expressions
328 ** are evaluated in order to get the data for this row.  If nColumn>0
329 ** then data is pulled from srcTab and pEList is used only to get the
330 ** datatypes for each column.
331 */
332 static int selectInnerLoop(
333   Parse *pParse,          /* The parser context */
334   Select *p,              /* The complete select statement being coded */
335   ExprList *pEList,       /* List of values being extracted */
336   int srcTab,             /* Pull data from this table */
337   int nColumn,            /* Number of columns in the source table */
338   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
339   int distinct,           /* If >=0, make sure results are distinct */
340   int eDest,              /* How to dispose of the results */
341   int iParm,              /* An argument to the disposal method */
342   int iContinue,          /* Jump here to continue with next row */
343   int iBreak,             /* Jump here to break out of the inner loop */
344   char *aff               /* affinity string if eDest is SRT_Union */
345 ){
346   Vdbe *v = pParse->pVdbe;
347   int i;
348 
349   if( v==0 ) return 0;
350   assert( pEList!=0 );
351 
352   /* If there was a LIMIT clause on the SELECT statement, then do the check
353   ** to see if this row should be output.
354   */
355   if( pOrderBy==0 ){
356     if( p->iOffset>=0 ){
357       int addr = sqlite3VdbeCurrentAddr(v);
358       sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+2);
359       sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
360     }
361     if( p->iLimit>=0 ){
362       sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
363     }
364   }
365 
366   /* Pull the requested columns.
367   */
368   if( nColumn>0 ){
369     for(i=0; i<nColumn; i++){
370       sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
371     }
372   }else{
373     nColumn = pEList->nExpr;
374     for(i=0; i<pEList->nExpr; i++){
375       sqlite3ExprCode(pParse, pEList->a[i].pExpr);
376     }
377   }
378 
379   /* If the DISTINCT keyword was present on the SELECT statement
380   ** and this row has been seen before, then do not make this row
381   ** part of the result.
382   */
383   if( distinct>=0 && pEList && pEList->nExpr>0 ){
384 #if NULL_ALWAYS_DISTINCT
385     sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
386 #endif
387     /* Deliberately leave the affinity string off of the following OP_MakeKey */
388     sqlite3VdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
389     sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
390     sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
391     sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
392     sqlite3VdbeAddOp(v, OP_String8, 0, 0);
393     sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
394   }
395 
396   switch( eDest ){
397     /* In this mode, write each query result to the key of the temporary
398     ** table iParm.
399     */
400     case SRT_Union: {
401       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
402       sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
403       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
404       sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
405       break;
406     }
407 
408     /* Store the result as data using a unique key.
409     */
410     case SRT_Table:
411     case SRT_TempTable: {
412       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
413       if( pOrderBy ){
414         pushOntoSorter(pParse, v, pOrderBy);
415       }else{
416         sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
417         sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
418         sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
419       }
420       break;
421     }
422 
423     /* Construct a record from the query result, but instead of
424     ** saving that record, use it as a key to delete elements from
425     ** the temporary table iParm.
426     */
427     case SRT_Except: {
428       int addr;
429       addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
430       sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
431       sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
432       sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
433       break;
434     }
435 
436     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
437     ** then there should be a single item on the stack.  Write this
438     ** item into the set table with bogus data.
439     */
440     case SRT_Set: {
441       int addr1 = sqlite3VdbeCurrentAddr(v);
442       int addr2;
443 
444       assert( nColumn==1 );
445       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
446       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
447       addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
448       if( pOrderBy ){
449         pushOntoSorter(pParse, v, pOrderBy);
450       }else{
451         char const *affStr;
452         char aff = (iParm>>16)&0xFF;
453         aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
454         affStr = sqlite3AffinityString(aff);
455         sqlite3VdbeOp3(v, OP_MakeKey, 1, 0, affStr, P3_STATIC);
456         sqlite3VdbeAddOp(v, OP_String8, 0, 0);
457         sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
458       }
459       sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
460       break;
461     }
462 
463     /* If this is a scalar select that is part of an expression, then
464     ** store the results in the appropriate memory cell and break out
465     ** of the scan loop.
466     */
467     case SRT_Mem: {
468       assert( nColumn==1 );
469       if( pOrderBy ){
470         pushOntoSorter(pParse, v, pOrderBy);
471       }else{
472         sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
473         sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
474       }
475       break;
476     }
477 
478     /* Send the data to the callback function.
479     */
480     case SRT_Callback:
481     case SRT_Sorter: {
482       if( pOrderBy ){
483         sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
484         pushOntoSorter(pParse, v, pOrderBy);
485       }else{
486         assert( eDest==SRT_Callback );
487         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
488       }
489       break;
490     }
491 
492     /* Invoke a subroutine to handle the results.  The subroutine itself
493     ** is responsible for popping the results off of the stack.
494     */
495     case SRT_Subroutine: {
496       if( pOrderBy ){
497         sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
498         pushOntoSorter(pParse, v, pOrderBy);
499       }else{
500         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
501       }
502       break;
503     }
504 
505     /* Discard the results.  This is used for SELECT statements inside
506     ** the body of a TRIGGER.  The purpose of such selects is to call
507     ** user-defined functions that have side effects.  We do not care
508     ** about the actual results of the select.
509     */
510     default: {
511       assert( eDest==SRT_Discard );
512       sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
513       break;
514     }
515   }
516   return 0;
517 }
518 
519 /*
520 ** If the inner loop was generated using a non-null pOrderBy argument,
521 ** then the results were placed in a sorter.  After the loop is terminated
522 ** we need to run the sorter and output the results.  The following
523 ** routine generates the code needed to do that.
524 */
525 static void generateSortTail(
526   Parse *pParse,   /* The parsing context */
527   Select *p,       /* The SELECT statement */
528   Vdbe *v,         /* Generate code into this VDBE */
529   int nColumn,     /* Number of columns of data */
530   int eDest,       /* Write the sorted results here */
531   int iParm        /* Optional parameter associated with eDest */
532 ){
533   int end1 = sqlite3VdbeMakeLabel(v);
534   int end2 = sqlite3VdbeMakeLabel(v);
535   int addr;
536   KeyInfo *pInfo;
537   ExprList *pOrderBy;
538   int nCol, i;
539   sqlite *db = pParse->db;
540 
541   if( eDest==SRT_Sorter ) return;
542   pOrderBy = p->pOrderBy;
543   nCol = pOrderBy->nExpr;
544   pInfo = sqliteMalloc( sizeof(*pInfo) + nCol*(sizeof(CollSeq*)+1) );
545   if( pInfo==0 ) return;
546   pInfo->aSortOrder = (char*)&pInfo->aColl[nCol];
547   pInfo->nField = nCol;
548   for(i=0; i<nCol; i++){
549     /* If a collation sequence was specified explicity, then it
550     ** is stored in pOrderBy->a[i].zName. Otherwise, use the default
551     ** collation type for the expression.
552     */
553     pInfo->aColl[i] = sqlite3ExprCollSeq(pParse, pOrderBy->a[i].pExpr);
554     if( !pInfo->aColl[i] ){
555       pInfo->aColl[i] = db->pDfltColl;
556     }
557     pInfo->aSortOrder[i] = pOrderBy->a[i].sortOrder;
558   }
559   sqlite3VdbeOp3(v, OP_Sort, 0, 0, (char*)pInfo, P3_KEYINFO_HANDOFF);
560   addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
561   if( p->iOffset>=0 ){
562     sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+4);
563     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
564     sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
565   }
566   if( p->iLimit>=0 ){
567     sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, end2);
568   }
569   switch( eDest ){
570     case SRT_Table:
571     case SRT_TempTable: {
572       sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
573       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
574       sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
575       break;
576     }
577     case SRT_Set: {
578       assert( nColumn==1 );
579       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
580       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
581       sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
582       sqlite3VdbeOp3(v, OP_MakeKey, 1, 0, "n", P3_STATIC);
583       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
584       sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
585       break;
586     }
587     case SRT_Mem: {
588       assert( nColumn==1 );
589       sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
590       sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
591       break;
592     }
593     case SRT_Callback:
594     case SRT_Subroutine: {
595       int i;
596       sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
597       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
598       for(i=0; i<nColumn; i++){
599         sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
600       }
601       if( eDest==SRT_Callback ){
602         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
603       }else{
604         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
605       }
606       sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
607       break;
608     }
609     default: {
610       /* Do nothing */
611       break;
612     }
613   }
614   sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
615   sqlite3VdbeResolveLabel(v, end2);
616   sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
617   sqlite3VdbeResolveLabel(v, end1);
618   sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
619 }
620 
621 /*
622 ** Return a pointer to a string containing the 'declaration type' of the
623 ** expression pExpr. The string may be treated as static by the caller.
624 **
625 ** If the declaration type is the exact datatype definition extracted from
626 ** the original CREATE TABLE statement if the expression is a column.
627 **
628 ** The declaration type for an expression is either TEXT, NUMERIC or ANY.
629 ** The declaration type for a ROWID field is INTEGER.
630 */
631 static const char *columnType(Parse *pParse, SrcList *pTabList, Expr *pExpr){
632   char const *zType = 0;
633   int j;
634   if( pExpr==0 ) return 0;
635   if( pExpr->op==TK_COLUMN && pTabList ){
636     Table *pTab;
637     int iCol = pExpr->iColumn;
638     for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable; j++){}
639     assert( j<pTabList->nSrc );
640     pTab = pTabList->a[j].pTab;
641     if( iCol<0 ) iCol = pTab->iPKey;
642     assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
643     if( iCol<0 ){
644       zType = "INTEGER";
645     }else{
646       zType = pTab->aCol[iCol].zType;
647     }
648   }else{
649     switch( sqlite3ExprType(pExpr) ){
650       case SQLITE_AFF_TEXT:     zType = "TEXT";    break;
651       case SQLITE_AFF_NUMERIC:  zType = "NUMERIC"; break;
652       default:                  zType = "ANY";     break;
653     }
654   }
655   return zType;
656 }
657 
658 /*
659 ** Generate code that will tell the VDBE the declaration types of columns
660 ** in the result set.
661 */
662 static void generateColumnTypes(
663   Parse *pParse,      /* Parser context */
664   SrcList *pTabList,  /* List of tables */
665   ExprList *pEList    /* Expressions defining the result set */
666 ){
667   Vdbe *v = pParse->pVdbe;
668   int i;
669   for(i=0; i<pEList->nExpr; i++){
670     Expr *p = pEList->a[i].pExpr;
671     const char *zType = columnType(pParse, pTabList, p);
672     if( p==0 ) continue;
673     sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, P3_STATIC);
674   }
675 }
676 
677 /*
678 ** Generate code that will tell the VDBE the names of columns
679 ** in the result set.  This information is used to provide the
680 ** azCol[] values in the callback.
681 */
682 static void generateColumnNames(
683   Parse *pParse,      /* Parser context */
684   SrcList *pTabList,  /* List of tables */
685   ExprList *pEList    /* Expressions defining the result set */
686 ){
687   Vdbe *v = pParse->pVdbe;
688   int i, j;
689   sqlite *db = pParse->db;
690   int fullNames, shortNames;
691 
692   /* If this is an EXPLAIN, skip this step */
693   if( pParse->explain ){
694     return;
695   }
696 
697   assert( v!=0 );
698   if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
699   pParse->colNamesSet = 1;
700   fullNames = (db->flags & SQLITE_FullColNames)!=0;
701   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
702   sqlite3VdbeSetNumCols(v, pEList->nExpr);
703   for(i=0; i<pEList->nExpr; i++){
704     Expr *p;
705     p = pEList->a[i].pExpr;
706     if( p==0 ) continue;
707     if( pEList->a[i].zName ){
708       char *zName = pEList->a[i].zName;
709       sqlite3VdbeSetColName(v, i, zName, 0);
710       continue;
711     }
712     if( p->op==TK_COLUMN && pTabList ){
713       Table *pTab;
714       char *zCol;
715       int iCol = p->iColumn;
716       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
717       assert( j<pTabList->nSrc );
718       pTab = pTabList->a[j].pTab;
719       if( iCol<0 ) iCol = pTab->iPKey;
720       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
721       if( iCol<0 ){
722         zCol = "_ROWID_";
723       }else{
724         zCol = pTab->aCol[iCol].zName;
725       }
726       if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
727         sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
728         /* sqlite3VdbeCompressSpace(v, addr); */
729       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
730         char *zName = 0;
731         char *zTab;
732 
733         zTab = pTabList->a[j].zAlias;
734         if( fullNames || zTab==0 ) zTab = pTab->zName;
735         sqlite3SetString(&zName, zTab, ".", zCol, 0);
736         sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
737       }else{
738         sqlite3VdbeSetColName(v, i, zCol, 0);
739       }
740     }else if( p->span.z && p->span.z[0] ){
741       sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
742       /* sqlite3VdbeCompressSpace(v, addr); */
743     }else{
744       char zName[30];
745       assert( p->op!=TK_COLUMN || pTabList==0 );
746       sprintf(zName, "column%d", i+1);
747       sqlite3VdbeSetColName(v, i, zName, 0);
748     }
749   }
750   generateColumnTypes(pParse, pTabList, pEList);
751 }
752 
753 /*
754 ** Name of the connection operator, used for error messages.
755 */
756 static const char *selectOpName(int id){
757   char *z;
758   switch( id ){
759     case TK_ALL:       z = "UNION ALL";   break;
760     case TK_INTERSECT: z = "INTERSECT";   break;
761     case TK_EXCEPT:    z = "EXCEPT";      break;
762     default:           z = "UNION";       break;
763   }
764   return z;
765 }
766 
767 /*
768 ** Forward declaration
769 */
770 static int fillInColumnList(Parse*, Select*);
771 
772 /*
773 ** Given a SELECT statement, generate a Table structure that describes
774 ** the result set of that SELECT.
775 */
776 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
777   Table *pTab;
778   int i, j;
779   ExprList *pEList;
780   Column *aCol;
781 
782   if( fillInColumnList(pParse, pSelect) ){
783     return 0;
784   }
785   pTab = sqliteMalloc( sizeof(Table) );
786   if( pTab==0 ){
787     return 0;
788   }
789   pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
790   pEList = pSelect->pEList;
791   pTab->nCol = pEList->nExpr;
792   assert( pTab->nCol>0 );
793   pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
794   for(i=0; i<pTab->nCol; i++){
795     Expr *pR;
796     char *zType;
797     Expr *p = pEList->a[i].pExpr;
798     if( pEList->a[i].zName ){
799       aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
800     }else if( p->op==TK_DOT
801                && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
802       int cnt;
803       sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, 0);
804       for(j=cnt=0; j<i; j++){
805         if( sqlite3StrICmp(aCol[j].zName, aCol[i].zName)==0 ){
806           int n;
807           char zBuf[30];
808           sprintf(zBuf,"_%d",++cnt);
809           n = strlen(zBuf);
810           sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, zBuf,n,0);
811           j = -1;
812         }
813       }
814     }else if( p->span.z && p->span.z[0] ){
815       sqlite3SetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
816     }else{
817       char zBuf[30];
818       sprintf(zBuf, "column%d", i+1);
819       pTab->aCol[i].zName = sqliteStrDup(zBuf);
820     }
821 
822     zType = sqliteStrDup(columnType(pParse, pSelect->pSrc ,p));
823     pTab->aCol[i].zType = zType;
824     pTab->aCol[i].affinity = SQLITE_AFF_NUMERIC;
825     if( zType ){
826       pTab->aCol[i].affinity = sqlite3AffinityType(zType, strlen(zType));
827     }
828     pTab->aCol[i].pColl = sqlite3ExprCollSeq(pParse, p);
829     if( !pTab->aCol[i].pColl ){
830       pTab->aCol[i].pColl = pParse->db->pDfltColl;
831     }
832   }
833   pTab->iPKey = -1;
834   return pTab;
835 }
836 
837 /*
838 ** For the given SELECT statement, do three things.
839 **
840 **    (1)  Fill in the pTabList->a[].pTab fields in the SrcList that
841 **         defines the set of tables that should be scanned.  For views,
842 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
843 **         that implements the view.  A copy is made of the view's SELECT
844 **         statement so that we can freely modify or delete that statement
845 **         without worrying about messing up the presistent representation
846 **         of the view.
847 **
848 **    (2)  Add terms to the WHERE clause to accomodate the NATURAL keyword
849 **         on joins and the ON and USING clause of joins.
850 **
851 **    (3)  Scan the list of columns in the result set (pEList) looking
852 **         for instances of the "*" operator or the TABLE.* operator.
853 **         If found, expand each "*" to be every column in every table
854 **         and TABLE.* to be every column in TABLE.
855 **
856 ** Return 0 on success.  If there are problems, leave an error message
857 ** in pParse and return non-zero.
858 */
859 static int fillInColumnList(Parse *pParse, Select *p){
860   int i, j, k, rc;
861   SrcList *pTabList;
862   ExprList *pEList;
863   Table *pTab;
864 
865   if( p==0 || p->pSrc==0 ) return 1;
866   pTabList = p->pSrc;
867   pEList = p->pEList;
868 
869   /* Look up every table in the table list.
870   */
871   for(i=0; i<pTabList->nSrc; i++){
872     if( pTabList->a[i].pTab ){
873       /* This routine has run before!  No need to continue */
874       return 0;
875     }
876     if( pTabList->a[i].zName==0 ){
877       /* A sub-query in the FROM clause of a SELECT */
878       assert( pTabList->a[i].pSelect!=0 );
879       if( pTabList->a[i].zAlias==0 ){
880         char zFakeName[60];
881         sprintf(zFakeName, "sqlite_subquery_%p_",
882            (void*)pTabList->a[i].pSelect);
883         sqlite3SetString(&pTabList->a[i].zAlias, zFakeName, 0);
884       }
885       pTabList->a[i].pTab = pTab =
886         sqlite3ResultSetOfSelect(pParse, pTabList->a[i].zAlias,
887                                         pTabList->a[i].pSelect);
888       if( pTab==0 ){
889         return 1;
890       }
891       /* The isTransient flag indicates that the Table structure has been
892       ** dynamically allocated and may be freed at any time.  In other words,
893       ** pTab is not pointing to a persistent table structure that defines
894       ** part of the schema. */
895       pTab->isTransient = 1;
896     }else{
897       /* An ordinary table or view name in the FROM clause */
898       pTabList->a[i].pTab = pTab =
899         sqlite3LocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
900       if( pTab==0 ){
901         return 1;
902       }
903       if( pTab->pSelect ){
904         /* We reach here if the named table is a really a view */
905         if( sqlite3ViewGetColumnNames(pParse, pTab) ){
906           return 1;
907         }
908         /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
909         ** view within a view.  The SELECT structure has already been
910         ** copied by the outer view so we can skip the copy step here
911         ** in the inner view.
912         */
913         if( pTabList->a[i].pSelect==0 ){
914           pTabList->a[i].pSelect = sqlite3SelectDup(pTab->pSelect);
915         }
916       }
917     }
918   }
919 
920   /* Process NATURAL keywords, and ON and USING clauses of joins.
921   */
922   if( sqliteProcessJoin(pParse, p) ) return 1;
923 
924   /* For every "*" that occurs in the column list, insert the names of
925   ** all columns in all tables.  And for every TABLE.* insert the names
926   ** of all columns in TABLE.  The parser inserted a special expression
927   ** with the TK_ALL operator for each "*" that it found in the column list.
928   ** The following code just has to locate the TK_ALL expressions and expand
929   ** each one to the list of all columns in all tables.
930   **
931   ** The first loop just checks to see if there are any "*" operators
932   ** that need expanding.
933   */
934   for(k=0; k<pEList->nExpr; k++){
935     Expr *pE = pEList->a[k].pExpr;
936     if( pE->op==TK_ALL ) break;
937     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
938          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
939   }
940   rc = 0;
941   if( k<pEList->nExpr ){
942     /*
943     ** If we get here it means the result set contains one or more "*"
944     ** operators that need to be expanded.  Loop through each expression
945     ** in the result set and expand them one by one.
946     */
947     struct ExprList_item *a = pEList->a;
948     ExprList *pNew = 0;
949     for(k=0; k<pEList->nExpr; k++){
950       Expr *pE = a[k].pExpr;
951       if( pE->op!=TK_ALL &&
952            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
953         /* This particular expression does not need to be expanded.
954         */
955         pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
956         pNew->a[pNew->nExpr-1].zName = a[k].zName;
957         a[k].pExpr = 0;
958         a[k].zName = 0;
959       }else{
960         /* This expression is a "*" or a "TABLE.*" and needs to be
961         ** expanded. */
962         int tableSeen = 0;      /* Set to 1 when TABLE matches */
963         Token *pName;           /* text of name of TABLE */
964         if( pE->op==TK_DOT && pE->pLeft ){
965           pName = &pE->pLeft->token;
966         }else{
967           pName = 0;
968         }
969         for(i=0; i<pTabList->nSrc; i++){
970           Table *pTab = pTabList->a[i].pTab;
971           char *zTabName = pTabList->a[i].zAlias;
972           if( zTabName==0 || zTabName[0]==0 ){
973             zTabName = pTab->zName;
974           }
975           if( pName && (zTabName==0 || zTabName[0]==0 ||
976                  sqlite3StrNICmp(pName->z, zTabName, pName->n)!=0 ||
977                  zTabName[pName->n]!=0) ){
978             continue;
979           }
980           tableSeen = 1;
981           for(j=0; j<pTab->nCol; j++){
982             Expr *pExpr, *pLeft, *pRight;
983             char *zName = pTab->aCol[j].zName;
984 
985             if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
986                 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
987               /* In a NATURAL join, omit the join columns from the
988               ** table on the right */
989               continue;
990             }
991             if( i>0 && sqlite3IdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
992               /* In a join with a USING clause, omit columns in the
993               ** using clause from the table on the right. */
994               continue;
995             }
996             pRight = sqlite3Expr(TK_ID, 0, 0, 0);
997             if( pRight==0 ) break;
998             pRight->token.z = zName;
999             pRight->token.n = strlen(zName);
1000             pRight->token.dyn = 0;
1001             if( zTabName && pTabList->nSrc>1 ){
1002               pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1003               pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
1004               if( pExpr==0 ) break;
1005               pLeft->token.z = zTabName;
1006               pLeft->token.n = strlen(zTabName);
1007               pLeft->token.dyn = 0;
1008               sqlite3SetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
1009               pExpr->span.n = strlen(pExpr->span.z);
1010               pExpr->span.dyn = 1;
1011               pExpr->token.z = 0;
1012               pExpr->token.n = 0;
1013               pExpr->token.dyn = 0;
1014             }else{
1015               pExpr = pRight;
1016               pExpr->span = pExpr->token;
1017             }
1018             pNew = sqlite3ExprListAppend(pNew, pExpr, 0);
1019           }
1020         }
1021         if( !tableSeen ){
1022           if( pName ){
1023             sqlite3ErrorMsg(pParse, "no such table: %T", pName);
1024           }else{
1025             sqlite3ErrorMsg(pParse, "no tables specified");
1026           }
1027           rc = 1;
1028         }
1029       }
1030     }
1031     sqlite3ExprListDelete(pEList);
1032     p->pEList = pNew;
1033   }
1034   return rc;
1035 }
1036 
1037 /*
1038 ** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1039 ** in a select structure.  It just sets the pointers to NULL.  This
1040 ** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1041 ** pointer is not NULL, this routine is called recursively on that pointer.
1042 **
1043 ** This routine is called on the Select structure that defines a
1044 ** VIEW in order to undo any bindings to tables.  This is necessary
1045 ** because those tables might be DROPed by a subsequent SQL command.
1046 ** If the bindings are not removed, then the Select.pSrc->a[].pTab field
1047 ** will be left pointing to a deallocated Table structure after the
1048 ** DROP and a coredump will occur the next time the VIEW is used.
1049 */
1050 void sqlite3SelectUnbind(Select *p){
1051   int i;
1052   SrcList *pSrc = p->pSrc;
1053   Table *pTab;
1054   if( p==0 ) return;
1055   for(i=0; i<pSrc->nSrc; i++){
1056     if( (pTab = pSrc->a[i].pTab)!=0 ){
1057       if( pTab->isTransient ){
1058         sqlite3DeleteTable(0, pTab);
1059       }
1060       pSrc->a[i].pTab = 0;
1061       if( pSrc->a[i].pSelect ){
1062         sqlite3SelectUnbind(pSrc->a[i].pSelect);
1063       }
1064     }
1065   }
1066 }
1067 
1068 /*
1069 ** This routine associates entries in an ORDER BY expression list with
1070 ** columns in a result.  For each ORDER BY expression, the opcode of
1071 ** the top-level node is changed to TK_COLUMN and the iColumn value of
1072 ** the top-level node is filled in with column number and the iTable
1073 ** value of the top-level node is filled with iTable parameter.
1074 **
1075 ** If there are prior SELECT clauses, they are processed first.  A match
1076 ** in an earlier SELECT takes precedence over a later SELECT.
1077 **
1078 ** Any entry that does not match is flagged as an error.  The number
1079 ** of errors is returned.
1080 */
1081 static int matchOrderbyToColumn(
1082   Parse *pParse,          /* A place to leave error messages */
1083   Select *pSelect,        /* Match to result columns of this SELECT */
1084   ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
1085   int iTable,             /* Insert this value in iTable */
1086   int mustComplete        /* If TRUE all ORDER BYs must match */
1087 ){
1088   int nErr = 0;
1089   int i, j;
1090   ExprList *pEList;
1091 
1092   if( pSelect==0 || pOrderBy==0 ) return 1;
1093   if( mustComplete ){
1094     for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1095   }
1096   if( fillInColumnList(pParse, pSelect) ){
1097     return 1;
1098   }
1099   if( pSelect->pPrior ){
1100     if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1101       return 1;
1102     }
1103   }
1104   pEList = pSelect->pEList;
1105   for(i=0; i<pOrderBy->nExpr; i++){
1106     Expr *pE = pOrderBy->a[i].pExpr;
1107     int iCol = -1;
1108     if( pOrderBy->a[i].done ) continue;
1109     if( sqlite3ExprIsInteger(pE, &iCol) ){
1110       if( iCol<=0 || iCol>pEList->nExpr ){
1111         sqlite3ErrorMsg(pParse,
1112           "ORDER BY position %d should be between 1 and %d",
1113           iCol, pEList->nExpr);
1114         nErr++;
1115         break;
1116       }
1117       if( !mustComplete ) continue;
1118       iCol--;
1119     }
1120     for(j=0; iCol<0 && j<pEList->nExpr; j++){
1121       if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
1122         char *zName, *zLabel;
1123         zName = pEList->a[j].zName;
1124         assert( pE->token.z );
1125         zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
1126         sqlite3Dequote(zLabel);
1127         if( sqlite3StrICmp(zName, zLabel)==0 ){
1128           iCol = j;
1129         }
1130         sqliteFree(zLabel);
1131       }
1132       if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
1133         iCol = j;
1134       }
1135     }
1136     if( iCol>=0 ){
1137       pE->op = TK_COLUMN;
1138       pE->iColumn = iCol;
1139       pE->iTable = iTable;
1140       pOrderBy->a[i].done = 1;
1141     }
1142     if( iCol<0 && mustComplete ){
1143       sqlite3ErrorMsg(pParse,
1144         "ORDER BY term number %d does not match any result column", i+1);
1145       nErr++;
1146       break;
1147     }
1148   }
1149   return nErr;
1150 }
1151 
1152 /*
1153 ** Get a VDBE for the given parser context.  Create a new one if necessary.
1154 ** If an error occurs, return NULL and leave a message in pParse.
1155 */
1156 Vdbe *sqlite3GetVdbe(Parse *pParse){
1157   Vdbe *v = pParse->pVdbe;
1158   if( v==0 ){
1159     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1160   }
1161   return v;
1162 }
1163 
1164 #if 0  /***** This routine needs deleting *****/
1165 static void multiSelectAffinity(Select *p, char *zAff){
1166   int i;
1167 
1168   if( !p ) return;
1169   multiSelectAffinity(p->pPrior, zAff);
1170 
1171   for(i=0; i<p->pEList->nExpr; i++){
1172     if( zAff[i]=='\0' ){
1173       zAff[i] = sqlite3ExprAffinity(p->pEList->a[i].pExpr);
1174     }
1175   }
1176 }
1177 #endif
1178 
1179 /*
1180 ** Compute the iLimit and iOffset fields of the SELECT based on the
1181 ** nLimit and nOffset fields.  nLimit and nOffset hold the integers
1182 ** that appear in the original SQL statement after the LIMIT and OFFSET
1183 ** keywords.  Or that hold -1 and 0 if those keywords are omitted.
1184 ** iLimit and iOffset are the integer memory register numbers for
1185 ** counters used to compute the limit and offset.  If there is no
1186 ** limit and/or offset, then iLimit and iOffset are negative.
1187 **
1188 ** This routine changes the values if iLimit and iOffset only if
1189 ** a limit or offset is defined by nLimit and nOffset.  iLimit and
1190 ** iOffset should have been preset to appropriate default values
1191 ** (usually but not always -1) prior to calling this routine.
1192 ** Only if nLimit>=0 or nOffset>0 do the limit registers get
1193 ** redefined.  The UNION ALL operator uses this property to force
1194 ** the reuse of the same limit and offset registers across multiple
1195 ** SELECT statements.
1196 */
1197 static void computeLimitRegisters(Parse *pParse, Select *p){
1198   /*
1199   ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
1200   ** all rows.  It is the same as no limit. If the comparision is
1201   ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
1202   ** "LIMIT -1" always shows all rows.  There is some
1203   ** contraversy about what the correct behavior should be.
1204   ** The current implementation interprets "LIMIT 0" to mean
1205   ** no rows.
1206   */
1207   if( p->nLimit>=0 ){
1208     int iMem = pParse->nMem++;
1209     Vdbe *v = sqlite3GetVdbe(pParse);
1210     if( v==0 ) return;
1211     sqlite3VdbeAddOp(v, OP_Integer, -p->nLimit, 0);
1212     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
1213     p->iLimit = iMem;
1214   }
1215   if( p->nOffset>0 ){
1216     int iMem = pParse->nMem++;
1217     Vdbe *v = sqlite3GetVdbe(pParse);
1218     if( v==0 ) return;
1219     sqlite3VdbeAddOp(v, OP_Integer, -p->nOffset, 0);
1220     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
1221     p->iOffset = iMem;
1222   }
1223 }
1224 
1225 /*
1226 ** Generate VDBE instructions that will open a transient table that
1227 ** will be used for an index or to store keyed results for a compound
1228 ** select.  In other words, open a transient table that needs a
1229 ** KeyInfo structure.  The number of columns in the KeyInfo is determined
1230 ** by the result set of the SELECT statement in the second argument.
1231 **
1232 ** Make the new table a KeyAsData table if keyAsData is true.
1233 */
1234 static void openTempIndex(Parse *pParse, Select *p, int iTab, int keyAsData){
1235   KeyInfo *pKeyInfo;
1236   int nColumn;
1237   sqlite *db = pParse->db;
1238   int i;
1239   Vdbe *v = pParse->pVdbe;
1240 
1241   if( fillInColumnList(pParse, p) ){
1242     return;
1243   }
1244   nColumn = p->pEList->nExpr;
1245   pKeyInfo = sqliteMalloc( sizeof(*pKeyInfo)+nColumn*sizeof(CollSeq*) );
1246   if( pKeyInfo==0 ) return;
1247   pKeyInfo->nField = nColumn;
1248   for(i=0; i<nColumn; i++){
1249     pKeyInfo->aColl[i] = db->pDfltColl;
1250   }
1251   sqlite3VdbeOp3(v, OP_OpenTemp, iTab, 0, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
1252   if( keyAsData ){
1253     sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
1254   }
1255 }
1256 
1257 /*
1258 ** This routine is called to process a query that is really the union
1259 ** or intersection of two or more separate queries.
1260 **
1261 ** "p" points to the right-most of the two queries.  the query on the
1262 ** left is p->pPrior.  The left query could also be a compound query
1263 ** in which case this routine will be called recursively.
1264 **
1265 ** The results of the total query are to be written into a destination
1266 ** of type eDest with parameter iParm.
1267 **
1268 ** Example 1:  Consider a three-way compound SQL statement.
1269 **
1270 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1271 **
1272 ** This statement is parsed up as follows:
1273 **
1274 **     SELECT c FROM t3
1275 **      |
1276 **      `----->  SELECT b FROM t2
1277 **                |
1278 **                `------>  SELECT a FROM t1
1279 **
1280 ** The arrows in the diagram above represent the Select.pPrior pointer.
1281 ** So if this routine is called with p equal to the t3 query, then
1282 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1283 **
1284 ** Notice that because of the way SQLite parses compound SELECTs, the
1285 ** individual selects always group from left to right.
1286 */
1287 static int multiSelect(
1288   Parse *pParse,
1289   Select *p,
1290   int eDest,
1291   int iParm,
1292   char *aff           /* If eDest is SRT_Union, the affinity string */
1293 ){
1294   int rc = SQLITE_OK;  /* Success code from a subroutine */
1295   Select *pPrior;     /* Another SELECT immediately to our left */
1296   Vdbe *v;            /* Generate code to this VDBE */
1297 #if 0 /* NOT USED */
1298   char *affStr = 0;
1299 
1300   if( !aff ){
1301     int len;
1302     rc = fillInColumnList(pParse, p);
1303     if( rc!=SQLITE_OK ){
1304       goto multi_select_end;
1305     }
1306     len = p->pEList->nExpr+1;
1307     affStr = (char *)sqliteMalloc(p->pEList->nExpr+1);
1308     if( !affStr ){
1309       rc = SQLITE_NOMEM;
1310       goto multi_select_end;
1311     }
1312     memset(affStr, (int)SQLITE_AFF_NUMERIC, len-1);
1313     aff = affStr;
1314   }
1315 #endif
1316 
1317   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1318   ** the last SELECT in the series may have an ORDER BY or LIMIT.
1319   */
1320   if( p==0 || p->pPrior==0 ){
1321     rc = 1;
1322     goto multi_select_end;
1323   }
1324   pPrior = p->pPrior;
1325   if( pPrior->pOrderBy ){
1326     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1327       selectOpName(p->op));
1328     rc = 1;
1329     goto multi_select_end;
1330   }
1331   if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
1332     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
1333       selectOpName(p->op));
1334     rc = 1;
1335     goto multi_select_end;
1336   }
1337 
1338   /* Make sure we have a valid query engine.  If not, create a new one.
1339   */
1340   v = sqlite3GetVdbe(pParse);
1341   if( v==0 ){
1342     rc = 1;
1343     goto multi_select_end;
1344   }
1345 
1346   /* Create the destination temporary table if necessary
1347   */
1348   if( eDest==SRT_TempTable ){
1349     assert( p->pEList );
1350     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
1351     sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, p->pEList->nExpr);
1352     eDest = SRT_Table;
1353   }
1354 
1355   /* Generate code for the left and right SELECT statements.
1356   */
1357   switch( p->op ){
1358     case TK_ALL: {
1359       if( p->pOrderBy==0 ){
1360         pPrior->nLimit = p->nLimit;
1361         pPrior->nOffset = p->nOffset;
1362         rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
1363         if( rc ){
1364           goto multi_select_end;
1365         }
1366         p->pPrior = 0;
1367         p->iLimit = pPrior->iLimit;
1368         p->iOffset = pPrior->iOffset;
1369         p->nLimit = -1;
1370         p->nOffset = 0;
1371         rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
1372         p->pPrior = pPrior;
1373         if( rc ){
1374           goto multi_select_end;
1375         }
1376         break;
1377       }
1378       /* For UNION ALL ... ORDER BY fall through to the next case */
1379     }
1380     case TK_EXCEPT:
1381     case TK_UNION: {
1382       int unionTab;    /* Cursor number of the temporary table holding result */
1383       int op;          /* One of the SRT_ operations to apply to self */
1384       int priorOp;     /* The SRT_ operation to apply to prior selects */
1385       int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
1386       ExprList *pOrderBy;  /* The ORDER BY clause for the right SELECT */
1387 
1388       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
1389       if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
1390         /* We can reuse a temporary table generated by a SELECT to our
1391         ** right.
1392         */
1393         unionTab = iParm;
1394       }else{
1395         /* We will need to create our own temporary table to hold the
1396         ** intermediate results.
1397         */
1398         unionTab = pParse->nTab++;
1399         if( p->pOrderBy
1400         && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
1401           rc = 1;
1402           goto multi_select_end;
1403         }
1404         if( p->op!=TK_ALL ){
1405           openTempIndex(pParse, p, unionTab, 1);
1406         }else{
1407           sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
1408         }
1409         assert( p->pEList );
1410       }
1411 
1412       /* Code the SELECT statements to our left
1413       */
1414       rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
1415       if( rc ){
1416         goto multi_select_end;
1417       }
1418       if( p->op==TK_ALL ){
1419         sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, pPrior->pEList->nExpr);
1420       }
1421 
1422       /* Code the current SELECT statement
1423       */
1424       switch( p->op ){
1425          case TK_EXCEPT:  op = SRT_Except;   break;
1426          case TK_UNION:   op = SRT_Union;    break;
1427          case TK_ALL:     op = SRT_Table;    break;
1428       }
1429       p->pPrior = 0;
1430       pOrderBy = p->pOrderBy;
1431       p->pOrderBy = 0;
1432       nLimit = p->nLimit;
1433       p->nLimit = -1;
1434       nOffset = p->nOffset;
1435       p->nOffset = 0;
1436       rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
1437       p->pPrior = pPrior;
1438       p->pOrderBy = pOrderBy;
1439       p->nLimit = nLimit;
1440       p->nOffset = nOffset;
1441       if( rc ){
1442         goto multi_select_end;
1443       }
1444 
1445 
1446       /* Convert the data in the temporary table into whatever form
1447       ** it is that we currently need.
1448       */
1449       if( eDest!=priorOp || unionTab!=iParm ){
1450         int iCont, iBreak, iStart;
1451         assert( p->pEList );
1452         if( eDest==SRT_Callback ){
1453           generateColumnNames(pParse, 0, p->pEList);
1454         }
1455         iBreak = sqlite3VdbeMakeLabel(v);
1456         iCont = sqlite3VdbeMakeLabel(v);
1457         sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
1458         computeLimitRegisters(pParse, p);
1459         iStart = sqlite3VdbeCurrentAddr(v);
1460         rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
1461                              p->pOrderBy, -1, eDest, iParm,
1462                              iCont, iBreak, 0);
1463         if( rc ){
1464           rc = 1;
1465           goto multi_select_end;
1466         }
1467         sqlite3VdbeResolveLabel(v, iCont);
1468         sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1469         sqlite3VdbeResolveLabel(v, iBreak);
1470         sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
1471         if( p->pOrderBy ){
1472           generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1473         }
1474       }
1475       break;
1476     }
1477     case TK_INTERSECT: {
1478       int tab1, tab2;
1479       int iCont, iBreak, iStart;
1480       int nLimit, nOffset;
1481 
1482       /* INTERSECT is different from the others since it requires
1483       ** two temporary tables.  Hence it has its own case.  Begin
1484       ** by allocating the tables we will need.
1485       */
1486       tab1 = pParse->nTab++;
1487       tab2 = pParse->nTab++;
1488       if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
1489         rc = 1;
1490         goto multi_select_end;
1491       }
1492       openTempIndex(pParse, p, tab1, 1);
1493       assert( p->pEList );
1494 
1495       /* Code the SELECTs to our left into temporary table "tab1".
1496       */
1497       rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
1498       if( rc ){
1499         goto multi_select_end;
1500       }
1501 
1502       /* Code the current SELECT into temporary table "tab2"
1503       */
1504       openTempIndex(pParse, p, tab2, 1);
1505       p->pPrior = 0;
1506       nLimit = p->nLimit;
1507       p->nLimit = -1;
1508       nOffset = p->nOffset;
1509       p->nOffset = 0;
1510       rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
1511       p->pPrior = pPrior;
1512       p->nLimit = nLimit;
1513       p->nOffset = nOffset;
1514       if( rc ){
1515         goto multi_select_end;
1516       }
1517 
1518       /* Generate code to take the intersection of the two temporary
1519       ** tables.
1520       */
1521       assert( p->pEList );
1522       if( eDest==SRT_Callback ){
1523         generateColumnNames(pParse, 0, p->pEList);
1524       }
1525       iBreak = sqlite3VdbeMakeLabel(v);
1526       iCont = sqlite3VdbeMakeLabel(v);
1527       sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
1528       computeLimitRegisters(pParse, p);
1529       iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
1530       sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
1531       rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
1532                              p->pOrderBy, -1, eDest, iParm,
1533                              iCont, iBreak, 0);
1534       if( rc ){
1535         rc = 1;
1536         goto multi_select_end;
1537       }
1538       sqlite3VdbeResolveLabel(v, iCont);
1539       sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1540       sqlite3VdbeResolveLabel(v, iBreak);
1541       sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1542       sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
1543       if( p->pOrderBy ){
1544         generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1545       }
1546       break;
1547     }
1548   }
1549   assert( p->pEList && pPrior->pEList );
1550   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
1551     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
1552       " do not have the same number of result columns", selectOpName(p->op));
1553     rc = 1;
1554     goto multi_select_end;
1555   }
1556 
1557 multi_select_end:
1558 #if 0  /*** NOT USED ****/
1559   if( affStr ){
1560     if( rc!=SQLITE_OK ){
1561       sqliteFree(affStr);
1562     }else{
1563       multiSelectAffinity(p, affStr);
1564       sqlite3VdbeOp3(v, OP_Noop, 0, 0, affStr, P3_DYNAMIC);
1565     }
1566   }
1567 #endif
1568   return rc;
1569 }
1570 
1571 /*
1572 ** Scan through the expression pExpr.  Replace every reference to
1573 ** a column in table number iTable with a copy of the iColumn-th
1574 ** entry in pEList.  (But leave references to the ROWID column
1575 ** unchanged.)
1576 **
1577 ** This routine is part of the flattening procedure.  A subquery
1578 ** whose result set is defined by pEList appears as entry in the
1579 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
1580 ** FORM clause entry is iTable.  This routine make the necessary
1581 ** changes to pExpr so that it refers directly to the source table
1582 ** of the subquery rather the result set of the subquery.
1583 */
1584 static void substExprList(ExprList*,int,ExprList*);  /* Forward Decl */
1585 static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
1586   if( pExpr==0 ) return;
1587   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1588     if( pExpr->iColumn<0 ){
1589       pExpr->op = TK_NULL;
1590     }else{
1591       Expr *pNew;
1592       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1593       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1594       pNew = pEList->a[pExpr->iColumn].pExpr;
1595       assert( pNew!=0 );
1596       pExpr->op = pNew->op;
1597       assert( pExpr->pLeft==0 );
1598       pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
1599       assert( pExpr->pRight==0 );
1600       pExpr->pRight = sqlite3ExprDup(pNew->pRight);
1601       assert( pExpr->pList==0 );
1602       pExpr->pList = sqlite3ExprListDup(pNew->pList);
1603       pExpr->iTable = pNew->iTable;
1604       pExpr->iColumn = pNew->iColumn;
1605       pExpr->iAgg = pNew->iAgg;
1606       sqlite3TokenCopy(&pExpr->token, &pNew->token);
1607       sqlite3TokenCopy(&pExpr->span, &pNew->span);
1608     }
1609   }else{
1610     substExpr(pExpr->pLeft, iTable, pEList);
1611     substExpr(pExpr->pRight, iTable, pEList);
1612     substExprList(pExpr->pList, iTable, pEList);
1613   }
1614 }
1615 static void
1616 substExprList(ExprList *pList, int iTable, ExprList *pEList){
1617   int i;
1618   if( pList==0 ) return;
1619   for(i=0; i<pList->nExpr; i++){
1620     substExpr(pList->a[i].pExpr, iTable, pEList);
1621   }
1622 }
1623 
1624 /*
1625 ** This routine attempts to flatten subqueries in order to speed
1626 ** execution.  It returns 1 if it makes changes and 0 if no flattening
1627 ** occurs.
1628 **
1629 ** To understand the concept of flattening, consider the following
1630 ** query:
1631 **
1632 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1633 **
1634 ** The default way of implementing this query is to execute the
1635 ** subquery first and store the results in a temporary table, then
1636 ** run the outer query on that temporary table.  This requires two
1637 ** passes over the data.  Furthermore, because the temporary table
1638 ** has no indices, the WHERE clause on the outer query cannot be
1639 ** optimized.
1640 **
1641 ** This routine attempts to rewrite queries such as the above into
1642 ** a single flat select, like this:
1643 **
1644 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1645 **
1646 ** The code generated for this simpification gives the same result
1647 ** but only has to scan the data once.  And because indices might
1648 ** exist on the table t1, a complete scan of the data might be
1649 ** avoided.
1650 **
1651 ** Flattening is only attempted if all of the following are true:
1652 **
1653 **   (1)  The subquery and the outer query do not both use aggregates.
1654 **
1655 **   (2)  The subquery is not an aggregate or the outer query is not a join.
1656 **
1657 **   (3)  The subquery is not the right operand of a left outer join, or
1658 **        the subquery is not itself a join.  (Ticket #306)
1659 **
1660 **   (4)  The subquery is not DISTINCT or the outer query is not a join.
1661 **
1662 **   (5)  The subquery is not DISTINCT or the outer query does not use
1663 **        aggregates.
1664 **
1665 **   (6)  The subquery does not use aggregates or the outer query is not
1666 **        DISTINCT.
1667 **
1668 **   (7)  The subquery has a FROM clause.
1669 **
1670 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
1671 **
1672 **   (9)  The subquery does not use LIMIT or the outer query does not use
1673 **        aggregates.
1674 **
1675 **  (10)  The subquery does not use aggregates or the outer query does not
1676 **        use LIMIT.
1677 **
1678 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
1679 **
1680 **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
1681 **        subquery has no WHERE clause.  (added by ticket #350)
1682 **
1683 ** In this routine, the "p" parameter is a pointer to the outer query.
1684 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
1685 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1686 **
1687 ** If flattening is not attempted, this routine is a no-op and returns 0.
1688 ** If flattening is attempted this routine returns 1.
1689 **
1690 ** All of the expression analysis must occur on both the outer query and
1691 ** the subquery before this routine runs.
1692 */
1693 static int flattenSubquery(
1694   Parse *pParse,       /* The parsing context */
1695   Select *p,           /* The parent or outer SELECT statement */
1696   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
1697   int isAgg,           /* True if outer SELECT uses aggregate functions */
1698   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
1699 ){
1700   Select *pSub;       /* The inner query or "subquery" */
1701   SrcList *pSrc;      /* The FROM clause of the outer query */
1702   SrcList *pSubSrc;   /* The FROM clause of the subquery */
1703   ExprList *pList;    /* The result set of the outer query */
1704   int iParent;        /* VDBE cursor number of the pSub result set temp table */
1705   int i;
1706   Expr *pWhere;
1707 
1708   /* Check to see if flattening is permitted.  Return 0 if not.
1709   */
1710   if( p==0 ) return 0;
1711   pSrc = p->pSrc;
1712   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
1713   pSub = pSrc->a[iFrom].pSelect;
1714   assert( pSub!=0 );
1715   if( isAgg && subqueryIsAgg ) return 0;
1716   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
1717   pSubSrc = pSub->pSrc;
1718   assert( pSubSrc );
1719   if( pSubSrc->nSrc==0 ) return 0;
1720   if( (pSub->isDistinct || pSub->nLimit>=0) &&  (pSrc->nSrc>1 || isAgg) ){
1721      return 0;
1722   }
1723   if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
1724   if( p->pOrderBy && pSub->pOrderBy ) return 0;
1725 
1726   /* Restriction 3:  If the subquery is a join, make sure the subquery is
1727   ** not used as the right operand of an outer join.  Examples of why this
1728   ** is not allowed:
1729   **
1730   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
1731   **
1732   ** If we flatten the above, we would get
1733   **
1734   **         (t1 LEFT OUTER JOIN t2) JOIN t3
1735   **
1736   ** which is not at all the same thing.
1737   */
1738   if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1739     return 0;
1740   }
1741 
1742   /* Restriction 12:  If the subquery is the right operand of a left outer
1743   ** join, make sure the subquery has no WHERE clause.
1744   ** An examples of why this is not allowed:
1745   **
1746   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1747   **
1748   ** If we flatten the above, we would get
1749   **
1750   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1751   **
1752   ** But the t2.x>0 test will always fail on a NULL row of t2, which
1753   ** effectively converts the OUTER JOIN into an INNER JOIN.
1754   */
1755   if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
1756       && pSub->pWhere!=0 ){
1757     return 0;
1758   }
1759 
1760   /* If we reach this point, it means flattening is permitted for the
1761   ** iFrom-th entry of the FROM clause in the outer query.
1762   */
1763 
1764   /* Move all of the FROM elements of the subquery into the
1765   ** the FROM clause of the outer query.  Before doing this, remember
1766   ** the cursor number for the original outer query FROM element in
1767   ** iParent.  The iParent cursor will never be used.  Subsequent code
1768   ** will scan expressions looking for iParent references and replace
1769   ** those references with expressions that resolve to the subquery FROM
1770   ** elements we are now copying in.
1771   */
1772   iParent = pSrc->a[iFrom].iCursor;
1773   {
1774     int nSubSrc = pSubSrc->nSrc;
1775     int jointype = pSrc->a[iFrom].jointype;
1776 
1777     if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
1778       sqlite3DeleteTable(0, pSrc->a[iFrom].pTab);
1779     }
1780     sqliteFree(pSrc->a[iFrom].zDatabase);
1781     sqliteFree(pSrc->a[iFrom].zName);
1782     sqliteFree(pSrc->a[iFrom].zAlias);
1783     if( nSubSrc>1 ){
1784       int extra = nSubSrc - 1;
1785       for(i=1; i<nSubSrc; i++){
1786         pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
1787       }
1788       p->pSrc = pSrc;
1789       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1790         pSrc->a[i] = pSrc->a[i-extra];
1791       }
1792     }
1793     for(i=0; i<nSubSrc; i++){
1794       pSrc->a[i+iFrom] = pSubSrc->a[i];
1795       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1796     }
1797     pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
1798   }
1799 
1800   /* Now begin substituting subquery result set expressions for
1801   ** references to the iParent in the outer query.
1802   **
1803   ** Example:
1804   **
1805   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1806   **   \                     \_____________ subquery __________/          /
1807   **    \_____________________ outer query ______________________________/
1808   **
1809   ** We look at every expression in the outer query and every place we see
1810   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1811   */
1812   substExprList(p->pEList, iParent, pSub->pEList);
1813   pList = p->pEList;
1814   for(i=0; i<pList->nExpr; i++){
1815     Expr *pExpr;
1816     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
1817       pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
1818     }
1819   }
1820   if( isAgg ){
1821     substExprList(p->pGroupBy, iParent, pSub->pEList);
1822     substExpr(p->pHaving, iParent, pSub->pEList);
1823   }
1824   if( pSub->pOrderBy ){
1825     assert( p->pOrderBy==0 );
1826     p->pOrderBy = pSub->pOrderBy;
1827     pSub->pOrderBy = 0;
1828   }else if( p->pOrderBy ){
1829     substExprList(p->pOrderBy, iParent, pSub->pEList);
1830   }
1831   if( pSub->pWhere ){
1832     pWhere = sqlite3ExprDup(pSub->pWhere);
1833   }else{
1834     pWhere = 0;
1835   }
1836   if( subqueryIsAgg ){
1837     assert( p->pHaving==0 );
1838     p->pHaving = p->pWhere;
1839     p->pWhere = pWhere;
1840     substExpr(p->pHaving, iParent, pSub->pEList);
1841     if( pSub->pHaving ){
1842       Expr *pHaving = sqlite3ExprDup(pSub->pHaving);
1843       if( p->pHaving ){
1844         p->pHaving = sqlite3Expr(TK_AND, p->pHaving, pHaving, 0);
1845       }else{
1846         p->pHaving = pHaving;
1847       }
1848     }
1849     assert( p->pGroupBy==0 );
1850     p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
1851   }else if( p->pWhere==0 ){
1852     p->pWhere = pWhere;
1853   }else{
1854     substExpr(p->pWhere, iParent, pSub->pEList);
1855     if( pWhere ){
1856       p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pWhere, 0);
1857     }
1858   }
1859 
1860   /* The flattened query is distinct if either the inner or the
1861   ** outer query is distinct.
1862   */
1863   p->isDistinct = p->isDistinct || pSub->isDistinct;
1864 
1865   /* Transfer the limit expression from the subquery to the outer
1866   ** query.
1867   */
1868   if( pSub->nLimit>=0 ){
1869     if( p->nLimit<0 ){
1870       p->nLimit = pSub->nLimit;
1871     }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1872       p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1873     }
1874   }
1875   p->nOffset += pSub->nOffset;
1876 
1877   /* Finially, delete what is left of the subquery and return
1878   ** success.
1879   */
1880   sqlite3SelectDelete(pSub);
1881   return 1;
1882 }
1883 
1884 /*
1885 ** Analyze the SELECT statement passed in as an argument to see if it
1886 ** is a simple min() or max() query.  If it is and this query can be
1887 ** satisfied using a single seek to the beginning or end of an index,
1888 ** then generate the code for this SELECT and return 1.  If this is not a
1889 ** simple min() or max() query, then return 0;
1890 **
1891 ** A simply min() or max() query looks like this:
1892 **
1893 **    SELECT min(a) FROM table;
1894 **    SELECT max(a) FROM table;
1895 **
1896 ** The query may have only a single table in its FROM argument.  There
1897 ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
1898 ** be the min() or max() of a single column of the table.  The column
1899 ** in the min() or max() function must be indexed.
1900 **
1901 ** The parameters to this routine are the same as for sqlite3Select().
1902 ** See the header comment on that routine for additional information.
1903 */
1904 static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
1905   Expr *pExpr;
1906   int iCol;
1907   Table *pTab;
1908   Index *pIdx;
1909   int base;
1910   Vdbe *v;
1911   int seekOp;
1912   int cont;
1913   ExprList *pEList, *pList, eList;
1914   struct ExprList_item eListItem;
1915   SrcList *pSrc;
1916 
1917 
1918   /* Check to see if this query is a simple min() or max() query.  Return
1919   ** zero if it is  not.
1920   */
1921   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
1922   pSrc = p->pSrc;
1923   if( pSrc->nSrc!=1 ) return 0;
1924   pEList = p->pEList;
1925   if( pEList->nExpr!=1 ) return 0;
1926   pExpr = pEList->a[0].pExpr;
1927   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
1928   pList = pExpr->pList;
1929   if( pList==0 || pList->nExpr!=1 ) return 0;
1930   if( pExpr->token.n!=3 ) return 0;
1931   if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
1932     seekOp = OP_Rewind;
1933   }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
1934     seekOp = OP_Last;
1935   }else{
1936     return 0;
1937   }
1938   pExpr = pList->a[0].pExpr;
1939   if( pExpr->op!=TK_COLUMN ) return 0;
1940   iCol = pExpr->iColumn;
1941   pTab = pSrc->a[0].pTab;
1942 
1943   /* If we get to here, it means the query is of the correct form.
1944   ** Check to make sure we have an index and make pIdx point to the
1945   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
1946   ** key column, no index is necessary so set pIdx to NULL.  If no
1947   ** usable index is found, return 0.
1948   */
1949   if( iCol<0 ){
1950     pIdx = 0;
1951   }else{
1952     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1953       assert( pIdx->nColumn>=1 );
1954       if( pIdx->aiColumn[0]==iCol ) break;
1955     }
1956     if( pIdx==0 ) return 0;
1957   }
1958 
1959   /* Identify column types if we will be using the callback.  This
1960   ** step is skipped if the output is going to a table or a memory cell.
1961   ** The column names have already been generated in the calling function.
1962   */
1963   v = sqlite3GetVdbe(pParse);
1964   if( v==0 ) return 0;
1965 
1966   /* If the output is destined for a temporary table, open that table.
1967   */
1968   if( eDest==SRT_TempTable ){
1969     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
1970     sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
1971   }
1972 
1973   /* Generating code to find the min or the max.  Basically all we have
1974   ** to do is find the first or the last entry in the chosen index.  If
1975   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
1976   ** or last entry in the main table.
1977   */
1978   sqlite3CodeVerifySchema(pParse, pTab->iDb);
1979   base = pSrc->a[0].iCursor;
1980   computeLimitRegisters(pParse, p);
1981   if( pSrc->a[0].pSelect==0 ){
1982     sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
1983     sqlite3VdbeAddOp(v, OP_OpenRead, base, pTab->tnum);
1984     sqlite3VdbeAddOp(v, OP_SetNumColumns, base, pTab->nCol);
1985   }
1986   cont = sqlite3VdbeMakeLabel(v);
1987   if( pIdx==0 ){
1988     sqlite3VdbeAddOp(v, seekOp, base, 0);
1989   }else{
1990     sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
1991     sqlite3VdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum,
1992                    (char*)&pIdx->keyInfo, P3_KEYINFO);
1993     sqlite3VdbeAddOp(v, seekOp, base+1, 0);
1994     sqlite3VdbeAddOp(v, OP_IdxRecno, base+1, 0);
1995     sqlite3VdbeAddOp(v, OP_Close, base+1, 0);
1996     sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
1997   }
1998   eList.nExpr = 1;
1999   memset(&eListItem, 0, sizeof(eListItem));
2000   eList.a = &eListItem;
2001   eList.a[0].pExpr = pExpr;
2002   selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
2003   sqlite3VdbeResolveLabel(v, cont);
2004   sqlite3VdbeAddOp(v, OP_Close, base, 0);
2005 
2006   return 1;
2007 }
2008 
2009 /*
2010 ** Generate code for the given SELECT statement.
2011 **
2012 ** The results are distributed in various ways depending on the
2013 ** value of eDest and iParm.
2014 **
2015 **     eDest Value       Result
2016 **     ------------    -------------------------------------------
2017 **     SRT_Callback    Invoke the callback for each row of the result.
2018 **
2019 **     SRT_Mem         Store first result in memory cell iParm
2020 **
2021 **     SRT_Set         Store results as keys of table iParm.
2022 **
2023 **     SRT_Union       Store results as a key in a temporary table iParm
2024 **
2025 **     SRT_Except      Remove results from the temporary table iParm.
2026 **
2027 **     SRT_Table       Store results in temporary table iParm
2028 **
2029 ** The table above is incomplete.  Additional eDist value have be added
2030 ** since this comment was written.  See the selectInnerLoop() function for
2031 ** a complete listing of the allowed values of eDest and their meanings.
2032 **
2033 ** This routine returns the number of errors.  If any errors are
2034 ** encountered, then an appropriate error message is left in
2035 ** pParse->zErrMsg.
2036 **
2037 ** This routine does NOT free the Select structure passed in.  The
2038 ** calling function needs to do that.
2039 **
2040 ** The pParent, parentTab, and *pParentAgg fields are filled in if this
2041 ** SELECT is a subquery.  This routine may try to combine this SELECT
2042 ** with its parent to form a single flat query.  In so doing, it might
2043 ** change the parent query from a non-aggregate to an aggregate query.
2044 ** For that reason, the pParentAgg flag is passed as a pointer, so it
2045 ** can be changed.
2046 **
2047 ** Example 1:   The meaning of the pParent parameter.
2048 **
2049 **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2050 **    \                      \_______ subquery _______/        /
2051 **     \                                                      /
2052 **      \____________________ outer query ___________________/
2053 **
2054 ** This routine is called for the outer query first.   For that call,
2055 ** pParent will be NULL.  During the processing of the outer query, this
2056 ** routine is called recursively to handle the subquery.  For the recursive
2057 ** call, pParent will point to the outer query.  Because the subquery is
2058 ** the second element in a three-way join, the parentTab parameter will
2059 ** be 1 (the 2nd value of a 0-indexed array.)
2060 */
2061 int sqlite3Select(
2062   Parse *pParse,         /* The parser context */
2063   Select *p,             /* The SELECT statement being coded. */
2064   int eDest,             /* How to dispose of the results */
2065   int iParm,             /* A parameter used by the eDest disposal method */
2066   Select *pParent,       /* Another SELECT for which this is a sub-query */
2067   int parentTab,         /* Index in pParent->pSrc of this query */
2068   int *pParentAgg,       /* True if pParent uses aggregate functions */
2069   char *aff              /* If eDest is SRT_Union, the affinity string */
2070 ){
2071   int i;
2072   WhereInfo *pWInfo;
2073   Vdbe *v;
2074   int isAgg = 0;         /* True for select lists like "count(*)" */
2075   ExprList *pEList;      /* List of columns to extract. */
2076   SrcList *pTabList;     /* List of tables to select from */
2077   Expr *pWhere;          /* The WHERE clause.  May be NULL */
2078   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
2079   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
2080   Expr *pHaving;         /* The HAVING clause.  May be NULL */
2081   int isDistinct;        /* True if the DISTINCT keyword is present */
2082   int distinct;          /* Table to use for the distinct set */
2083   int rc = 1;            /* Value to return from this function */
2084 
2085   if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
2086   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
2087 
2088   /* If there is are a sequence of queries, do the earlier ones first.
2089   */
2090   if( p->pPrior ){
2091     return multiSelect(pParse, p, eDest, iParm, aff);
2092   }
2093 
2094   /* Make local copies of the parameters for this query.
2095   */
2096   pTabList = p->pSrc;
2097   pWhere = p->pWhere;
2098   pOrderBy = p->pOrderBy;
2099   pGroupBy = p->pGroupBy;
2100   pHaving = p->pHaving;
2101   isDistinct = p->isDistinct;
2102 
2103   /* Allocate VDBE cursors for each table in the FROM clause
2104   */
2105   sqlite3SrcListAssignCursors(pParse, pTabList);
2106 
2107   /*
2108   ** Do not even attempt to generate any code if we have already seen
2109   ** errors before this routine starts.
2110   */
2111   if( pParse->nErr>0 ) goto select_end;
2112 
2113   /* Expand any "*" terms in the result set.  (For example the "*" in
2114   ** "SELECT * FROM t1")  The fillInColumnlist() routine also does some
2115   ** other housekeeping - see the header comment for details.
2116   */
2117   if( fillInColumnList(pParse, p) ){
2118     goto select_end;
2119   }
2120   pWhere = p->pWhere;
2121   pEList = p->pEList;
2122   if( pEList==0 ) goto select_end;
2123 
2124   /* If writing to memory or generating a set
2125   ** only a single column may be output.
2126   */
2127   if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
2128     sqlite3ErrorMsg(pParse, "only a single result allowed for "
2129        "a SELECT that is part of an expression");
2130     goto select_end;
2131   }
2132 
2133   /* ORDER BY is ignored for some destinations.
2134   */
2135   switch( eDest ){
2136     case SRT_Union:
2137     case SRT_Except:
2138     case SRT_Discard:
2139     case SRT_Set:
2140       pOrderBy = 0;
2141       break;
2142     default:
2143       break;
2144   }
2145 
2146   /* At this point, we should have allocated all the cursors that we
2147   ** need to handle subquerys and temporary tables.
2148   **
2149   ** Resolve the column names and do a semantics check on all the expressions.
2150   */
2151   for(i=0; i<pEList->nExpr; i++){
2152     if( sqlite3ExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
2153       goto select_end;
2154     }
2155     if( sqlite3ExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
2156       goto select_end;
2157     }
2158   }
2159   if( pWhere ){
2160     if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pWhere) ){
2161       goto select_end;
2162     }
2163     if( sqlite3ExprCheck(pParse, pWhere, 0, 0) ){
2164       goto select_end;
2165     }
2166   }
2167   if( pHaving ){
2168     if( pGroupBy==0 ){
2169       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2170       goto select_end;
2171     }
2172     if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pHaving) ){
2173       goto select_end;
2174     }
2175     if( sqlite3ExprCheck(pParse, pHaving, 1, &isAgg) ){
2176       goto select_end;
2177     }
2178   }
2179   if( pOrderBy ){
2180     for(i=0; i<pOrderBy->nExpr; i++){
2181       int iCol;
2182       Expr *pE = pOrderBy->a[i].pExpr;
2183       if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2184         sqlite3ExprDelete(pE);
2185         pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
2186       }
2187       if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
2188         goto select_end;
2189       }
2190       if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
2191         goto select_end;
2192       }
2193       if( sqlite3ExprIsConstant(pE) ){
2194         if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2195           sqlite3ErrorMsg(pParse,
2196              "ORDER BY terms must not be non-integer constants");
2197           goto select_end;
2198         }else if( iCol<=0 || iCol>pEList->nExpr ){
2199           sqlite3ErrorMsg(pParse,
2200              "ORDER BY column number %d out of range - should be "
2201              "between 1 and %d", iCol, pEList->nExpr);
2202           goto select_end;
2203         }
2204       }
2205     }
2206   }
2207   if( pGroupBy ){
2208     for(i=0; i<pGroupBy->nExpr; i++){
2209       int iCol;
2210       Expr *pE = pGroupBy->a[i].pExpr;
2211       if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2212         sqlite3ExprDelete(pE);
2213         pE = pGroupBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
2214       }
2215       if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
2216         goto select_end;
2217       }
2218       if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
2219         goto select_end;
2220       }
2221       if( sqlite3ExprIsConstant(pE) ){
2222         if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2223           sqlite3ErrorMsg(pParse,
2224             "GROUP BY terms must not be non-integer constants");
2225           goto select_end;
2226         }else if( iCol<=0 || iCol>pEList->nExpr ){
2227           sqlite3ErrorMsg(pParse,
2228              "GROUP BY column number %d out of range - should be "
2229              "between 1 and %d", iCol, pEList->nExpr);
2230           goto select_end;
2231         }
2232       }
2233     }
2234   }
2235 
2236   /* Begin generating code.
2237   */
2238   v = sqlite3GetVdbe(pParse);
2239   if( v==0 ) goto select_end;
2240 
2241   /* Identify column names if we will be using them in a callback.  This
2242   ** step is skipped if the output is going to some other destination.
2243   */
2244   if( eDest==SRT_Callback ){
2245     generateColumnNames(pParse, pTabList, pEList);
2246   }
2247 
2248 #if 1  /* I do not think we need the following code any more.... */
2249   /* If the destination is SRT_Union, then set the number of columns in
2250   ** the records that will be inserted into the temporary table. The caller
2251   ** couldn't do this, in case the select statement is of the form
2252   ** "SELECT * FROM ....".
2253   **
2254   ** We need to do this before we start inserting records into the
2255   ** temporary table (which has had OP_KeyAsData executed on it), because
2256   ** it is required by the key comparison function. So do it now, even
2257   ** though this means that OP_SetNumColumns may be executed on the same
2258   ** cursor more than once.
2259   */
2260   if( eDest==SRT_Union ){
2261     sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
2262   }
2263 #endif
2264 
2265   /* Generate code for all sub-queries in the FROM clause
2266   */
2267   for(i=0; i<pTabList->nSrc; i++){
2268     const char *zSavedAuthContext;
2269     int needRestoreContext;
2270 
2271     if( pTabList->a[i].pSelect==0 ) continue;
2272     if( pTabList->a[i].zName!=0 ){
2273       zSavedAuthContext = pParse->zAuthContext;
2274       pParse->zAuthContext = pTabList->a[i].zName;
2275       needRestoreContext = 1;
2276     }else{
2277       needRestoreContext = 0;
2278     }
2279     sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
2280                  pTabList->a[i].iCursor, p, i, &isAgg, 0);
2281     if( needRestoreContext ){
2282       pParse->zAuthContext = zSavedAuthContext;
2283     }
2284     pTabList = p->pSrc;
2285     pWhere = p->pWhere;
2286     if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
2287       pOrderBy = p->pOrderBy;
2288     }
2289     pGroupBy = p->pGroupBy;
2290     pHaving = p->pHaving;
2291     isDistinct = p->isDistinct;
2292   }
2293 
2294   /* Check for the special case of a min() or max() function by itself
2295   ** in the result set.
2296   */
2297   if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2298     rc = 0;
2299     goto select_end;
2300   }
2301 
2302   /* Check to see if this is a subquery that can be "flattened" into its parent.
2303   ** If flattening is a possiblity, do so and return immediately.
2304   */
2305   if( pParent && pParentAgg &&
2306       flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
2307     if( isAgg ) *pParentAgg = 1;
2308     return rc;
2309   }
2310 
2311   /* If there is an ORDER BY clause, resolve any collation sequences
2312   ** names that have been explicitly specified.
2313   */
2314   if( pOrderBy ){
2315     for(i=0; i<pOrderBy->nExpr; i++){
2316       if( pOrderBy->a[i].zName ){
2317         pOrderBy->a[i].pExpr->pColl =
2318             sqlite3LocateCollSeq(pParse, pOrderBy->a[i].zName, -1);
2319       }
2320     }
2321     if( pParse->nErr ){
2322       goto select_end;
2323     }
2324   }
2325 
2326   /* Set the limiter.
2327   */
2328   computeLimitRegisters(pParse, p);
2329 
2330   /* If the output is destined for a temporary table, open that table.
2331   */
2332   if( eDest==SRT_TempTable ){
2333     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
2334     sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
2335   }
2336 
2337   /* Do an analysis of aggregate expressions.
2338   */
2339   sqliteAggregateInfoReset(pParse);
2340   if( isAgg || pGroupBy ){
2341     assert( pParse->nAgg==0 );
2342     isAgg = 1;
2343     for(i=0; i<pEList->nExpr; i++){
2344       if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
2345         goto select_end;
2346       }
2347     }
2348     if( pGroupBy ){
2349       for(i=0; i<pGroupBy->nExpr; i++){
2350         if( sqlite3ExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
2351           goto select_end;
2352         }
2353       }
2354     }
2355     if( pHaving && sqlite3ExprAnalyzeAggregates(pParse, pHaving) ){
2356       goto select_end;
2357     }
2358     if( pOrderBy ){
2359       for(i=0; i<pOrderBy->nExpr; i++){
2360         if( sqlite3ExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
2361           goto select_end;
2362         }
2363       }
2364     }
2365   }
2366 
2367   /* Reset the aggregator
2368   */
2369   if( isAgg ){
2370     sqlite3VdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
2371     for(i=0; i<pParse->nAgg; i++){
2372       FuncDef *pFunc;
2373       if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
2374         sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_FUNCDEF);
2375       }
2376     }
2377     if( pGroupBy==0 ){
2378       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
2379       sqlite3VdbeAddOp(v, OP_AggFocus, 0, 0);
2380     }
2381   }
2382 
2383   /* Initialize the memory cell to NULL
2384   */
2385   if( eDest==SRT_Mem ){
2386     sqlite3VdbeAddOp(v, OP_String8, 0, 0);
2387     sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
2388   }
2389 
2390   /* Open a temporary table to use for the distinct set.
2391   */
2392   if( isDistinct ){
2393     distinct = pParse->nTab++;
2394     openTempIndex(pParse, p, distinct, 0);
2395   }else{
2396     distinct = -1;
2397   }
2398 
2399   /* Begin the database scan
2400   */
2401   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
2402                             pGroupBy ? 0 : &pOrderBy);
2403   if( pWInfo==0 ) goto select_end;
2404 
2405   /* Use the standard inner loop if we are not dealing with
2406   ** aggregates
2407   */
2408   if( !isAgg ){
2409     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2410                     iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
2411        goto select_end;
2412     }
2413   }
2414 
2415   /* If we are dealing with aggregates, then do the special aggregate
2416   ** processing.
2417   */
2418   else{
2419     AggExpr *pAgg;
2420     if( pGroupBy ){
2421       int lbl1;
2422       for(i=0; i<pGroupBy->nExpr; i++){
2423         sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
2424       }
2425       /* No affinity string is attached to the following OP_MakeKey
2426       ** because we do not need to do any coercion of datatypes. */
2427       sqlite3VdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
2428       lbl1 = sqlite3VdbeMakeLabel(v);
2429       sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
2430       for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2431         if( pAgg->isAgg ) continue;
2432         sqlite3ExprCode(pParse, pAgg->pExpr);
2433         sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
2434       }
2435       sqlite3VdbeResolveLabel(v, lbl1);
2436     }
2437     for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2438       Expr *pE;
2439       int nExpr;
2440       FuncDef *pDef;
2441       if( !pAgg->isAgg ) continue;
2442       assert( pAgg->pFunc!=0 );
2443       assert( pAgg->pFunc->xStep!=0 );
2444       pDef = pAgg->pFunc;
2445       pE = pAgg->pExpr;
2446       assert( pE!=0 );
2447       assert( pE->op==TK_AGG_FUNCTION );
2448       nExpr = sqlite3ExprCodeExprList(pParse, pE->pList);
2449       sqlite3VdbeAddOp(v, OP_Integer, i, 0);
2450       sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
2451     }
2452   }
2453 
2454   /* End the database scan loop.
2455   */
2456   sqlite3WhereEnd(pWInfo);
2457 
2458   /* If we are processing aggregates, we need to set up a second loop
2459   ** over all of the aggregate values and process them.
2460   */
2461   if( isAgg ){
2462     int endagg = sqlite3VdbeMakeLabel(v);
2463     int startagg;
2464     startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
2465     pParse->useAgg = 1;
2466     if( pHaving ){
2467       sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
2468     }
2469     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2470                     iParm, startagg, endagg, aff) ){
2471       goto select_end;
2472     }
2473     sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
2474     sqlite3VdbeResolveLabel(v, endagg);
2475     sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
2476     pParse->useAgg = 0;
2477   }
2478 
2479   /* If there is an ORDER BY clause, then we need to sort the results
2480   ** and send them to the callback one by one.
2481   */
2482   if( pOrderBy ){
2483     generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
2484   }
2485 
2486   /* If this was a subquery, we have now converted the subquery into a
2487   ** temporary table.  So delete the subquery structure from the parent
2488   ** to prevent this subquery from being evaluated again and to force the
2489   ** the use of the temporary table.
2490   */
2491   if( pParent ){
2492     assert( pParent->pSrc->nSrc>parentTab );
2493     assert( pParent->pSrc->a[parentTab].pSelect==p );
2494     sqlite3SelectDelete(p);
2495     pParent->pSrc->a[parentTab].pSelect = 0;
2496   }
2497 
2498   /* The SELECT was successfully coded.   Set the return code to 0
2499   ** to indicate no errors.
2500   */
2501   rc = 0;
2502 
2503   /* Control jumps to here if an error is encountered above, or upon
2504   ** successful coding of the SELECT.
2505   */
2506 select_end:
2507   sqliteAggregateInfoReset(pParse);
2508   return rc;
2509 }
2510