xref: /sqlite-3.40.0/src/select.c (revision fd3b2226)
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.526 2009/08/01 15:09:58 drh Exp $
16 */
17 #include "sqliteInt.h"
18 
19 
20 /*
21 ** Delete all the content of a Select structure but do not deallocate
22 ** the select structure itself.
23 */
24 static void clearSelect(sqlite3 *db, Select *p){
25   sqlite3ExprListDelete(db, p->pEList);
26   sqlite3SrcListDelete(db, p->pSrc);
27   sqlite3ExprDelete(db, p->pWhere);
28   sqlite3ExprListDelete(db, p->pGroupBy);
29   sqlite3ExprDelete(db, p->pHaving);
30   sqlite3ExprListDelete(db, p->pOrderBy);
31   sqlite3SelectDelete(db, p->pPrior);
32   sqlite3ExprDelete(db, p->pLimit);
33   sqlite3ExprDelete(db, p->pOffset);
34 }
35 
36 /*
37 ** Initialize a SelectDest structure.
38 */
39 void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
40   pDest->eDest = (u8)eDest;
41   pDest->iParm = iParm;
42   pDest->affinity = 0;
43   pDest->iMem = 0;
44   pDest->nMem = 0;
45 }
46 
47 
48 /*
49 ** Allocate a new Select structure and return a pointer to that
50 ** structure.
51 */
52 Select *sqlite3SelectNew(
53   Parse *pParse,        /* Parsing context */
54   ExprList *pEList,     /* which columns to include in the result */
55   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
56   Expr *pWhere,         /* the WHERE clause */
57   ExprList *pGroupBy,   /* the GROUP BY clause */
58   Expr *pHaving,        /* the HAVING clause */
59   ExprList *pOrderBy,   /* the ORDER BY clause */
60   int isDistinct,       /* true if the DISTINCT keyword is present */
61   Expr *pLimit,         /* LIMIT value.  NULL means not used */
62   Expr *pOffset         /* OFFSET value.  NULL means no offset */
63 ){
64   Select *pNew;
65   Select standin;
66   sqlite3 *db = pParse->db;
67   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
68   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
69   if( pNew==0 ){
70     pNew = &standin;
71     memset(pNew, 0, sizeof(*pNew));
72   }
73   if( pEList==0 ){
74     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
75   }
76   pNew->pEList = pEList;
77   pNew->pSrc = pSrc;
78   pNew->pWhere = pWhere;
79   pNew->pGroupBy = pGroupBy;
80   pNew->pHaving = pHaving;
81   pNew->pOrderBy = pOrderBy;
82   pNew->selFlags = isDistinct ? SF_Distinct : 0;
83   pNew->op = TK_SELECT;
84   pNew->pLimit = pLimit;
85   pNew->pOffset = pOffset;
86   assert( pOffset==0 || pLimit!=0 );
87   pNew->addrOpenEphm[0] = -1;
88   pNew->addrOpenEphm[1] = -1;
89   pNew->addrOpenEphm[2] = -1;
90   if( db->mallocFailed ) {
91     clearSelect(db, pNew);
92     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
93     pNew = 0;
94   }
95   return pNew;
96 }
97 
98 /*
99 ** Delete the given Select structure and all of its substructures.
100 */
101 void sqlite3SelectDelete(sqlite3 *db, Select *p){
102   if( p ){
103     clearSelect(db, p);
104     sqlite3DbFree(db, p);
105   }
106 }
107 
108 /*
109 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
110 ** type of join.  Return an integer constant that expresses that type
111 ** in terms of the following bit values:
112 **
113 **     JT_INNER
114 **     JT_CROSS
115 **     JT_OUTER
116 **     JT_NATURAL
117 **     JT_LEFT
118 **     JT_RIGHT
119 **
120 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
121 **
122 ** If an illegal or unsupported join type is seen, then still return
123 ** a join type, but put an error in the pParse structure.
124 */
125 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
126   int jointype = 0;
127   Token *apAll[3];
128   Token *p;
129                              /*   0123456789 123456789 123456789 123 */
130   static const char zKeyText[] = "naturaleftouterightfullinnercross";
131   static const struct {
132     u8 i;        /* Beginning of keyword text in zKeyText[] */
133     u8 nChar;    /* Length of the keyword in characters */
134     u8 code;     /* Join type mask */
135   } aKeyword[] = {
136     /* natural */ { 0,  7, JT_NATURAL                },
137     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
138     /* outer   */ { 10, 5, JT_OUTER                  },
139     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
140     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
141     /* inner   */ { 23, 5, JT_INNER                  },
142     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
143   };
144   int i, j;
145   apAll[0] = pA;
146   apAll[1] = pB;
147   apAll[2] = pC;
148   for(i=0; i<3 && apAll[i]; i++){
149     p = apAll[i];
150     for(j=0; j<ArraySize(aKeyword); j++){
151       if( p->n==aKeyword[j].nChar
152           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
153         jointype |= aKeyword[j].code;
154         break;
155       }
156     }
157     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
158     if( j>=ArraySize(aKeyword) ){
159       jointype |= JT_ERROR;
160       break;
161     }
162   }
163   if(
164      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
165      (jointype & JT_ERROR)!=0
166   ){
167     const char *zSp = " ";
168     assert( pB!=0 );
169     if( pC==0 ){ zSp++; }
170     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
171        "%T %T%s%T", pA, pB, zSp, pC);
172     jointype = JT_INNER;
173   }else if( (jointype & JT_OUTER)!=0
174          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
175     sqlite3ErrorMsg(pParse,
176       "RIGHT and FULL OUTER JOINs are not currently supported");
177     jointype = JT_INNER;
178   }
179   return jointype;
180 }
181 
182 /*
183 ** Return the index of a column in a table.  Return -1 if the column
184 ** is not contained in the table.
185 */
186 static int columnIndex(Table *pTab, const char *zCol){
187   int i;
188   for(i=0; i<pTab->nCol; i++){
189     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
190   }
191   return -1;
192 }
193 
194 /*
195 ** Create an expression node for an identifier with the name of zName
196 */
197 Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
198   return sqlite3Expr(pParse->db, TK_ID, zName);
199 }
200 
201 /*
202 ** Add a term to the WHERE expression in *ppExpr that requires the
203 ** zCol column to be equal in the two tables pTab1 and pTab2.
204 */
205 static void addWhereTerm(
206   Parse *pParse,           /* Parsing context */
207   const char *zCol,        /* Name of the column */
208   const Table *pTab1,      /* First table */
209   const char *zAlias1,     /* Alias for first table.  May be NULL */
210   const Table *pTab2,      /* Second table */
211   const char *zAlias2,     /* Alias for second table.  May be NULL */
212   int iRightJoinTable,     /* VDBE cursor for the right table */
213   Expr **ppExpr,           /* Add the equality term to this expression */
214   int isOuterJoin          /* True if dealing with an OUTER join */
215 ){
216   Expr *pE1a, *pE1b, *pE1c;
217   Expr *pE2a, *pE2b, *pE2c;
218   Expr *pE;
219 
220   pE1a = sqlite3CreateIdExpr(pParse, zCol);
221   pE2a = sqlite3CreateIdExpr(pParse, zCol);
222   if( zAlias1==0 ){
223     zAlias1 = pTab1->zName;
224   }
225   pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
226   if( zAlias2==0 ){
227     zAlias2 = pTab2->zName;
228   }
229   pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
230   pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
231   pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
232   pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
233   if( pE && isOuterJoin ){
234     ExprSetProperty(pE, EP_FromJoin);
235     assert( !ExprHasAnyProperty(pE, EP_TokenOnly|EP_Reduced) );
236     ExprSetIrreducible(pE);
237     pE->iRightJoinTable = (i16)iRightJoinTable;
238   }
239   *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
240 }
241 
242 /*
243 ** Set the EP_FromJoin property on all terms of the given expression.
244 ** And set the Expr.iRightJoinTable to iTable for every term in the
245 ** expression.
246 **
247 ** The EP_FromJoin property is used on terms of an expression to tell
248 ** the LEFT OUTER JOIN processing logic that this term is part of the
249 ** join restriction specified in the ON or USING clause and not a part
250 ** of the more general WHERE clause.  These terms are moved over to the
251 ** WHERE clause during join processing but we need to remember that they
252 ** originated in the ON or USING clause.
253 **
254 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
255 ** expression depends on table iRightJoinTable even if that table is not
256 ** explicitly mentioned in the expression.  That information is needed
257 ** for cases like this:
258 **
259 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
260 **
261 ** The where clause needs to defer the handling of the t1.x=5
262 ** term until after the t2 loop of the join.  In that way, a
263 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
264 ** defer the handling of t1.x=5, it will be processed immediately
265 ** after the t1 loop and rows with t1.x!=5 will never appear in
266 ** the output, which is incorrect.
267 */
268 static void setJoinExpr(Expr *p, int iTable){
269   while( p ){
270     ExprSetProperty(p, EP_FromJoin);
271     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
272     ExprSetIrreducible(p);
273     p->iRightJoinTable = (i16)iTable;
274     setJoinExpr(p->pLeft, iTable);
275     p = p->pRight;
276   }
277 }
278 
279 /*
280 ** This routine processes the join information for a SELECT statement.
281 ** ON and USING clauses are converted into extra terms of the WHERE clause.
282 ** NATURAL joins also create extra WHERE clause terms.
283 **
284 ** The terms of a FROM clause are contained in the Select.pSrc structure.
285 ** The left most table is the first entry in Select.pSrc.  The right-most
286 ** table is the last entry.  The join operator is held in the entry to
287 ** the left.  Thus entry 0 contains the join operator for the join between
288 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
289 ** also attached to the left entry.
290 **
291 ** This routine returns the number of errors encountered.
292 */
293 static int sqliteProcessJoin(Parse *pParse, Select *p){
294   SrcList *pSrc;                  /* All tables in the FROM clause */
295   int i, j;                       /* Loop counters */
296   struct SrcList_item *pLeft;     /* Left table being joined */
297   struct SrcList_item *pRight;    /* Right table being joined */
298 
299   pSrc = p->pSrc;
300   pLeft = &pSrc->a[0];
301   pRight = &pLeft[1];
302   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
303     Table *pLeftTab = pLeft->pTab;
304     Table *pRightTab = pRight->pTab;
305     int isOuter;
306 
307     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
308     isOuter = (pRight->jointype & JT_OUTER)!=0;
309 
310     /* When the NATURAL keyword is present, add WHERE clause terms for
311     ** every column that the two tables have in common.
312     */
313     if( pRight->jointype & JT_NATURAL ){
314       if( pRight->pOn || pRight->pUsing ){
315         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
316            "an ON or USING clause", 0);
317         return 1;
318       }
319       for(j=0; j<pLeftTab->nCol; j++){
320         char *zName = pLeftTab->aCol[j].zName;
321         if( columnIndex(pRightTab, zName)>=0 ){
322           addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
323                               pRightTab, pRight->zAlias,
324                               pRight->iCursor, &p->pWhere, isOuter);
325 
326         }
327       }
328     }
329 
330     /* Disallow both ON and USING clauses in the same join
331     */
332     if( pRight->pOn && pRight->pUsing ){
333       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
334         "clauses in the same join");
335       return 1;
336     }
337 
338     /* Add the ON clause to the end of the WHERE clause, connected by
339     ** an AND operator.
340     */
341     if( pRight->pOn ){
342       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
343       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
344       pRight->pOn = 0;
345     }
346 
347     /* Create extra terms on the WHERE clause for each column named
348     ** in the USING clause.  Example: If the two tables to be joined are
349     ** A and B and the USING clause names X, Y, and Z, then add this
350     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
351     ** Report an error if any column mentioned in the USING clause is
352     ** not contained in both tables to be joined.
353     */
354     if( pRight->pUsing ){
355       IdList *pList = pRight->pUsing;
356       for(j=0; j<pList->nId; j++){
357         char *zName = pList->a[j].zName;
358         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
359           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
360             "not present in both tables", zName);
361           return 1;
362         }
363         addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
364                             pRightTab, pRight->zAlias,
365                             pRight->iCursor, &p->pWhere, isOuter);
366       }
367     }
368   }
369   return 0;
370 }
371 
372 /*
373 ** Insert code into "v" that will push the record on the top of the
374 ** stack into the sorter.
375 */
376 static void pushOntoSorter(
377   Parse *pParse,         /* Parser context */
378   ExprList *pOrderBy,    /* The ORDER BY clause */
379   Select *pSelect,       /* The whole SELECT statement */
380   int regData            /* Register holding data to be sorted */
381 ){
382   Vdbe *v = pParse->pVdbe;
383   int nExpr = pOrderBy->nExpr;
384   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
385   int regRecord = sqlite3GetTempReg(pParse);
386   sqlite3ExprCacheClear(pParse);
387   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
388   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
389   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
390   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
391   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
392   sqlite3ReleaseTempReg(pParse, regRecord);
393   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
394   if( pSelect->iLimit ){
395     int addr1, addr2;
396     int iLimit;
397     if( pSelect->iOffset ){
398       iLimit = pSelect->iOffset+1;
399     }else{
400       iLimit = pSelect->iLimit;
401     }
402     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
403     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
404     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
405     sqlite3VdbeJumpHere(v, addr1);
406     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
407     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
408     sqlite3VdbeJumpHere(v, addr2);
409     pSelect->iLimit = 0;
410   }
411 }
412 
413 /*
414 ** Add code to implement the OFFSET
415 */
416 static void codeOffset(
417   Vdbe *v,          /* Generate code into this VM */
418   Select *p,        /* The SELECT statement being coded */
419   int iContinue     /* Jump here to skip the current record */
420 ){
421   if( p->iOffset && iContinue!=0 ){
422     int addr;
423     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
424     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
425     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
426     VdbeComment((v, "skip OFFSET records"));
427     sqlite3VdbeJumpHere(v, addr);
428   }
429 }
430 
431 /*
432 ** Add code that will check to make sure the N registers starting at iMem
433 ** form a distinct entry.  iTab is a sorting index that holds previously
434 ** seen combinations of the N values.  A new entry is made in iTab
435 ** if the current N values are new.
436 **
437 ** A jump to addrRepeat is made and the N+1 values are popped from the
438 ** stack if the top N elements are not distinct.
439 */
440 static void codeDistinct(
441   Parse *pParse,     /* Parsing and code generating context */
442   int iTab,          /* A sorting index used to test for distinctness */
443   int addrRepeat,    /* Jump to here if not distinct */
444   int N,             /* Number of elements */
445   int iMem           /* First element */
446 ){
447   Vdbe *v;
448   int r1;
449 
450   v = pParse->pVdbe;
451   r1 = sqlite3GetTempReg(pParse);
452   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
453   sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1);
454   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
455   sqlite3ReleaseTempReg(pParse, r1);
456 }
457 
458 /*
459 ** Generate an error message when a SELECT is used within a subexpression
460 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
461 ** column.  We do this in a subroutine because the error occurs in multiple
462 ** places.
463 */
464 static int checkForMultiColumnSelectError(
465   Parse *pParse,       /* Parse context. */
466   SelectDest *pDest,   /* Destination of SELECT results */
467   int nExpr            /* Number of result columns returned by SELECT */
468 ){
469   int eDest = pDest->eDest;
470   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
471     sqlite3ErrorMsg(pParse, "only a single result allowed for "
472        "a SELECT that is part of an expression");
473     return 1;
474   }else{
475     return 0;
476   }
477 }
478 
479 /*
480 ** This routine generates the code for the inside of the inner loop
481 ** of a SELECT.
482 **
483 ** If srcTab and nColumn are both zero, then the pEList expressions
484 ** are evaluated in order to get the data for this row.  If nColumn>0
485 ** then data is pulled from srcTab and pEList is used only to get the
486 ** datatypes for each column.
487 */
488 static void selectInnerLoop(
489   Parse *pParse,          /* The parser context */
490   Select *p,              /* The complete select statement being coded */
491   ExprList *pEList,       /* List of values being extracted */
492   int srcTab,             /* Pull data from this table */
493   int nColumn,            /* Number of columns in the source table */
494   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
495   int distinct,           /* If >=0, make sure results are distinct */
496   SelectDest *pDest,      /* How to dispose of the results */
497   int iContinue,          /* Jump here to continue with next row */
498   int iBreak              /* Jump here to break out of the inner loop */
499 ){
500   Vdbe *v = pParse->pVdbe;
501   int i;
502   int hasDistinct;        /* True if the DISTINCT keyword is present */
503   int regResult;              /* Start of memory holding result set */
504   int eDest = pDest->eDest;   /* How to dispose of results */
505   int iParm = pDest->iParm;   /* First argument to disposal method */
506   int nResultCol;             /* Number of result columns */
507 
508   assert( v );
509   if( NEVER(v==0) ) return;
510   assert( pEList!=0 );
511   hasDistinct = distinct>=0;
512   if( pOrderBy==0 && !hasDistinct ){
513     codeOffset(v, p, iContinue);
514   }
515 
516   /* Pull the requested columns.
517   */
518   if( nColumn>0 ){
519     nResultCol = nColumn;
520   }else{
521     nResultCol = pEList->nExpr;
522   }
523   if( pDest->iMem==0 ){
524     pDest->iMem = pParse->nMem+1;
525     pDest->nMem = nResultCol;
526     pParse->nMem += nResultCol;
527   }else{
528     assert( pDest->nMem==nResultCol );
529   }
530   regResult = pDest->iMem;
531   if( nColumn>0 ){
532     for(i=0; i<nColumn; i++){
533       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
534     }
535   }else if( eDest!=SRT_Exists ){
536     /* If the destination is an EXISTS(...) expression, the actual
537     ** values returned by the SELECT are not required.
538     */
539     sqlite3ExprCacheClear(pParse);
540     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
541   }
542   nColumn = nResultCol;
543 
544   /* If the DISTINCT keyword was present on the SELECT statement
545   ** and this row has been seen before, then do not make this row
546   ** part of the result.
547   */
548   if( hasDistinct ){
549     assert( pEList!=0 );
550     assert( pEList->nExpr==nColumn );
551     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
552     if( pOrderBy==0 ){
553       codeOffset(v, p, iContinue);
554     }
555   }
556 
557   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
558     return;
559   }
560 
561   switch( eDest ){
562     /* In this mode, write each query result to the key of the temporary
563     ** table iParm.
564     */
565 #ifndef SQLITE_OMIT_COMPOUND_SELECT
566     case SRT_Union: {
567       int r1;
568       r1 = sqlite3GetTempReg(pParse);
569       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
570       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
571       sqlite3ReleaseTempReg(pParse, r1);
572       break;
573     }
574 
575     /* Construct a record from the query result, but instead of
576     ** saving that record, use it as a key to delete elements from
577     ** the temporary table iParm.
578     */
579     case SRT_Except: {
580       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
581       break;
582     }
583 #endif
584 
585     /* Store the result as data using a unique key.
586     */
587     case SRT_Table:
588     case SRT_EphemTab: {
589       int r1 = sqlite3GetTempReg(pParse);
590       testcase( eDest==SRT_Table );
591       testcase( eDest==SRT_EphemTab );
592       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
593       if( pOrderBy ){
594         pushOntoSorter(pParse, pOrderBy, p, r1);
595       }else{
596         int r2 = sqlite3GetTempReg(pParse);
597         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
598         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
599         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
600         sqlite3ReleaseTempReg(pParse, r2);
601       }
602       sqlite3ReleaseTempReg(pParse, r1);
603       break;
604     }
605 
606 #ifndef SQLITE_OMIT_SUBQUERY
607     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
608     ** then there should be a single item on the stack.  Write this
609     ** item into the set table with bogus data.
610     */
611     case SRT_Set: {
612       assert( nColumn==1 );
613       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
614       if( pOrderBy ){
615         /* At first glance you would think we could optimize out the
616         ** ORDER BY in this case since the order of entries in the set
617         ** does not matter.  But there might be a LIMIT clause, in which
618         ** case the order does matter */
619         pushOntoSorter(pParse, pOrderBy, p, regResult);
620       }else{
621         int r1 = sqlite3GetTempReg(pParse);
622         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
623         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
624         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
625         sqlite3ReleaseTempReg(pParse, r1);
626       }
627       break;
628     }
629 
630     /* If any row exist in the result set, record that fact and abort.
631     */
632     case SRT_Exists: {
633       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
634       /* The LIMIT clause will terminate the loop for us */
635       break;
636     }
637 
638     /* If this is a scalar select that is part of an expression, then
639     ** store the results in the appropriate memory cell and break out
640     ** of the scan loop.
641     */
642     case SRT_Mem: {
643       assert( nColumn==1 );
644       if( pOrderBy ){
645         pushOntoSorter(pParse, pOrderBy, p, regResult);
646       }else{
647         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
648         /* The LIMIT clause will jump out of the loop for us */
649       }
650       break;
651     }
652 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
653 
654     /* Send the data to the callback function or to a subroutine.  In the
655     ** case of a subroutine, the subroutine itself is responsible for
656     ** popping the data from the stack.
657     */
658     case SRT_Coroutine:
659     case SRT_Output: {
660       testcase( eDest==SRT_Coroutine );
661       testcase( eDest==SRT_Output );
662       if( pOrderBy ){
663         int r1 = sqlite3GetTempReg(pParse);
664         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
665         pushOntoSorter(pParse, pOrderBy, p, r1);
666         sqlite3ReleaseTempReg(pParse, r1);
667       }else if( eDest==SRT_Coroutine ){
668         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
669       }else{
670         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
671         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
672       }
673       break;
674     }
675 
676 #if !defined(SQLITE_OMIT_TRIGGER)
677     /* Discard the results.  This is used for SELECT statements inside
678     ** the body of a TRIGGER.  The purpose of such selects is to call
679     ** user-defined functions that have side effects.  We do not care
680     ** about the actual results of the select.
681     */
682     default: {
683       assert( eDest==SRT_Discard );
684       break;
685     }
686 #endif
687   }
688 
689   /* Jump to the end of the loop if the LIMIT is reached.
690   */
691   if( p->iLimit ){
692     assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
693                             ** pushOntoSorter() would have cleared p->iLimit */
694     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
695     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
696   }
697 }
698 
699 /*
700 ** Given an expression list, generate a KeyInfo structure that records
701 ** the collating sequence for each expression in that expression list.
702 **
703 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
704 ** KeyInfo structure is appropriate for initializing a virtual index to
705 ** implement that clause.  If the ExprList is the result set of a SELECT
706 ** then the KeyInfo structure is appropriate for initializing a virtual
707 ** index to implement a DISTINCT test.
708 **
709 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
710 ** function is responsible for seeing that this structure is eventually
711 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
712 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
713 */
714 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
715   sqlite3 *db = pParse->db;
716   int nExpr;
717   KeyInfo *pInfo;
718   struct ExprList_item *pItem;
719   int i;
720 
721   nExpr = pList->nExpr;
722   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
723   if( pInfo ){
724     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
725     pInfo->nField = (u16)nExpr;
726     pInfo->enc = ENC(db);
727     pInfo->db = db;
728     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
729       CollSeq *pColl;
730       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
731       if( !pColl ){
732         pColl = db->pDfltColl;
733       }
734       pInfo->aColl[i] = pColl;
735       pInfo->aSortOrder[i] = pItem->sortOrder;
736     }
737   }
738   return pInfo;
739 }
740 
741 
742 /*
743 ** If the inner loop was generated using a non-null pOrderBy argument,
744 ** then the results were placed in a sorter.  After the loop is terminated
745 ** we need to run the sorter and output the results.  The following
746 ** routine generates the code needed to do that.
747 */
748 static void generateSortTail(
749   Parse *pParse,    /* Parsing context */
750   Select *p,        /* The SELECT statement */
751   Vdbe *v,          /* Generate code into this VDBE */
752   int nColumn,      /* Number of columns of data */
753   SelectDest *pDest /* Write the sorted results here */
754 ){
755   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
756   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
757   int addr;
758   int iTab;
759   int pseudoTab = 0;
760   ExprList *pOrderBy = p->pOrderBy;
761 
762   int eDest = pDest->eDest;
763   int iParm = pDest->iParm;
764 
765   int regRow;
766   int regRowid;
767 
768   iTab = pOrderBy->iECursor;
769   regRow = sqlite3GetTempReg(pParse);
770   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
771     pseudoTab = pParse->nTab++;
772     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
773     regRowid = 0;
774   }else{
775     regRowid = sqlite3GetTempReg(pParse);
776   }
777   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
778   codeOffset(v, p, addrContinue);
779   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
780   switch( eDest ){
781     case SRT_Table:
782     case SRT_EphemTab: {
783       testcase( eDest==SRT_Table );
784       testcase( eDest==SRT_EphemTab );
785       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
786       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
787       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
788       break;
789     }
790 #ifndef SQLITE_OMIT_SUBQUERY
791     case SRT_Set: {
792       assert( nColumn==1 );
793       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
794       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
795       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
796       break;
797     }
798     case SRT_Mem: {
799       assert( nColumn==1 );
800       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
801       /* The LIMIT clause will terminate the loop for us */
802       break;
803     }
804 #endif
805     default: {
806       int i;
807       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
808       testcase( eDest==SRT_Output );
809       testcase( eDest==SRT_Coroutine );
810       for(i=0; i<nColumn; i++){
811         assert( regRow!=pDest->iMem+i );
812         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
813         if( i==0 ){
814           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
815         }
816       }
817       if( eDest==SRT_Output ){
818         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
819         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
820       }else{
821         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
822       }
823       break;
824     }
825   }
826   sqlite3ReleaseTempReg(pParse, regRow);
827   sqlite3ReleaseTempReg(pParse, regRowid);
828 
829   /* LIMIT has been implemented by the pushOntoSorter() routine.
830   */
831   assert( p->iLimit==0 );
832 
833   /* The bottom of the loop
834   */
835   sqlite3VdbeResolveLabel(v, addrContinue);
836   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
837   sqlite3VdbeResolveLabel(v, addrBreak);
838   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
839     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
840   }
841 }
842 
843 /*
844 ** Return a pointer to a string containing the 'declaration type' of the
845 ** expression pExpr. The string may be treated as static by the caller.
846 **
847 ** The declaration type is the exact datatype definition extracted from the
848 ** original CREATE TABLE statement if the expression is a column. The
849 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
850 ** is considered a column can be complex in the presence of subqueries. The
851 ** result-set expression in all of the following SELECT statements is
852 ** considered a column by this function.
853 **
854 **   SELECT col FROM tbl;
855 **   SELECT (SELECT col FROM tbl;
856 **   SELECT (SELECT col FROM tbl);
857 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
858 **
859 ** The declaration type for any expression other than a column is NULL.
860 */
861 static const char *columnType(
862   NameContext *pNC,
863   Expr *pExpr,
864   const char **pzOriginDb,
865   const char **pzOriginTab,
866   const char **pzOriginCol
867 ){
868   char const *zType = 0;
869   char const *zOriginDb = 0;
870   char const *zOriginTab = 0;
871   char const *zOriginCol = 0;
872   int j;
873   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
874 
875   switch( pExpr->op ){
876     case TK_AGG_COLUMN:
877     case TK_COLUMN: {
878       /* The expression is a column. Locate the table the column is being
879       ** extracted from in NameContext.pSrcList. This table may be real
880       ** database table or a subquery.
881       */
882       Table *pTab = 0;            /* Table structure column is extracted from */
883       Select *pS = 0;             /* Select the column is extracted from */
884       int iCol = pExpr->iColumn;  /* Index of column in pTab */
885       testcase( pExpr->op==TK_AGG_COLUMN );
886       testcase( pExpr->op==TK_COLUMN );
887       while( pNC && !pTab ){
888         SrcList *pTabList = pNC->pSrcList;
889         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
890         if( j<pTabList->nSrc ){
891           pTab = pTabList->a[j].pTab;
892           pS = pTabList->a[j].pSelect;
893         }else{
894           pNC = pNC->pNext;
895         }
896       }
897 
898       if( pTab==0 ){
899         /* At one time, code such as "SELECT new.x" within a trigger would
900         ** cause this condition to run.  Since then, we have restructured how
901         ** trigger code is generated and so this condition is no longer
902         ** possible. However, it can still be true for statements like
903         ** the following:
904         **
905         **   CREATE TABLE t1(col INTEGER);
906         **   SELECT (SELECT t1.col) FROM FROM t1;
907         **
908         ** when columnType() is called on the expression "t1.col" in the
909         ** sub-select. In this case, set the column type to NULL, even
910         ** though it should really be "INTEGER".
911         **
912         ** This is not a problem, as the column type of "t1.col" is never
913         ** used. When columnType() is called on the expression
914         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
915         ** branch below.  */
916         break;
917       }
918 
919       assert( pTab && pExpr->pTab==pTab );
920       if( pS ){
921         /* The "table" is actually a sub-select or a view in the FROM clause
922         ** of the SELECT statement. Return the declaration type and origin
923         ** data for the result-set column of the sub-select.
924         */
925         if( ALWAYS(iCol>=0 && iCol<pS->pEList->nExpr) ){
926           /* If iCol is less than zero, then the expression requests the
927           ** rowid of the sub-select or view. This expression is legal (see
928           ** test case misc2.2.2) - it always evaluates to NULL.
929           */
930           NameContext sNC;
931           Expr *p = pS->pEList->a[iCol].pExpr;
932           sNC.pSrcList = pS->pSrc;
933           sNC.pNext = pNC;
934           sNC.pParse = pNC->pParse;
935           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
936         }
937       }else if( ALWAYS(pTab->pSchema) ){
938         /* A real table */
939         assert( !pS );
940         if( iCol<0 ) iCol = pTab->iPKey;
941         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
942         if( iCol<0 ){
943           zType = "INTEGER";
944           zOriginCol = "rowid";
945         }else{
946           zType = pTab->aCol[iCol].zType;
947           zOriginCol = pTab->aCol[iCol].zName;
948         }
949         zOriginTab = pTab->zName;
950         if( pNC->pParse ){
951           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
952           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
953         }
954       }
955       break;
956     }
957 #ifndef SQLITE_OMIT_SUBQUERY
958     case TK_SELECT: {
959       /* The expression is a sub-select. Return the declaration type and
960       ** origin info for the single column in the result set of the SELECT
961       ** statement.
962       */
963       NameContext sNC;
964       Select *pS = pExpr->x.pSelect;
965       Expr *p = pS->pEList->a[0].pExpr;
966       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
967       sNC.pSrcList = pS->pSrc;
968       sNC.pNext = pNC;
969       sNC.pParse = pNC->pParse;
970       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
971       break;
972     }
973 #endif
974   }
975 
976   if( pzOriginDb ){
977     assert( pzOriginTab && pzOriginCol );
978     *pzOriginDb = zOriginDb;
979     *pzOriginTab = zOriginTab;
980     *pzOriginCol = zOriginCol;
981   }
982   return zType;
983 }
984 
985 /*
986 ** Generate code that will tell the VDBE the declaration types of columns
987 ** in the result set.
988 */
989 static void generateColumnTypes(
990   Parse *pParse,      /* Parser context */
991   SrcList *pTabList,  /* List of tables */
992   ExprList *pEList    /* Expressions defining the result set */
993 ){
994 #ifndef SQLITE_OMIT_DECLTYPE
995   Vdbe *v = pParse->pVdbe;
996   int i;
997   NameContext sNC;
998   sNC.pSrcList = pTabList;
999   sNC.pParse = pParse;
1000   for(i=0; i<pEList->nExpr; i++){
1001     Expr *p = pEList->a[i].pExpr;
1002     const char *zType;
1003 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1004     const char *zOrigDb = 0;
1005     const char *zOrigTab = 0;
1006     const char *zOrigCol = 0;
1007     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
1008 
1009     /* The vdbe must make its own copy of the column-type and other
1010     ** column specific strings, in case the schema is reset before this
1011     ** virtual machine is deleted.
1012     */
1013     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
1014     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
1015     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
1016 #else
1017     zType = columnType(&sNC, p, 0, 0, 0);
1018 #endif
1019     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
1020   }
1021 #endif /* SQLITE_OMIT_DECLTYPE */
1022 }
1023 
1024 /*
1025 ** Generate code that will tell the VDBE the names of columns
1026 ** in the result set.  This information is used to provide the
1027 ** azCol[] values in the callback.
1028 */
1029 static void generateColumnNames(
1030   Parse *pParse,      /* Parser context */
1031   SrcList *pTabList,  /* List of tables */
1032   ExprList *pEList    /* Expressions defining the result set */
1033 ){
1034   Vdbe *v = pParse->pVdbe;
1035   int i, j;
1036   sqlite3 *db = pParse->db;
1037   int fullNames, shortNames;
1038 
1039 #ifndef SQLITE_OMIT_EXPLAIN
1040   /* If this is an EXPLAIN, skip this step */
1041   if( pParse->explain ){
1042     return;
1043   }
1044 #endif
1045 
1046   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
1047   pParse->colNamesSet = 1;
1048   fullNames = (db->flags & SQLITE_FullColNames)!=0;
1049   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
1050   sqlite3VdbeSetNumCols(v, pEList->nExpr);
1051   for(i=0; i<pEList->nExpr; i++){
1052     Expr *p;
1053     p = pEList->a[i].pExpr;
1054     if( NEVER(p==0) ) continue;
1055     if( pEList->a[i].zName ){
1056       char *zName = pEList->a[i].zName;
1057       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
1058     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
1059       Table *pTab;
1060       char *zCol;
1061       int iCol = p->iColumn;
1062       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
1063         if( pTabList->a[j].iCursor==p->iTable ) break;
1064       }
1065       assert( j<pTabList->nSrc );
1066       pTab = pTabList->a[j].pTab;
1067       if( iCol<0 ) iCol = pTab->iPKey;
1068       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1069       if( iCol<0 ){
1070         zCol = "rowid";
1071       }else{
1072         zCol = pTab->aCol[iCol].zName;
1073       }
1074       if( !shortNames && !fullNames ){
1075         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
1076             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
1077       }else if( fullNames ){
1078         char *zName = 0;
1079         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
1080         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
1081       }else{
1082         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
1083       }
1084     }else{
1085       sqlite3VdbeSetColName(v, i, COLNAME_NAME,
1086           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
1087     }
1088   }
1089   generateColumnTypes(pParse, pTabList, pEList);
1090 }
1091 
1092 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1093 /*
1094 ** Name of the connection operator, used for error messages.
1095 */
1096 static const char *selectOpName(int id){
1097   char *z;
1098   switch( id ){
1099     case TK_ALL:       z = "UNION ALL";   break;
1100     case TK_INTERSECT: z = "INTERSECT";   break;
1101     case TK_EXCEPT:    z = "EXCEPT";      break;
1102     default:           z = "UNION";       break;
1103   }
1104   return z;
1105 }
1106 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1107 
1108 /*
1109 ** Given a an expression list (which is really the list of expressions
1110 ** that form the result set of a SELECT statement) compute appropriate
1111 ** column names for a table that would hold the expression list.
1112 **
1113 ** All column names will be unique.
1114 **
1115 ** Only the column names are computed.  Column.zType, Column.zColl,
1116 ** and other fields of Column are zeroed.
1117 **
1118 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
1119 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
1120 */
1121 static int selectColumnsFromExprList(
1122   Parse *pParse,          /* Parsing context */
1123   ExprList *pEList,       /* Expr list from which to derive column names */
1124   int *pnCol,             /* Write the number of columns here */
1125   Column **paCol          /* Write the new column list here */
1126 ){
1127   sqlite3 *db = pParse->db;   /* Database connection */
1128   int i, j;                   /* Loop counters */
1129   int cnt;                    /* Index added to make the name unique */
1130   Column *aCol, *pCol;        /* For looping over result columns */
1131   int nCol;                   /* Number of columns in the result set */
1132   Expr *p;                    /* Expression for a single result column */
1133   char *zName;                /* Column name */
1134   int nName;                  /* Size of name in zName[] */
1135 
1136   *pnCol = nCol = pEList->nExpr;
1137   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
1138   if( aCol==0 ) return SQLITE_NOMEM;
1139   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
1140     /* Get an appropriate name for the column
1141     */
1142     p = pEList->a[i].pExpr;
1143     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
1144                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
1145     if( (zName = pEList->a[i].zName)!=0 ){
1146       /* If the column contains an "AS <name>" phrase, use <name> as the name */
1147       zName = sqlite3DbStrDup(db, zName);
1148     }else{
1149       Expr *pColExpr = p;  /* The expression that is the result column name */
1150       Table *pTab;         /* Table associated with this expression */
1151       while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
1152       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
1153         /* For columns use the column name name */
1154         int iCol = pColExpr->iColumn;
1155         pTab = pColExpr->pTab;
1156         if( iCol<0 ) iCol = pTab->iPKey;
1157         zName = sqlite3MPrintf(db, "%s",
1158                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
1159       }else if( pColExpr->op==TK_ID ){
1160         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
1161         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
1162       }else{
1163         /* Use the original text of the column expression as its name */
1164         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
1165       }
1166     }
1167     if( db->mallocFailed ){
1168       sqlite3DbFree(db, zName);
1169       break;
1170     }
1171 
1172     /* Make sure the column name is unique.  If the name is not unique,
1173     ** append a integer to the name so that it becomes unique.
1174     */
1175     nName = sqlite3Strlen30(zName);
1176     for(j=cnt=0; j<i; j++){
1177       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
1178         char *zNewName;
1179         zName[nName] = 0;
1180         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
1181         sqlite3DbFree(db, zName);
1182         zName = zNewName;
1183         j = -1;
1184         if( zName==0 ) break;
1185       }
1186     }
1187     pCol->zName = zName;
1188   }
1189   if( db->mallocFailed ){
1190     for(j=0; j<i; j++){
1191       sqlite3DbFree(db, aCol[j].zName);
1192     }
1193     sqlite3DbFree(db, aCol);
1194     *paCol = 0;
1195     *pnCol = 0;
1196     return SQLITE_NOMEM;
1197   }
1198   return SQLITE_OK;
1199 }
1200 
1201 /*
1202 ** Add type and collation information to a column list based on
1203 ** a SELECT statement.
1204 **
1205 ** The column list presumably came from selectColumnNamesFromExprList().
1206 ** The column list has only names, not types or collations.  This
1207 ** routine goes through and adds the types and collations.
1208 **
1209 ** This routine requires that all identifiers in the SELECT
1210 ** statement be resolved.
1211 */
1212 static void selectAddColumnTypeAndCollation(
1213   Parse *pParse,        /* Parsing contexts */
1214   int nCol,             /* Number of columns */
1215   Column *aCol,         /* List of columns */
1216   Select *pSelect       /* SELECT used to determine types and collations */
1217 ){
1218   sqlite3 *db = pParse->db;
1219   NameContext sNC;
1220   Column *pCol;
1221   CollSeq *pColl;
1222   int i;
1223   Expr *p;
1224   struct ExprList_item *a;
1225 
1226   assert( pSelect!=0 );
1227   assert( (pSelect->selFlags & SF_Resolved)!=0 );
1228   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
1229   if( db->mallocFailed ) return;
1230   memset(&sNC, 0, sizeof(sNC));
1231   sNC.pSrcList = pSelect->pSrc;
1232   a = pSelect->pEList->a;
1233   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
1234     p = a[i].pExpr;
1235     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
1236     pCol->affinity = sqlite3ExprAffinity(p);
1237     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
1238     pColl = sqlite3ExprCollSeq(pParse, p);
1239     if( pColl ){
1240       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
1241     }
1242   }
1243 }
1244 
1245 /*
1246 ** Given a SELECT statement, generate a Table structure that describes
1247 ** the result set of that SELECT.
1248 */
1249 Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
1250   Table *pTab;
1251   sqlite3 *db = pParse->db;
1252   int savedFlags;
1253 
1254   savedFlags = db->flags;
1255   db->flags &= ~SQLITE_FullColNames;
1256   db->flags |= SQLITE_ShortColNames;
1257   sqlite3SelectPrep(pParse, pSelect, 0);
1258   if( pParse->nErr ) return 0;
1259   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
1260   db->flags = savedFlags;
1261   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
1262   if( pTab==0 ){
1263     return 0;
1264   }
1265   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
1266   ** is disabled, so we might as well hard-code pTab->dbMem to NULL. */
1267   assert( db->lookaside.bEnabled==0 );
1268   pTab->dbMem = 0;
1269   pTab->nRef = 1;
1270   pTab->zName = 0;
1271   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
1272   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
1273   pTab->iPKey = -1;
1274   if( db->mallocFailed ){
1275     sqlite3DeleteTable(pTab);
1276     return 0;
1277   }
1278   return pTab;
1279 }
1280 
1281 /*
1282 ** Get a VDBE for the given parser context.  Create a new one if necessary.
1283 ** If an error occurs, return NULL and leave a message in pParse.
1284 */
1285 Vdbe *sqlite3GetVdbe(Parse *pParse){
1286   Vdbe *v = pParse->pVdbe;
1287   if( v==0 ){
1288     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1289 #ifndef SQLITE_OMIT_TRACE
1290     if( v ){
1291       sqlite3VdbeAddOp0(v, OP_Trace);
1292     }
1293 #endif
1294   }
1295   return v;
1296 }
1297 
1298 
1299 /*
1300 ** Compute the iLimit and iOffset fields of the SELECT based on the
1301 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
1302 ** that appear in the original SQL statement after the LIMIT and OFFSET
1303 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1304 ** are the integer memory register numbers for counters used to compute
1305 ** the limit and offset.  If there is no limit and/or offset, then
1306 ** iLimit and iOffset are negative.
1307 **
1308 ** This routine changes the values of iLimit and iOffset only if
1309 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
1310 ** iOffset should have been preset to appropriate default values
1311 ** (usually but not always -1) prior to calling this routine.
1312 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
1313 ** redefined.  The UNION ALL operator uses this property to force
1314 ** the reuse of the same limit and offset registers across multiple
1315 ** SELECT statements.
1316 */
1317 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
1318   Vdbe *v = 0;
1319   int iLimit = 0;
1320   int iOffset;
1321   int addr1;
1322   if( p->iLimit ) return;
1323 
1324   /*
1325   ** "LIMIT -1" always shows all rows.  There is some
1326   ** contraversy about what the correct behavior should be.
1327   ** The current implementation interprets "LIMIT 0" to mean
1328   ** no rows.
1329   */
1330   sqlite3ExprCacheClear(pParse);
1331   assert( p->pOffset==0 || p->pLimit!=0 );
1332   if( p->pLimit ){
1333     p->iLimit = iLimit = ++pParse->nMem;
1334     v = sqlite3GetVdbe(pParse);
1335     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
1336     sqlite3ExprCode(pParse, p->pLimit, iLimit);
1337     sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
1338     VdbeComment((v, "LIMIT counter"));
1339     sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
1340     if( p->pOffset ){
1341       p->iOffset = iOffset = ++pParse->nMem;
1342       pParse->nMem++;   /* Allocate an extra register for limit+offset */
1343       sqlite3ExprCode(pParse, p->pOffset, iOffset);
1344       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
1345       VdbeComment((v, "OFFSET counter"));
1346       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
1347       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
1348       sqlite3VdbeJumpHere(v, addr1);
1349       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
1350       VdbeComment((v, "LIMIT+OFFSET"));
1351       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
1352       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
1353       sqlite3VdbeJumpHere(v, addr1);
1354     }
1355   }
1356 }
1357 
1358 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1359 /*
1360 ** Return the appropriate collating sequence for the iCol-th column of
1361 ** the result set for the compound-select statement "p".  Return NULL if
1362 ** the column has no default collating sequence.
1363 **
1364 ** The collating sequence for the compound select is taken from the
1365 ** left-most term of the select that has a collating sequence.
1366 */
1367 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1368   CollSeq *pRet;
1369   if( p->pPrior ){
1370     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1371   }else{
1372     pRet = 0;
1373   }
1374   assert( iCol>=0 );
1375   if( pRet==0 && iCol<p->pEList->nExpr ){
1376     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1377   }
1378   return pRet;
1379 }
1380 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1381 
1382 /* Forward reference */
1383 static int multiSelectOrderBy(
1384   Parse *pParse,        /* Parsing context */
1385   Select *p,            /* The right-most of SELECTs to be coded */
1386   SelectDest *pDest     /* What to do with query results */
1387 );
1388 
1389 
1390 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1391 /*
1392 ** This routine is called to process a compound query form from
1393 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
1394 ** INTERSECT
1395 **
1396 ** "p" points to the right-most of the two queries.  the query on the
1397 ** left is p->pPrior.  The left query could also be a compound query
1398 ** in which case this routine will be called recursively.
1399 **
1400 ** The results of the total query are to be written into a destination
1401 ** of type eDest with parameter iParm.
1402 **
1403 ** Example 1:  Consider a three-way compound SQL statement.
1404 **
1405 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1406 **
1407 ** This statement is parsed up as follows:
1408 **
1409 **     SELECT c FROM t3
1410 **      |
1411 **      `----->  SELECT b FROM t2
1412 **                |
1413 **                `------>  SELECT a FROM t1
1414 **
1415 ** The arrows in the diagram above represent the Select.pPrior pointer.
1416 ** So if this routine is called with p equal to the t3 query, then
1417 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1418 **
1419 ** Notice that because of the way SQLite parses compound SELECTs, the
1420 ** individual selects always group from left to right.
1421 */
1422 static int multiSelect(
1423   Parse *pParse,        /* Parsing context */
1424   Select *p,            /* The right-most of SELECTs to be coded */
1425   SelectDest *pDest     /* What to do with query results */
1426 ){
1427   int rc = SQLITE_OK;   /* Success code from a subroutine */
1428   Select *pPrior;       /* Another SELECT immediately to our left */
1429   Vdbe *v;              /* Generate code to this VDBE */
1430   SelectDest dest;      /* Alternative data destination */
1431   Select *pDelete = 0;  /* Chain of simple selects to delete */
1432   sqlite3 *db;          /* Database connection */
1433 
1434   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1435   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
1436   */
1437   assert( p && p->pPrior );  /* Calling function guarantees this much */
1438   db = pParse->db;
1439   pPrior = p->pPrior;
1440   assert( pPrior->pRightmost!=pPrior );
1441   assert( pPrior->pRightmost==p->pRightmost );
1442   dest = *pDest;
1443   if( pPrior->pOrderBy ){
1444     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1445       selectOpName(p->op));
1446     rc = 1;
1447     goto multi_select_end;
1448   }
1449   if( pPrior->pLimit ){
1450     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
1451       selectOpName(p->op));
1452     rc = 1;
1453     goto multi_select_end;
1454   }
1455 
1456   v = sqlite3GetVdbe(pParse);
1457   assert( v!=0 );  /* The VDBE already created by calling function */
1458 
1459   /* Create the destination temporary table if necessary
1460   */
1461   if( dest.eDest==SRT_EphemTab ){
1462     assert( p->pEList );
1463     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
1464     dest.eDest = SRT_Table;
1465   }
1466 
1467   /* Make sure all SELECTs in the statement have the same number of elements
1468   ** in their result sets.
1469   */
1470   assert( p->pEList && pPrior->pEList );
1471   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
1472     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
1473       " do not have the same number of result columns", selectOpName(p->op));
1474     rc = 1;
1475     goto multi_select_end;
1476   }
1477 
1478   /* Compound SELECTs that have an ORDER BY clause are handled separately.
1479   */
1480   if( p->pOrderBy ){
1481     return multiSelectOrderBy(pParse, p, pDest);
1482   }
1483 
1484   /* Generate code for the left and right SELECT statements.
1485   */
1486   switch( p->op ){
1487     case TK_ALL: {
1488       int addr = 0;
1489       assert( !pPrior->pLimit );
1490       pPrior->pLimit = p->pLimit;
1491       pPrior->pOffset = p->pOffset;
1492       rc = sqlite3Select(pParse, pPrior, &dest);
1493       p->pLimit = 0;
1494       p->pOffset = 0;
1495       if( rc ){
1496         goto multi_select_end;
1497       }
1498       p->pPrior = 0;
1499       p->iLimit = pPrior->iLimit;
1500       p->iOffset = pPrior->iOffset;
1501       if( p->iLimit ){
1502         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
1503         VdbeComment((v, "Jump ahead if LIMIT reached"));
1504       }
1505       rc = sqlite3Select(pParse, p, &dest);
1506       testcase( rc!=SQLITE_OK );
1507       pDelete = p->pPrior;
1508       p->pPrior = pPrior;
1509       if( addr ){
1510         sqlite3VdbeJumpHere(v, addr);
1511       }
1512       break;
1513     }
1514     case TK_EXCEPT:
1515     case TK_UNION: {
1516       int unionTab;    /* Cursor number of the temporary table holding result */
1517       u8 op = 0;       /* One of the SRT_ operations to apply to self */
1518       int priorOp;     /* The SRT_ operation to apply to prior selects */
1519       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
1520       int addr;
1521       SelectDest uniondest;
1522 
1523       testcase( p->op==TK_EXCEPT );
1524       testcase( p->op==TK_UNION );
1525       priorOp = SRT_Union;
1526       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
1527         /* We can reuse a temporary table generated by a SELECT to our
1528         ** right.
1529         */
1530         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
1531                                      ** of a 3-way or more compound */
1532         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
1533         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
1534         unionTab = dest.iParm;
1535       }else{
1536         /* We will need to create our own temporary table to hold the
1537         ** intermediate results.
1538         */
1539         unionTab = pParse->nTab++;
1540         assert( p->pOrderBy==0 );
1541         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
1542         assert( p->addrOpenEphm[0] == -1 );
1543         p->addrOpenEphm[0] = addr;
1544         p->pRightmost->selFlags |= SF_UsesEphemeral;
1545         assert( p->pEList );
1546       }
1547 
1548       /* Code the SELECT statements to our left
1549       */
1550       assert( !pPrior->pOrderBy );
1551       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
1552       rc = sqlite3Select(pParse, pPrior, &uniondest);
1553       if( rc ){
1554         goto multi_select_end;
1555       }
1556 
1557       /* Code the current SELECT statement
1558       */
1559       if( p->op==TK_EXCEPT ){
1560         op = SRT_Except;
1561       }else{
1562         assert( p->op==TK_UNION );
1563         op = SRT_Union;
1564       }
1565       p->pPrior = 0;
1566       pLimit = p->pLimit;
1567       p->pLimit = 0;
1568       pOffset = p->pOffset;
1569       p->pOffset = 0;
1570       uniondest.eDest = op;
1571       rc = sqlite3Select(pParse, p, &uniondest);
1572       testcase( rc!=SQLITE_OK );
1573       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
1574       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
1575       sqlite3ExprListDelete(db, p->pOrderBy);
1576       pDelete = p->pPrior;
1577       p->pPrior = pPrior;
1578       p->pOrderBy = 0;
1579       sqlite3ExprDelete(db, p->pLimit);
1580       p->pLimit = pLimit;
1581       p->pOffset = pOffset;
1582       p->iLimit = 0;
1583       p->iOffset = 0;
1584 
1585       /* Convert the data in the temporary table into whatever form
1586       ** it is that we currently need.
1587       */
1588       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
1589       if( dest.eDest!=priorOp ){
1590         int iCont, iBreak, iStart;
1591         assert( p->pEList );
1592         if( dest.eDest==SRT_Output ){
1593           Select *pFirst = p;
1594           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
1595           generateColumnNames(pParse, 0, pFirst->pEList);
1596         }
1597         iBreak = sqlite3VdbeMakeLabel(v);
1598         iCont = sqlite3VdbeMakeLabel(v);
1599         computeLimitRegisters(pParse, p, iBreak);
1600         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
1601         iStart = sqlite3VdbeCurrentAddr(v);
1602         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
1603                         0, -1, &dest, iCont, iBreak);
1604         sqlite3VdbeResolveLabel(v, iCont);
1605         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
1606         sqlite3VdbeResolveLabel(v, iBreak);
1607         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
1608       }
1609       break;
1610     }
1611     default: assert( p->op==TK_INTERSECT ); {
1612       int tab1, tab2;
1613       int iCont, iBreak, iStart;
1614       Expr *pLimit, *pOffset;
1615       int addr;
1616       SelectDest intersectdest;
1617       int r1;
1618 
1619       /* INTERSECT is different from the others since it requires
1620       ** two temporary tables.  Hence it has its own case.  Begin
1621       ** by allocating the tables we will need.
1622       */
1623       tab1 = pParse->nTab++;
1624       tab2 = pParse->nTab++;
1625       assert( p->pOrderBy==0 );
1626 
1627       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
1628       assert( p->addrOpenEphm[0] == -1 );
1629       p->addrOpenEphm[0] = addr;
1630       p->pRightmost->selFlags |= SF_UsesEphemeral;
1631       assert( p->pEList );
1632 
1633       /* Code the SELECTs to our left into temporary table "tab1".
1634       */
1635       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
1636       rc = sqlite3Select(pParse, pPrior, &intersectdest);
1637       if( rc ){
1638         goto multi_select_end;
1639       }
1640 
1641       /* Code the current SELECT into temporary table "tab2"
1642       */
1643       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
1644       assert( p->addrOpenEphm[1] == -1 );
1645       p->addrOpenEphm[1] = addr;
1646       p->pPrior = 0;
1647       pLimit = p->pLimit;
1648       p->pLimit = 0;
1649       pOffset = p->pOffset;
1650       p->pOffset = 0;
1651       intersectdest.iParm = tab2;
1652       rc = sqlite3Select(pParse, p, &intersectdest);
1653       testcase( rc!=SQLITE_OK );
1654       pDelete = p->pPrior;
1655       p->pPrior = pPrior;
1656       sqlite3ExprDelete(db, p->pLimit);
1657       p->pLimit = pLimit;
1658       p->pOffset = pOffset;
1659 
1660       /* Generate code to take the intersection of the two temporary
1661       ** tables.
1662       */
1663       assert( p->pEList );
1664       if( dest.eDest==SRT_Output ){
1665         Select *pFirst = p;
1666         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
1667         generateColumnNames(pParse, 0, pFirst->pEList);
1668       }
1669       iBreak = sqlite3VdbeMakeLabel(v);
1670       iCont = sqlite3VdbeMakeLabel(v);
1671       computeLimitRegisters(pParse, p, iBreak);
1672       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
1673       r1 = sqlite3GetTempReg(pParse);
1674       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
1675       sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1);
1676       sqlite3ReleaseTempReg(pParse, r1);
1677       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
1678                       0, -1, &dest, iCont, iBreak);
1679       sqlite3VdbeResolveLabel(v, iCont);
1680       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
1681       sqlite3VdbeResolveLabel(v, iBreak);
1682       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
1683       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
1684       break;
1685     }
1686   }
1687 
1688   /* Compute collating sequences used by
1689   ** temporary tables needed to implement the compound select.
1690   ** Attach the KeyInfo structure to all temporary tables.
1691   **
1692   ** This section is run by the right-most SELECT statement only.
1693   ** SELECT statements to the left always skip this part.  The right-most
1694   ** SELECT might also skip this part if it has no ORDER BY clause and
1695   ** no temp tables are required.
1696   */
1697   if( p->selFlags & SF_UsesEphemeral ){
1698     int i;                        /* Loop counter */
1699     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
1700     Select *pLoop;                /* For looping through SELECT statements */
1701     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
1702     int nCol;                     /* Number of columns in result set */
1703 
1704     assert( p->pRightmost==p );
1705     nCol = p->pEList->nExpr;
1706     pKeyInfo = sqlite3DbMallocZero(db,
1707                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
1708     if( !pKeyInfo ){
1709       rc = SQLITE_NOMEM;
1710       goto multi_select_end;
1711     }
1712 
1713     pKeyInfo->enc = ENC(db);
1714     pKeyInfo->nField = (u16)nCol;
1715 
1716     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
1717       *apColl = multiSelectCollSeq(pParse, p, i);
1718       if( 0==*apColl ){
1719         *apColl = db->pDfltColl;
1720       }
1721     }
1722 
1723     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
1724       for(i=0; i<2; i++){
1725         int addr = pLoop->addrOpenEphm[i];
1726         if( addr<0 ){
1727           /* If [0] is unused then [1] is also unused.  So we can
1728           ** always safely abort as soon as the first unused slot is found */
1729           assert( pLoop->addrOpenEphm[1]<0 );
1730           break;
1731         }
1732         sqlite3VdbeChangeP2(v, addr, nCol);
1733         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
1734         pLoop->addrOpenEphm[i] = -1;
1735       }
1736     }
1737     sqlite3DbFree(db, pKeyInfo);
1738   }
1739 
1740 multi_select_end:
1741   pDest->iMem = dest.iMem;
1742   pDest->nMem = dest.nMem;
1743   sqlite3SelectDelete(db, pDelete);
1744   return rc;
1745 }
1746 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1747 
1748 /*
1749 ** Code an output subroutine for a coroutine implementation of a
1750 ** SELECT statment.
1751 **
1752 ** The data to be output is contained in pIn->iMem.  There are
1753 ** pIn->nMem columns to be output.  pDest is where the output should
1754 ** be sent.
1755 **
1756 ** regReturn is the number of the register holding the subroutine
1757 ** return address.
1758 **
1759 ** If regPrev>0 then it is a the first register in a vector that
1760 ** records the previous output.  mem[regPrev] is a flag that is false
1761 ** if there has been no previous output.  If regPrev>0 then code is
1762 ** generated to suppress duplicates.  pKeyInfo is used for comparing
1763 ** keys.
1764 **
1765 ** If the LIMIT found in p->iLimit is reached, jump immediately to
1766 ** iBreak.
1767 */
1768 static int generateOutputSubroutine(
1769   Parse *pParse,          /* Parsing context */
1770   Select *p,              /* The SELECT statement */
1771   SelectDest *pIn,        /* Coroutine supplying data */
1772   SelectDest *pDest,      /* Where to send the data */
1773   int regReturn,          /* The return address register */
1774   int regPrev,            /* Previous result register.  No uniqueness if 0 */
1775   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
1776   int p4type,             /* The p4 type for pKeyInfo */
1777   int iBreak              /* Jump here if we hit the LIMIT */
1778 ){
1779   Vdbe *v = pParse->pVdbe;
1780   int iContinue;
1781   int addr;
1782 
1783   addr = sqlite3VdbeCurrentAddr(v);
1784   iContinue = sqlite3VdbeMakeLabel(v);
1785 
1786   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
1787   */
1788   if( regPrev ){
1789     int j1, j2;
1790     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
1791     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
1792                               (char*)pKeyInfo, p4type);
1793     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
1794     sqlite3VdbeJumpHere(v, j1);
1795     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
1796     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
1797   }
1798   if( pParse->db->mallocFailed ) return 0;
1799 
1800   /* Suppress the the first OFFSET entries if there is an OFFSET clause
1801   */
1802   codeOffset(v, p, iContinue);
1803 
1804   switch( pDest->eDest ){
1805     /* Store the result as data using a unique key.
1806     */
1807     case SRT_Table:
1808     case SRT_EphemTab: {
1809       int r1 = sqlite3GetTempReg(pParse);
1810       int r2 = sqlite3GetTempReg(pParse);
1811       testcase( pDest->eDest==SRT_Table );
1812       testcase( pDest->eDest==SRT_EphemTab );
1813       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
1814       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
1815       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
1816       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1817       sqlite3ReleaseTempReg(pParse, r2);
1818       sqlite3ReleaseTempReg(pParse, r1);
1819       break;
1820     }
1821 
1822 #ifndef SQLITE_OMIT_SUBQUERY
1823     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
1824     ** then there should be a single item on the stack.  Write this
1825     ** item into the set table with bogus data.
1826     */
1827     case SRT_Set: {
1828       int r1;
1829       assert( pIn->nMem==1 );
1830       p->affinity =
1831          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
1832       r1 = sqlite3GetTempReg(pParse);
1833       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
1834       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
1835       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
1836       sqlite3ReleaseTempReg(pParse, r1);
1837       break;
1838     }
1839 
1840 #if 0  /* Never occurs on an ORDER BY query */
1841     /* If any row exist in the result set, record that fact and abort.
1842     */
1843     case SRT_Exists: {
1844       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
1845       /* The LIMIT clause will terminate the loop for us */
1846       break;
1847     }
1848 #endif
1849 
1850     /* If this is a scalar select that is part of an expression, then
1851     ** store the results in the appropriate memory cell and break out
1852     ** of the scan loop.
1853     */
1854     case SRT_Mem: {
1855       assert( pIn->nMem==1 );
1856       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
1857       /* The LIMIT clause will jump out of the loop for us */
1858       break;
1859     }
1860 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
1861 
1862     /* The results are stored in a sequence of registers
1863     ** starting at pDest->iMem.  Then the co-routine yields.
1864     */
1865     case SRT_Coroutine: {
1866       if( pDest->iMem==0 ){
1867         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
1868         pDest->nMem = pIn->nMem;
1869       }
1870       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
1871       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
1872       break;
1873     }
1874 
1875     /* If none of the above, then the result destination must be
1876     ** SRT_Output.  This routine is never called with any other
1877     ** destination other than the ones handled above or SRT_Output.
1878     **
1879     ** For SRT_Output, results are stored in a sequence of registers.
1880     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
1881     ** return the next row of result.
1882     */
1883     default: {
1884       assert( pDest->eDest==SRT_Output );
1885       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
1886       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
1887       break;
1888     }
1889   }
1890 
1891   /* Jump to the end of the loop if the LIMIT is reached.
1892   */
1893   if( p->iLimit ){
1894     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
1895     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
1896   }
1897 
1898   /* Generate the subroutine return
1899   */
1900   sqlite3VdbeResolveLabel(v, iContinue);
1901   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
1902 
1903   return addr;
1904 }
1905 
1906 /*
1907 ** Alternative compound select code generator for cases when there
1908 ** is an ORDER BY clause.
1909 **
1910 ** We assume a query of the following form:
1911 **
1912 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
1913 **
1914 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
1915 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
1916 ** co-routines.  Then run the co-routines in parallel and merge the results
1917 ** into the output.  In addition to the two coroutines (called selectA and
1918 ** selectB) there are 7 subroutines:
1919 **
1920 **    outA:    Move the output of the selectA coroutine into the output
1921 **             of the compound query.
1922 **
1923 **    outB:    Move the output of the selectB coroutine into the output
1924 **             of the compound query.  (Only generated for UNION and
1925 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
1926 **             appears only in B.)
1927 **
1928 **    AltB:    Called when there is data from both coroutines and A<B.
1929 **
1930 **    AeqB:    Called when there is data from both coroutines and A==B.
1931 **
1932 **    AgtB:    Called when there is data from both coroutines and A>B.
1933 **
1934 **    EofA:    Called when data is exhausted from selectA.
1935 **
1936 **    EofB:    Called when data is exhausted from selectB.
1937 **
1938 ** The implementation of the latter five subroutines depend on which
1939 ** <operator> is used:
1940 **
1941 **
1942 **             UNION ALL         UNION            EXCEPT          INTERSECT
1943 **          -------------  -----------------  --------------  -----------------
1944 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
1945 **
1946 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
1947 **
1948 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
1949 **
1950 **   EofA:   outB, nextB      outB, nextB          halt             halt
1951 **
1952 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
1953 **
1954 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
1955 ** causes an immediate jump to EofA and an EOF on B following nextB causes
1956 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
1957 ** following nextX causes a jump to the end of the select processing.
1958 **
1959 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
1960 ** within the output subroutine.  The regPrev register set holds the previously
1961 ** output value.  A comparison is made against this value and the output
1962 ** is skipped if the next results would be the same as the previous.
1963 **
1964 ** The implementation plan is to implement the two coroutines and seven
1965 ** subroutines first, then put the control logic at the bottom.  Like this:
1966 **
1967 **          goto Init
1968 **     coA: coroutine for left query (A)
1969 **     coB: coroutine for right query (B)
1970 **    outA: output one row of A
1971 **    outB: output one row of B (UNION and UNION ALL only)
1972 **    EofA: ...
1973 **    EofB: ...
1974 **    AltB: ...
1975 **    AeqB: ...
1976 **    AgtB: ...
1977 **    Init: initialize coroutine registers
1978 **          yield coA
1979 **          if eof(A) goto EofA
1980 **          yield coB
1981 **          if eof(B) goto EofB
1982 **    Cmpr: Compare A, B
1983 **          Jump AltB, AeqB, AgtB
1984 **     End: ...
1985 **
1986 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
1987 ** actually called using Gosub and they do not Return.  EofA and EofB loop
1988 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
1989 ** and AgtB jump to either L2 or to one of EofA or EofB.
1990 */
1991 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1992 static int multiSelectOrderBy(
1993   Parse *pParse,        /* Parsing context */
1994   Select *p,            /* The right-most of SELECTs to be coded */
1995   SelectDest *pDest     /* What to do with query results */
1996 ){
1997   int i, j;             /* Loop counters */
1998   Select *pPrior;       /* Another SELECT immediately to our left */
1999   Vdbe *v;              /* Generate code to this VDBE */
2000   SelectDest destA;     /* Destination for coroutine A */
2001   SelectDest destB;     /* Destination for coroutine B */
2002   int regAddrA;         /* Address register for select-A coroutine */
2003   int regEofA;          /* Flag to indicate when select-A is complete */
2004   int regAddrB;         /* Address register for select-B coroutine */
2005   int regEofB;          /* Flag to indicate when select-B is complete */
2006   int addrSelectA;      /* Address of the select-A coroutine */
2007   int addrSelectB;      /* Address of the select-B coroutine */
2008   int regOutA;          /* Address register for the output-A subroutine */
2009   int regOutB;          /* Address register for the output-B subroutine */
2010   int addrOutA;         /* Address of the output-A subroutine */
2011   int addrOutB = 0;     /* Address of the output-B subroutine */
2012   int addrEofA;         /* Address of the select-A-exhausted subroutine */
2013   int addrEofB;         /* Address of the select-B-exhausted subroutine */
2014   int addrAltB;         /* Address of the A<B subroutine */
2015   int addrAeqB;         /* Address of the A==B subroutine */
2016   int addrAgtB;         /* Address of the A>B subroutine */
2017   int regLimitA;        /* Limit register for select-A */
2018   int regLimitB;        /* Limit register for select-A */
2019   int regPrev;          /* A range of registers to hold previous output */
2020   int savedLimit;       /* Saved value of p->iLimit */
2021   int savedOffset;      /* Saved value of p->iOffset */
2022   int labelCmpr;        /* Label for the start of the merge algorithm */
2023   int labelEnd;         /* Label for the end of the overall SELECT stmt */
2024   int j1;               /* Jump instructions that get retargetted */
2025   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
2026   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
2027   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
2028   sqlite3 *db;          /* Database connection */
2029   ExprList *pOrderBy;   /* The ORDER BY clause */
2030   int nOrderBy;         /* Number of terms in the ORDER BY clause */
2031   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
2032 
2033   assert( p->pOrderBy!=0 );
2034   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
2035   db = pParse->db;
2036   v = pParse->pVdbe;
2037   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
2038   labelEnd = sqlite3VdbeMakeLabel(v);
2039   labelCmpr = sqlite3VdbeMakeLabel(v);
2040 
2041 
2042   /* Patch up the ORDER BY clause
2043   */
2044   op = p->op;
2045   pPrior = p->pPrior;
2046   assert( pPrior->pOrderBy==0 );
2047   pOrderBy = p->pOrderBy;
2048   assert( pOrderBy );
2049   nOrderBy = pOrderBy->nExpr;
2050 
2051   /* For operators other than UNION ALL we have to make sure that
2052   ** the ORDER BY clause covers every term of the result set.  Add
2053   ** terms to the ORDER BY clause as necessary.
2054   */
2055   if( op!=TK_ALL ){
2056     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
2057       struct ExprList_item *pItem;
2058       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
2059         assert( pItem->iCol>0 );
2060         if( pItem->iCol==i ) break;
2061       }
2062       if( j==nOrderBy ){
2063         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
2064         if( pNew==0 ) return SQLITE_NOMEM;
2065         pNew->flags |= EP_IntValue;
2066         pNew->u.iValue = i;
2067         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
2068         pOrderBy->a[nOrderBy++].iCol = (u16)i;
2069       }
2070     }
2071   }
2072 
2073   /* Compute the comparison permutation and keyinfo that is used with
2074   ** the permutation used to determine if the next
2075   ** row of results comes from selectA or selectB.  Also add explicit
2076   ** collations to the ORDER BY clause terms so that when the subqueries
2077   ** to the right and the left are evaluated, they use the correct
2078   ** collation.
2079   */
2080   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
2081   if( aPermute ){
2082     struct ExprList_item *pItem;
2083     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
2084       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
2085       aPermute[i] = pItem->iCol - 1;
2086     }
2087     pKeyMerge =
2088       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
2089     if( pKeyMerge ){
2090       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
2091       pKeyMerge->nField = (u16)nOrderBy;
2092       pKeyMerge->enc = ENC(db);
2093       for(i=0; i<nOrderBy; i++){
2094         CollSeq *pColl;
2095         Expr *pTerm = pOrderBy->a[i].pExpr;
2096         if( pTerm->flags & EP_ExpCollate ){
2097           pColl = pTerm->pColl;
2098         }else{
2099           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
2100           pTerm->flags |= EP_ExpCollate;
2101           pTerm->pColl = pColl;
2102         }
2103         pKeyMerge->aColl[i] = pColl;
2104         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
2105       }
2106     }
2107   }else{
2108     pKeyMerge = 0;
2109   }
2110 
2111   /* Reattach the ORDER BY clause to the query.
2112   */
2113   p->pOrderBy = pOrderBy;
2114   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
2115 
2116   /* Allocate a range of temporary registers and the KeyInfo needed
2117   ** for the logic that removes duplicate result rows when the
2118   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
2119   */
2120   if( op==TK_ALL ){
2121     regPrev = 0;
2122   }else{
2123     int nExpr = p->pEList->nExpr;
2124     assert( nOrderBy>=nExpr || db->mallocFailed );
2125     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
2126     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
2127     pKeyDup = sqlite3DbMallocZero(db,
2128                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
2129     if( pKeyDup ){
2130       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
2131       pKeyDup->nField = (u16)nExpr;
2132       pKeyDup->enc = ENC(db);
2133       for(i=0; i<nExpr; i++){
2134         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
2135         pKeyDup->aSortOrder[i] = 0;
2136       }
2137     }
2138   }
2139 
2140   /* Separate the left and the right query from one another
2141   */
2142   p->pPrior = 0;
2143   pPrior->pRightmost = 0;
2144   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
2145   if( pPrior->pPrior==0 ){
2146     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
2147   }
2148 
2149   /* Compute the limit registers */
2150   computeLimitRegisters(pParse, p, labelEnd);
2151   if( p->iLimit && op==TK_ALL ){
2152     regLimitA = ++pParse->nMem;
2153     regLimitB = ++pParse->nMem;
2154     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
2155                                   regLimitA);
2156     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
2157   }else{
2158     regLimitA = regLimitB = 0;
2159   }
2160   sqlite3ExprDelete(db, p->pLimit);
2161   p->pLimit = 0;
2162   sqlite3ExprDelete(db, p->pOffset);
2163   p->pOffset = 0;
2164 
2165   regAddrA = ++pParse->nMem;
2166   regEofA = ++pParse->nMem;
2167   regAddrB = ++pParse->nMem;
2168   regEofB = ++pParse->nMem;
2169   regOutA = ++pParse->nMem;
2170   regOutB = ++pParse->nMem;
2171   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
2172   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
2173 
2174   /* Jump past the various subroutines and coroutines to the main
2175   ** merge loop
2176   */
2177   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
2178   addrSelectA = sqlite3VdbeCurrentAddr(v);
2179 
2180 
2181   /* Generate a coroutine to evaluate the SELECT statement to the
2182   ** left of the compound operator - the "A" select.
2183   */
2184   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
2185   pPrior->iLimit = regLimitA;
2186   sqlite3Select(pParse, pPrior, &destA);
2187   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
2188   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2189   VdbeNoopComment((v, "End coroutine for left SELECT"));
2190 
2191   /* Generate a coroutine to evaluate the SELECT statement on
2192   ** the right - the "B" select
2193   */
2194   addrSelectB = sqlite3VdbeCurrentAddr(v);
2195   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
2196   savedLimit = p->iLimit;
2197   savedOffset = p->iOffset;
2198   p->iLimit = regLimitB;
2199   p->iOffset = 0;
2200   sqlite3Select(pParse, p, &destB);
2201   p->iLimit = savedLimit;
2202   p->iOffset = savedOffset;
2203   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
2204   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
2205   VdbeNoopComment((v, "End coroutine for right SELECT"));
2206 
2207   /* Generate a subroutine that outputs the current row of the A
2208   ** select as the next output row of the compound select.
2209   */
2210   VdbeNoopComment((v, "Output routine for A"));
2211   addrOutA = generateOutputSubroutine(pParse,
2212                  p, &destA, pDest, regOutA,
2213                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
2214 
2215   /* Generate a subroutine that outputs the current row of the B
2216   ** select as the next output row of the compound select.
2217   */
2218   if( op==TK_ALL || op==TK_UNION ){
2219     VdbeNoopComment((v, "Output routine for B"));
2220     addrOutB = generateOutputSubroutine(pParse,
2221                  p, &destB, pDest, regOutB,
2222                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
2223   }
2224 
2225   /* Generate a subroutine to run when the results from select A
2226   ** are exhausted and only data in select B remains.
2227   */
2228   VdbeNoopComment((v, "eof-A subroutine"));
2229   if( op==TK_EXCEPT || op==TK_INTERSECT ){
2230     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
2231   }else{
2232     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
2233     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
2234     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
2235     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
2236   }
2237 
2238   /* Generate a subroutine to run when the results from select B
2239   ** are exhausted and only data in select A remains.
2240   */
2241   if( op==TK_INTERSECT ){
2242     addrEofB = addrEofA;
2243   }else{
2244     VdbeNoopComment((v, "eof-B subroutine"));
2245     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
2246     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
2247     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2248     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
2249   }
2250 
2251   /* Generate code to handle the case of A<B
2252   */
2253   VdbeNoopComment((v, "A-lt-B subroutine"));
2254   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
2255   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2256   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
2257   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2258 
2259   /* Generate code to handle the case of A==B
2260   */
2261   if( op==TK_ALL ){
2262     addrAeqB = addrAltB;
2263   }else if( op==TK_INTERSECT ){
2264     addrAeqB = addrAltB;
2265     addrAltB++;
2266   }else{
2267     VdbeNoopComment((v, "A-eq-B subroutine"));
2268     addrAeqB =
2269     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2270     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
2271     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2272   }
2273 
2274   /* Generate code to handle the case of A>B
2275   */
2276   VdbeNoopComment((v, "A-gt-B subroutine"));
2277   addrAgtB = sqlite3VdbeCurrentAddr(v);
2278   if( op==TK_ALL || op==TK_UNION ){
2279     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
2280   }
2281   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
2282   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
2283   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2284 
2285   /* This code runs once to initialize everything.
2286   */
2287   sqlite3VdbeJumpHere(v, j1);
2288   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
2289   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
2290   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
2291   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
2292   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
2293   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
2294 
2295   /* Implement the main merge loop
2296   */
2297   sqlite3VdbeResolveLabel(v, labelCmpr);
2298   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
2299   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
2300                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
2301   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
2302 
2303   /* Release temporary registers
2304   */
2305   if( regPrev ){
2306     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
2307   }
2308 
2309   /* Jump to the this point in order to terminate the query.
2310   */
2311   sqlite3VdbeResolveLabel(v, labelEnd);
2312 
2313   /* Set the number of output columns
2314   */
2315   if( pDest->eDest==SRT_Output ){
2316     Select *pFirst = pPrior;
2317     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
2318     generateColumnNames(pParse, 0, pFirst->pEList);
2319   }
2320 
2321   /* Reassembly the compound query so that it will be freed correctly
2322   ** by the calling function */
2323   if( p->pPrior ){
2324     sqlite3SelectDelete(db, p->pPrior);
2325   }
2326   p->pPrior = pPrior;
2327 
2328   /*** TBD:  Insert subroutine calls to close cursors on incomplete
2329   **** subqueries ****/
2330   return SQLITE_OK;
2331 }
2332 #endif
2333 
2334 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
2335 /* Forward Declarations */
2336 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
2337 static void substSelect(sqlite3*, Select *, int, ExprList *);
2338 
2339 /*
2340 ** Scan through the expression pExpr.  Replace every reference to
2341 ** a column in table number iTable with a copy of the iColumn-th
2342 ** entry in pEList.  (But leave references to the ROWID column
2343 ** unchanged.)
2344 **
2345 ** This routine is part of the flattening procedure.  A subquery
2346 ** whose result set is defined by pEList appears as entry in the
2347 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
2348 ** FORM clause entry is iTable.  This routine make the necessary
2349 ** changes to pExpr so that it refers directly to the source table
2350 ** of the subquery rather the result set of the subquery.
2351 */
2352 static Expr *substExpr(
2353   sqlite3 *db,        /* Report malloc errors to this connection */
2354   Expr *pExpr,        /* Expr in which substitution occurs */
2355   int iTable,         /* Table to be substituted */
2356   ExprList *pEList    /* Substitute expressions */
2357 ){
2358   if( pExpr==0 ) return 0;
2359   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
2360     if( pExpr->iColumn<0 ){
2361       pExpr->op = TK_NULL;
2362     }else{
2363       Expr *pNew;
2364       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
2365       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
2366       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
2367       if( pNew && pExpr->pColl ){
2368         pNew->pColl = pExpr->pColl;
2369       }
2370       sqlite3ExprDelete(db, pExpr);
2371       pExpr = pNew;
2372     }
2373   }else{
2374     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
2375     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
2376     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2377       substSelect(db, pExpr->x.pSelect, iTable, pEList);
2378     }else{
2379       substExprList(db, pExpr->x.pList, iTable, pEList);
2380     }
2381   }
2382   return pExpr;
2383 }
2384 static void substExprList(
2385   sqlite3 *db,         /* Report malloc errors here */
2386   ExprList *pList,     /* List to scan and in which to make substitutes */
2387   int iTable,          /* Table to be substituted */
2388   ExprList *pEList     /* Substitute values */
2389 ){
2390   int i;
2391   if( pList==0 ) return;
2392   for(i=0; i<pList->nExpr; i++){
2393     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
2394   }
2395 }
2396 static void substSelect(
2397   sqlite3 *db,         /* Report malloc errors here */
2398   Select *p,           /* SELECT statement in which to make substitutions */
2399   int iTable,          /* Table to be replaced */
2400   ExprList *pEList     /* Substitute values */
2401 ){
2402   SrcList *pSrc;
2403   struct SrcList_item *pItem;
2404   int i;
2405   if( !p ) return;
2406   substExprList(db, p->pEList, iTable, pEList);
2407   substExprList(db, p->pGroupBy, iTable, pEList);
2408   substExprList(db, p->pOrderBy, iTable, pEList);
2409   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
2410   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
2411   substSelect(db, p->pPrior, iTable, pEList);
2412   pSrc = p->pSrc;
2413   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
2414   if( ALWAYS(pSrc) ){
2415     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
2416       substSelect(db, pItem->pSelect, iTable, pEList);
2417     }
2418   }
2419 }
2420 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
2421 
2422 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
2423 /*
2424 ** This routine attempts to flatten subqueries in order to speed
2425 ** execution.  It returns 1 if it makes changes and 0 if no flattening
2426 ** occurs.
2427 **
2428 ** To understand the concept of flattening, consider the following
2429 ** query:
2430 **
2431 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
2432 **
2433 ** The default way of implementing this query is to execute the
2434 ** subquery first and store the results in a temporary table, then
2435 ** run the outer query on that temporary table.  This requires two
2436 ** passes over the data.  Furthermore, because the temporary table
2437 ** has no indices, the WHERE clause on the outer query cannot be
2438 ** optimized.
2439 **
2440 ** This routine attempts to rewrite queries such as the above into
2441 ** a single flat select, like this:
2442 **
2443 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
2444 **
2445 ** The code generated for this simpification gives the same result
2446 ** but only has to scan the data once.  And because indices might
2447 ** exist on the table t1, a complete scan of the data might be
2448 ** avoided.
2449 **
2450 ** Flattening is only attempted if all of the following are true:
2451 **
2452 **   (1)  The subquery and the outer query do not both use aggregates.
2453 **
2454 **   (2)  The subquery is not an aggregate or the outer query is not a join.
2455 **
2456 **   (3)  The subquery is not the right operand of a left outer join
2457 **        (Originally ticket #306.  Strenghtened by ticket #3300)
2458 **
2459 **   (4)  The subquery is not DISTINCT or the outer query is not a join.
2460 **
2461 **   (5)  The subquery is not DISTINCT or the outer query does not use
2462 **        aggregates.
2463 **
2464 **   (6)  The subquery does not use aggregates or the outer query is not
2465 **        DISTINCT.
2466 **
2467 **   (7)  The subquery has a FROM clause.
2468 **
2469 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
2470 **
2471 **   (9)  The subquery does not use LIMIT or the outer query does not use
2472 **        aggregates.
2473 **
2474 **  (10)  The subquery does not use aggregates or the outer query does not
2475 **        use LIMIT.
2476 **
2477 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
2478 **
2479 **  (12)  Not implemented.  Subsumed into restriction (3).  Was previously
2480 **        a separate restriction deriving from ticket #350.
2481 **
2482 **  (13)  The subquery and outer query do not both use LIMIT
2483 **
2484 **  (14)  The subquery does not use OFFSET
2485 **
2486 **  (15)  The outer query is not part of a compound select or the
2487 **        subquery does not have both an ORDER BY and a LIMIT clause.
2488 **        (See ticket #2339)
2489 **
2490 **  (16)  The outer query is not an aggregate or the subquery does
2491 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
2492 **        until we introduced the group_concat() function.
2493 **
2494 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
2495 **        compound clause made up entirely of non-aggregate queries, and
2496 **        the parent query:
2497 **
2498 **          * is not itself part of a compound select,
2499 **          * is not an aggregate or DISTINCT query, and
2500 **          * has no other tables or sub-selects in the FROM clause.
2501 **
2502 **        The parent and sub-query may contain WHERE clauses. Subject to
2503 **        rules (11), (13) and (14), they may also contain ORDER BY,
2504 **        LIMIT and OFFSET clauses.
2505 **
2506 **  (18)  If the sub-query is a compound select, then all terms of the
2507 **        ORDER by clause of the parent must be simple references to
2508 **        columns of the sub-query.
2509 **
2510 **  (19)  The subquery does not use LIMIT or the outer query does not
2511 **        have a WHERE clause.
2512 **
2513 **  (20)  If the sub-query is a compound select, then it must not use
2514 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
2515 **        somewhat by saying that the terms of the ORDER BY clause must
2516 **        appear as unmodified result columns in the outer query.  But
2517 **        have other optimizations in mind to deal with that case.
2518 **
2519 ** In this routine, the "p" parameter is a pointer to the outer query.
2520 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
2521 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
2522 **
2523 ** If flattening is not attempted, this routine is a no-op and returns 0.
2524 ** If flattening is attempted this routine returns 1.
2525 **
2526 ** All of the expression analysis must occur on both the outer query and
2527 ** the subquery before this routine runs.
2528 */
2529 static int flattenSubquery(
2530   Parse *pParse,       /* Parsing context */
2531   Select *p,           /* The parent or outer SELECT statement */
2532   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
2533   int isAgg,           /* True if outer SELECT uses aggregate functions */
2534   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
2535 ){
2536   const char *zSavedAuthContext = pParse->zAuthContext;
2537   Select *pParent;
2538   Select *pSub;       /* The inner query or "subquery" */
2539   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
2540   SrcList *pSrc;      /* The FROM clause of the outer query */
2541   SrcList *pSubSrc;   /* The FROM clause of the subquery */
2542   ExprList *pList;    /* The result set of the outer query */
2543   int iParent;        /* VDBE cursor number of the pSub result set temp table */
2544   int i;              /* Loop counter */
2545   Expr *pWhere;                    /* The WHERE clause */
2546   struct SrcList_item *pSubitem;   /* The subquery */
2547   sqlite3 *db = pParse->db;
2548 
2549   /* Check to see if flattening is permitted.  Return 0 if not.
2550   */
2551   assert( p!=0 );
2552   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
2553   pSrc = p->pSrc;
2554   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
2555   pSubitem = &pSrc->a[iFrom];
2556   iParent = pSubitem->iCursor;
2557   pSub = pSubitem->pSelect;
2558   assert( pSub!=0 );
2559   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
2560   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
2561   pSubSrc = pSub->pSrc;
2562   assert( pSubSrc );
2563   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
2564   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
2565   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
2566   ** became arbitrary expressions, we were forced to add restrictions (13)
2567   ** and (14). */
2568   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
2569   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
2570   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
2571     return 0;                                            /* Restriction (15) */
2572   }
2573   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
2574   if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit)
2575          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
2576      return 0;
2577   }
2578   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
2579      return 0;         /* Restriction (6)  */
2580   }
2581   if( p->pOrderBy && pSub->pOrderBy ){
2582      return 0;                                           /* Restriction (11) */
2583   }
2584   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
2585   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
2586 
2587   /* OBSOLETE COMMENT 1:
2588   ** Restriction 3:  If the subquery is a join, make sure the subquery is
2589   ** not used as the right operand of an outer join.  Examples of why this
2590   ** is not allowed:
2591   **
2592   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
2593   **
2594   ** If we flatten the above, we would get
2595   **
2596   **         (t1 LEFT OUTER JOIN t2) JOIN t3
2597   **
2598   ** which is not at all the same thing.
2599   **
2600   ** OBSOLETE COMMENT 2:
2601   ** Restriction 12:  If the subquery is the right operand of a left outer
2602   ** join, make sure the subquery has no WHERE clause.
2603   ** An examples of why this is not allowed:
2604   **
2605   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
2606   **
2607   ** If we flatten the above, we would get
2608   **
2609   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
2610   **
2611   ** But the t2.x>0 test will always fail on a NULL row of t2, which
2612   ** effectively converts the OUTER JOIN into an INNER JOIN.
2613   **
2614   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
2615   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
2616   ** is fraught with danger.  Best to avoid the whole thing.  If the
2617   ** subquery is the right term of a LEFT JOIN, then do not flatten.
2618   */
2619   if( (pSubitem->jointype & JT_OUTER)!=0 ){
2620     return 0;
2621   }
2622 
2623   /* Restriction 17: If the sub-query is a compound SELECT, then it must
2624   ** use only the UNION ALL operator. And none of the simple select queries
2625   ** that make up the compound SELECT are allowed to be aggregate or distinct
2626   ** queries.
2627   */
2628   if( pSub->pPrior ){
2629     if( pSub->pOrderBy ){
2630       return 0;  /* Restriction 20 */
2631     }
2632     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
2633       return 0;
2634     }
2635     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
2636       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
2637       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
2638       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
2639        || (pSub1->pPrior && pSub1->op!=TK_ALL)
2640        || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
2641       ){
2642         return 0;
2643       }
2644     }
2645 
2646     /* Restriction 18. */
2647     if( p->pOrderBy ){
2648       int ii;
2649       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
2650         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
2651       }
2652     }
2653   }
2654 
2655   /***** If we reach this point, flattening is permitted. *****/
2656 
2657   /* Authorize the subquery */
2658   pParse->zAuthContext = pSubitem->zName;
2659   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
2660   pParse->zAuthContext = zSavedAuthContext;
2661 
2662   /* If the sub-query is a compound SELECT statement, then (by restrictions
2663   ** 17 and 18 above) it must be a UNION ALL and the parent query must
2664   ** be of the form:
2665   **
2666   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
2667   **
2668   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
2669   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
2670   ** OFFSET clauses and joins them to the left-hand-side of the original
2671   ** using UNION ALL operators. In this case N is the number of simple
2672   ** select statements in the compound sub-query.
2673   **
2674   ** Example:
2675   **
2676   **     SELECT a+1 FROM (
2677   **        SELECT x FROM tab
2678   **        UNION ALL
2679   **        SELECT y FROM tab
2680   **        UNION ALL
2681   **        SELECT abs(z*2) FROM tab2
2682   **     ) WHERE a!=5 ORDER BY 1
2683   **
2684   ** Transformed into:
2685   **
2686   **     SELECT x+1 FROM tab WHERE x+1!=5
2687   **     UNION ALL
2688   **     SELECT y+1 FROM tab WHERE y+1!=5
2689   **     UNION ALL
2690   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
2691   **     ORDER BY 1
2692   **
2693   ** We call this the "compound-subquery flattening".
2694   */
2695   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
2696     Select *pNew;
2697     ExprList *pOrderBy = p->pOrderBy;
2698     Expr *pLimit = p->pLimit;
2699     Select *pPrior = p->pPrior;
2700     p->pOrderBy = 0;
2701     p->pSrc = 0;
2702     p->pPrior = 0;
2703     p->pLimit = 0;
2704     pNew = sqlite3SelectDup(db, p, 0);
2705     p->pLimit = pLimit;
2706     p->pOrderBy = pOrderBy;
2707     p->pSrc = pSrc;
2708     p->op = TK_ALL;
2709     p->pRightmost = 0;
2710     if( pNew==0 ){
2711       pNew = pPrior;
2712     }else{
2713       pNew->pPrior = pPrior;
2714       pNew->pRightmost = 0;
2715     }
2716     p->pPrior = pNew;
2717     if( db->mallocFailed ) return 1;
2718   }
2719 
2720   /* Begin flattening the iFrom-th entry of the FROM clause
2721   ** in the outer query.
2722   */
2723   pSub = pSub1 = pSubitem->pSelect;
2724 
2725   /* Delete the transient table structure associated with the
2726   ** subquery
2727   */
2728   sqlite3DbFree(db, pSubitem->zDatabase);
2729   sqlite3DbFree(db, pSubitem->zName);
2730   sqlite3DbFree(db, pSubitem->zAlias);
2731   pSubitem->zDatabase = 0;
2732   pSubitem->zName = 0;
2733   pSubitem->zAlias = 0;
2734   pSubitem->pSelect = 0;
2735 
2736   /* Defer deleting the Table object associated with the
2737   ** subquery until code generation is
2738   ** complete, since there may still exist Expr.pTab entries that
2739   ** refer to the subquery even after flattening.  Ticket #3346.
2740   **
2741   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
2742   */
2743   if( ALWAYS(pSubitem->pTab!=0) ){
2744     Table *pTabToDel = pSubitem->pTab;
2745     if( pTabToDel->nRef==1 ){
2746       Parse *pToplevel = sqlite3ParseToplevel(pParse);
2747       pTabToDel->pNextZombie = pToplevel->pZombieTab;
2748       pToplevel->pZombieTab = pTabToDel;
2749     }else{
2750       pTabToDel->nRef--;
2751     }
2752     pSubitem->pTab = 0;
2753   }
2754 
2755   /* The following loop runs once for each term in a compound-subquery
2756   ** flattening (as described above).  If we are doing a different kind
2757   ** of flattening - a flattening other than a compound-subquery flattening -
2758   ** then this loop only runs once.
2759   **
2760   ** This loop moves all of the FROM elements of the subquery into the
2761   ** the FROM clause of the outer query.  Before doing this, remember
2762   ** the cursor number for the original outer query FROM element in
2763   ** iParent.  The iParent cursor will never be used.  Subsequent code
2764   ** will scan expressions looking for iParent references and replace
2765   ** those references with expressions that resolve to the subquery FROM
2766   ** elements we are now copying in.
2767   */
2768   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
2769     int nSubSrc;
2770     u8 jointype = 0;
2771     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
2772     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
2773     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
2774 
2775     if( pSrc ){
2776       assert( pParent==p );  /* First time through the loop */
2777       jointype = pSubitem->jointype;
2778     }else{
2779       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
2780       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
2781       if( pSrc==0 ){
2782         assert( db->mallocFailed );
2783         break;
2784       }
2785     }
2786 
2787     /* The subquery uses a single slot of the FROM clause of the outer
2788     ** query.  If the subquery has more than one element in its FROM clause,
2789     ** then expand the outer query to make space for it to hold all elements
2790     ** of the subquery.
2791     **
2792     ** Example:
2793     **
2794     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
2795     **
2796     ** The outer query has 3 slots in its FROM clause.  One slot of the
2797     ** outer query (the middle slot) is used by the subquery.  The next
2798     ** block of code will expand the out query to 4 slots.  The middle
2799     ** slot is expanded to two slots in order to make space for the
2800     ** two elements in the FROM clause of the subquery.
2801     */
2802     if( nSubSrc>1 ){
2803       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
2804       if( db->mallocFailed ){
2805         break;
2806       }
2807     }
2808 
2809     /* Transfer the FROM clause terms from the subquery into the
2810     ** outer query.
2811     */
2812     for(i=0; i<nSubSrc; i++){
2813       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
2814       pSrc->a[i+iFrom] = pSubSrc->a[i];
2815       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2816     }
2817     pSrc->a[iFrom].jointype = jointype;
2818 
2819     /* Now begin substituting subquery result set expressions for
2820     ** references to the iParent in the outer query.
2821     **
2822     ** Example:
2823     **
2824     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2825     **   \                     \_____________ subquery __________/          /
2826     **    \_____________________ outer query ______________________________/
2827     **
2828     ** We look at every expression in the outer query and every place we see
2829     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2830     */
2831     pList = pParent->pEList;
2832     for(i=0; i<pList->nExpr; i++){
2833       if( pList->a[i].zName==0 ){
2834         const char *zSpan = pList->a[i].zSpan;
2835         if( ALWAYS(zSpan) ){
2836           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
2837         }
2838       }
2839     }
2840     substExprList(db, pParent->pEList, iParent, pSub->pEList);
2841     if( isAgg ){
2842       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
2843       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
2844     }
2845     if( pSub->pOrderBy ){
2846       assert( pParent->pOrderBy==0 );
2847       pParent->pOrderBy = pSub->pOrderBy;
2848       pSub->pOrderBy = 0;
2849     }else if( pParent->pOrderBy ){
2850       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
2851     }
2852     if( pSub->pWhere ){
2853       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
2854     }else{
2855       pWhere = 0;
2856     }
2857     if( subqueryIsAgg ){
2858       assert( pParent->pHaving==0 );
2859       pParent->pHaving = pParent->pWhere;
2860       pParent->pWhere = pWhere;
2861       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
2862       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
2863                                   sqlite3ExprDup(db, pSub->pHaving, 0));
2864       assert( pParent->pGroupBy==0 );
2865       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
2866     }else{
2867       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
2868       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
2869     }
2870 
2871     /* The flattened query is distinct if either the inner or the
2872     ** outer query is distinct.
2873     */
2874     pParent->selFlags |= pSub->selFlags & SF_Distinct;
2875 
2876     /*
2877     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2878     **
2879     ** One is tempted to try to add a and b to combine the limits.  But this
2880     ** does not work if either limit is negative.
2881     */
2882     if( pSub->pLimit ){
2883       pParent->pLimit = pSub->pLimit;
2884       pSub->pLimit = 0;
2885     }
2886   }
2887 
2888   /* Finially, delete what is left of the subquery and return
2889   ** success.
2890   */
2891   sqlite3SelectDelete(db, pSub1);
2892 
2893   return 1;
2894 }
2895 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
2896 
2897 /*
2898 ** Analyze the SELECT statement passed as an argument to see if it
2899 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
2900 ** it is, or 0 otherwise. At present, a query is considered to be
2901 ** a min()/max() query if:
2902 **
2903 **   1. There is a single object in the FROM clause.
2904 **
2905 **   2. There is a single expression in the result set, and it is
2906 **      either min(x) or max(x), where x is a column reference.
2907 */
2908 static u8 minMaxQuery(Select *p){
2909   Expr *pExpr;
2910   ExprList *pEList = p->pEList;
2911 
2912   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
2913   pExpr = pEList->a[0].pExpr;
2914   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
2915   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
2916   pEList = pExpr->x.pList;
2917   if( pEList==0 || pEList->nExpr!=1 ) return 0;
2918   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
2919   assert( !ExprHasProperty(pExpr, EP_IntValue) );
2920   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
2921     return WHERE_ORDERBY_MIN;
2922   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
2923     return WHERE_ORDERBY_MAX;
2924   }
2925   return WHERE_ORDERBY_NORMAL;
2926 }
2927 
2928 /*
2929 ** The select statement passed as the first argument is an aggregate query.
2930 ** The second argment is the associated aggregate-info object. This
2931 ** function tests if the SELECT is of the form:
2932 **
2933 **   SELECT count(*) FROM <tbl>
2934 **
2935 ** where table is a database table, not a sub-select or view. If the query
2936 ** does match this pattern, then a pointer to the Table object representing
2937 ** <tbl> is returned. Otherwise, 0 is returned.
2938 */
2939 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
2940   Table *pTab;
2941   Expr *pExpr;
2942 
2943   assert( !p->pGroupBy );
2944 
2945   if( p->pWhere || p->pEList->nExpr!=1
2946    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
2947   ){
2948     return 0;
2949   }
2950   pTab = p->pSrc->a[0].pTab;
2951   pExpr = p->pEList->a[0].pExpr;
2952   assert( pTab && !pTab->pSelect && pExpr );
2953 
2954   if( IsVirtual(pTab) ) return 0;
2955   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
2956   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
2957   if( pExpr->flags&EP_Distinct ) return 0;
2958 
2959   return pTab;
2960 }
2961 
2962 /*
2963 ** If the source-list item passed as an argument was augmented with an
2964 ** INDEXED BY clause, then try to locate the specified index. If there
2965 ** was such a clause and the named index cannot be found, return
2966 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
2967 ** pFrom->pIndex and return SQLITE_OK.
2968 */
2969 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
2970   if( pFrom->pTab && pFrom->zIndex ){
2971     Table *pTab = pFrom->pTab;
2972     char *zIndex = pFrom->zIndex;
2973     Index *pIdx;
2974     for(pIdx=pTab->pIndex;
2975         pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
2976         pIdx=pIdx->pNext
2977     );
2978     if( !pIdx ){
2979       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
2980       return SQLITE_ERROR;
2981     }
2982     pFrom->pIndex = pIdx;
2983   }
2984   return SQLITE_OK;
2985 }
2986 
2987 /*
2988 ** This routine is a Walker callback for "expanding" a SELECT statement.
2989 ** "Expanding" means to do the following:
2990 **
2991 **    (1)  Make sure VDBE cursor numbers have been assigned to every
2992 **         element of the FROM clause.
2993 **
2994 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
2995 **         defines FROM clause.  When views appear in the FROM clause,
2996 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
2997 **         that implements the view.  A copy is made of the view's SELECT
2998 **         statement so that we can freely modify or delete that statement
2999 **         without worrying about messing up the presistent representation
3000 **         of the view.
3001 **
3002 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
3003 **         on joins and the ON and USING clause of joins.
3004 **
3005 **    (4)  Scan the list of columns in the result set (pEList) looking
3006 **         for instances of the "*" operator or the TABLE.* operator.
3007 **         If found, expand each "*" to be every column in every table
3008 **         and TABLE.* to be every column in TABLE.
3009 **
3010 */
3011 static int selectExpander(Walker *pWalker, Select *p){
3012   Parse *pParse = pWalker->pParse;
3013   int i, j, k;
3014   SrcList *pTabList;
3015   ExprList *pEList;
3016   struct SrcList_item *pFrom;
3017   sqlite3 *db = pParse->db;
3018 
3019   if( db->mallocFailed  ){
3020     return WRC_Abort;
3021   }
3022   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
3023     return WRC_Prune;
3024   }
3025   p->selFlags |= SF_Expanded;
3026   pTabList = p->pSrc;
3027   pEList = p->pEList;
3028 
3029   /* Make sure cursor numbers have been assigned to all entries in
3030   ** the FROM clause of the SELECT statement.
3031   */
3032   sqlite3SrcListAssignCursors(pParse, pTabList);
3033 
3034   /* Look up every table named in the FROM clause of the select.  If
3035   ** an entry of the FROM clause is a subquery instead of a table or view,
3036   ** then create a transient table structure to describe the subquery.
3037   */
3038   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
3039     Table *pTab;
3040     if( pFrom->pTab!=0 ){
3041       /* This statement has already been prepared.  There is no need
3042       ** to go further. */
3043       assert( i==0 );
3044       return WRC_Prune;
3045     }
3046     if( pFrom->zName==0 ){
3047 #ifndef SQLITE_OMIT_SUBQUERY
3048       Select *pSel = pFrom->pSelect;
3049       /* A sub-query in the FROM clause of a SELECT */
3050       assert( pSel!=0 );
3051       assert( pFrom->pTab==0 );
3052       sqlite3WalkSelect(pWalker, pSel);
3053       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
3054       if( pTab==0 ) return WRC_Abort;
3055       pTab->dbMem = db->lookaside.bEnabled ? db : 0;
3056       pTab->nRef = 1;
3057       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
3058       while( pSel->pPrior ){ pSel = pSel->pPrior; }
3059       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
3060       pTab->iPKey = -1;
3061       pTab->tabFlags |= TF_Ephemeral;
3062 #endif
3063     }else{
3064       /* An ordinary table or view name in the FROM clause */
3065       assert( pFrom->pTab==0 );
3066       pFrom->pTab = pTab =
3067         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
3068       if( pTab==0 ) return WRC_Abort;
3069       pTab->nRef++;
3070 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
3071       if( pTab->pSelect || IsVirtual(pTab) ){
3072         /* We reach here if the named table is a really a view */
3073         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
3074         assert( pFrom->pSelect==0 );
3075         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
3076         sqlite3WalkSelect(pWalker, pFrom->pSelect);
3077       }
3078 #endif
3079     }
3080 
3081     /* Locate the index named by the INDEXED BY clause, if any. */
3082     if( sqlite3IndexedByLookup(pParse, pFrom) ){
3083       return WRC_Abort;
3084     }
3085   }
3086 
3087   /* Process NATURAL keywords, and ON and USING clauses of joins.
3088   */
3089   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
3090     return WRC_Abort;
3091   }
3092 
3093   /* For every "*" that occurs in the column list, insert the names of
3094   ** all columns in all tables.  And for every TABLE.* insert the names
3095   ** of all columns in TABLE.  The parser inserted a special expression
3096   ** with the TK_ALL operator for each "*" that it found in the column list.
3097   ** The following code just has to locate the TK_ALL expressions and expand
3098   ** each one to the list of all columns in all tables.
3099   **
3100   ** The first loop just checks to see if there are any "*" operators
3101   ** that need expanding.
3102   */
3103   for(k=0; k<pEList->nExpr; k++){
3104     Expr *pE = pEList->a[k].pExpr;
3105     if( pE->op==TK_ALL ) break;
3106     assert( pE->op!=TK_DOT || pE->pRight!=0 );
3107     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
3108     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
3109   }
3110   if( k<pEList->nExpr ){
3111     /*
3112     ** If we get here it means the result set contains one or more "*"
3113     ** operators that need to be expanded.  Loop through each expression
3114     ** in the result set and expand them one by one.
3115     */
3116     struct ExprList_item *a = pEList->a;
3117     ExprList *pNew = 0;
3118     int flags = pParse->db->flags;
3119     int longNames = (flags & SQLITE_FullColNames)!=0
3120                       && (flags & SQLITE_ShortColNames)==0;
3121 
3122     for(k=0; k<pEList->nExpr; k++){
3123       Expr *pE = a[k].pExpr;
3124       assert( pE->op!=TK_DOT || pE->pRight!=0 );
3125       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
3126         /* This particular expression does not need to be expanded.
3127         */
3128         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
3129         if( pNew ){
3130           pNew->a[pNew->nExpr-1].zName = a[k].zName;
3131           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
3132           a[k].zName = 0;
3133           a[k].zSpan = 0;
3134         }
3135         a[k].pExpr = 0;
3136       }else{
3137         /* This expression is a "*" or a "TABLE.*" and needs to be
3138         ** expanded. */
3139         int tableSeen = 0;      /* Set to 1 when TABLE matches */
3140         char *zTName;            /* text of name of TABLE */
3141         if( pE->op==TK_DOT ){
3142           assert( pE->pLeft!=0 );
3143           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
3144           zTName = pE->pLeft->u.zToken;
3145         }else{
3146           zTName = 0;
3147         }
3148         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
3149           Table *pTab = pFrom->pTab;
3150           char *zTabName = pFrom->zAlias;
3151           if( zTabName==0 ){
3152             zTabName = pTab->zName;
3153           }
3154           if( db->mallocFailed ) break;
3155           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
3156             continue;
3157           }
3158           tableSeen = 1;
3159           for(j=0; j<pTab->nCol; j++){
3160             Expr *pExpr, *pRight;
3161             char *zName = pTab->aCol[j].zName;
3162             char *zColname;  /* The computed column name */
3163             char *zToFree;   /* Malloced string that needs to be freed */
3164             Token sColname;  /* Computed column name as a token */
3165 
3166             /* If a column is marked as 'hidden' (currently only possible
3167             ** for virtual tables), do not include it in the expanded
3168             ** result-set list.
3169             */
3170             if( IsHiddenColumn(&pTab->aCol[j]) ){
3171               assert(IsVirtual(pTab));
3172               continue;
3173             }
3174 
3175             if( i>0 && zTName==0 ){
3176               struct SrcList_item *pLeft = &pTabList->a[i-1];
3177               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
3178                         columnIndex(pLeft->pTab, zName)>=0 ){
3179                 /* In a NATURAL join, omit the join columns from the
3180                 ** table on the right */
3181                 continue;
3182               }
3183               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
3184                 /* In a join with a USING clause, omit columns in the
3185                 ** using clause from the table on the right. */
3186                 continue;
3187               }
3188             }
3189             pRight = sqlite3Expr(db, TK_ID, zName);
3190             zColname = zName;
3191             zToFree = 0;
3192             if( longNames || pTabList->nSrc>1 ){
3193               Expr *pLeft;
3194               pLeft = sqlite3Expr(db, TK_ID, zTabName);
3195               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
3196               if( longNames ){
3197                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
3198                 zToFree = zColname;
3199               }
3200             }else{
3201               pExpr = pRight;
3202             }
3203             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
3204             sColname.z = zColname;
3205             sColname.n = sqlite3Strlen30(zColname);
3206             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
3207             sqlite3DbFree(db, zToFree);
3208           }
3209         }
3210         if( !tableSeen ){
3211           if( zTName ){
3212             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
3213           }else{
3214             sqlite3ErrorMsg(pParse, "no tables specified");
3215           }
3216         }
3217       }
3218     }
3219     sqlite3ExprListDelete(db, pEList);
3220     p->pEList = pNew;
3221   }
3222 #if SQLITE_MAX_COLUMN
3223   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
3224     sqlite3ErrorMsg(pParse, "too many columns in result set");
3225   }
3226 #endif
3227   return WRC_Continue;
3228 }
3229 
3230 /*
3231 ** No-op routine for the parse-tree walker.
3232 **
3233 ** When this routine is the Walker.xExprCallback then expression trees
3234 ** are walked without any actions being taken at each node.  Presumably,
3235 ** when this routine is used for Walker.xExprCallback then
3236 ** Walker.xSelectCallback is set to do something useful for every
3237 ** subquery in the parser tree.
3238 */
3239 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
3240   UNUSED_PARAMETER2(NotUsed, NotUsed2);
3241   return WRC_Continue;
3242 }
3243 
3244 /*
3245 ** This routine "expands" a SELECT statement and all of its subqueries.
3246 ** For additional information on what it means to "expand" a SELECT
3247 ** statement, see the comment on the selectExpand worker callback above.
3248 **
3249 ** Expanding a SELECT statement is the first step in processing a
3250 ** SELECT statement.  The SELECT statement must be expanded before
3251 ** name resolution is performed.
3252 **
3253 ** If anything goes wrong, an error message is written into pParse.
3254 ** The calling function can detect the problem by looking at pParse->nErr
3255 ** and/or pParse->db->mallocFailed.
3256 */
3257 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
3258   Walker w;
3259   w.xSelectCallback = selectExpander;
3260   w.xExprCallback = exprWalkNoop;
3261   w.pParse = pParse;
3262   sqlite3WalkSelect(&w, pSelect);
3263 }
3264 
3265 
3266 #ifndef SQLITE_OMIT_SUBQUERY
3267 /*
3268 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
3269 ** interface.
3270 **
3271 ** For each FROM-clause subquery, add Column.zType and Column.zColl
3272 ** information to the Table structure that represents the result set
3273 ** of that subquery.
3274 **
3275 ** The Table structure that represents the result set was constructed
3276 ** by selectExpander() but the type and collation information was omitted
3277 ** at that point because identifiers had not yet been resolved.  This
3278 ** routine is called after identifier resolution.
3279 */
3280 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
3281   Parse *pParse;
3282   int i;
3283   SrcList *pTabList;
3284   struct SrcList_item *pFrom;
3285 
3286   assert( p->selFlags & SF_Resolved );
3287   assert( (p->selFlags & SF_HasTypeInfo)==0 );
3288   p->selFlags |= SF_HasTypeInfo;
3289   pParse = pWalker->pParse;
3290   pTabList = p->pSrc;
3291   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
3292     Table *pTab = pFrom->pTab;
3293     if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
3294       /* A sub-query in the FROM clause of a SELECT */
3295       Select *pSel = pFrom->pSelect;
3296       assert( pSel );
3297       while( pSel->pPrior ) pSel = pSel->pPrior;
3298       selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
3299     }
3300   }
3301   return WRC_Continue;
3302 }
3303 #endif
3304 
3305 
3306 /*
3307 ** This routine adds datatype and collating sequence information to
3308 ** the Table structures of all FROM-clause subqueries in a
3309 ** SELECT statement.
3310 **
3311 ** Use this routine after name resolution.
3312 */
3313 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
3314 #ifndef SQLITE_OMIT_SUBQUERY
3315   Walker w;
3316   w.xSelectCallback = selectAddSubqueryTypeInfo;
3317   w.xExprCallback = exprWalkNoop;
3318   w.pParse = pParse;
3319   sqlite3WalkSelect(&w, pSelect);
3320 #endif
3321 }
3322 
3323 
3324 /*
3325 ** This routine sets of a SELECT statement for processing.  The
3326 ** following is accomplished:
3327 **
3328 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
3329 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
3330 **     *  ON and USING clauses are shifted into WHERE statements
3331 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
3332 **     *  Identifiers in expression are matched to tables.
3333 **
3334 ** This routine acts recursively on all subqueries within the SELECT.
3335 */
3336 void sqlite3SelectPrep(
3337   Parse *pParse,         /* The parser context */
3338   Select *p,             /* The SELECT statement being coded. */
3339   NameContext *pOuterNC  /* Name context for container */
3340 ){
3341   sqlite3 *db;
3342   if( NEVER(p==0) ) return;
3343   db = pParse->db;
3344   if( p->selFlags & SF_HasTypeInfo ) return;
3345   sqlite3SelectExpand(pParse, p);
3346   if( pParse->nErr || db->mallocFailed ) return;
3347   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
3348   if( pParse->nErr || db->mallocFailed ) return;
3349   sqlite3SelectAddTypeInfo(pParse, p);
3350 }
3351 
3352 /*
3353 ** Reset the aggregate accumulator.
3354 **
3355 ** The aggregate accumulator is a set of memory cells that hold
3356 ** intermediate results while calculating an aggregate.  This
3357 ** routine simply stores NULLs in all of those memory cells.
3358 */
3359 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
3360   Vdbe *v = pParse->pVdbe;
3361   int i;
3362   struct AggInfo_func *pFunc;
3363   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
3364     return;
3365   }
3366   for(i=0; i<pAggInfo->nColumn; i++){
3367     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
3368   }
3369   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
3370     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
3371     if( pFunc->iDistinct>=0 ){
3372       Expr *pE = pFunc->pExpr;
3373       assert( !ExprHasProperty(pE, EP_xIsSelect) );
3374       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
3375         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
3376            "argument");
3377         pFunc->iDistinct = -1;
3378       }else{
3379         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
3380         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
3381                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
3382       }
3383     }
3384   }
3385 }
3386 
3387 /*
3388 ** Invoke the OP_AggFinalize opcode for every aggregate function
3389 ** in the AggInfo structure.
3390 */
3391 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
3392   Vdbe *v = pParse->pVdbe;
3393   int i;
3394   struct AggInfo_func *pF;
3395   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
3396     ExprList *pList = pF->pExpr->x.pList;
3397     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
3398     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
3399                       (void*)pF->pFunc, P4_FUNCDEF);
3400   }
3401 }
3402 
3403 /*
3404 ** Update the accumulator memory cells for an aggregate based on
3405 ** the current cursor position.
3406 */
3407 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
3408   Vdbe *v = pParse->pVdbe;
3409   int i;
3410   struct AggInfo_func *pF;
3411   struct AggInfo_col *pC;
3412 
3413   pAggInfo->directMode = 1;
3414   sqlite3ExprCacheClear(pParse);
3415   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
3416     int nArg;
3417     int addrNext = 0;
3418     int regAgg;
3419     ExprList *pList = pF->pExpr->x.pList;
3420     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
3421     if( pList ){
3422       nArg = pList->nExpr;
3423       regAgg = sqlite3GetTempRange(pParse, nArg);
3424       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
3425     }else{
3426       nArg = 0;
3427       regAgg = 0;
3428     }
3429     if( pF->iDistinct>=0 ){
3430       addrNext = sqlite3VdbeMakeLabel(v);
3431       assert( nArg==1 );
3432       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
3433     }
3434     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
3435       CollSeq *pColl = 0;
3436       struct ExprList_item *pItem;
3437       int j;
3438       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
3439       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
3440         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
3441       }
3442       if( !pColl ){
3443         pColl = pParse->db->pDfltColl;
3444       }
3445       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
3446     }
3447     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
3448                       (void*)pF->pFunc, P4_FUNCDEF);
3449     sqlite3VdbeChangeP5(v, (u8)nArg);
3450     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
3451     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
3452     if( addrNext ){
3453       sqlite3VdbeResolveLabel(v, addrNext);
3454       sqlite3ExprCacheClear(pParse);
3455     }
3456   }
3457   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
3458     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
3459   }
3460   pAggInfo->directMode = 0;
3461   sqlite3ExprCacheClear(pParse);
3462 }
3463 
3464 /*
3465 ** Generate code for the SELECT statement given in the p argument.
3466 **
3467 ** The results are distributed in various ways depending on the
3468 ** contents of the SelectDest structure pointed to by argument pDest
3469 ** as follows:
3470 **
3471 **     pDest->eDest    Result
3472 **     ------------    -------------------------------------------
3473 **     SRT_Output      Generate a row of output (using the OP_ResultRow
3474 **                     opcode) for each row in the result set.
3475 **
3476 **     SRT_Mem         Only valid if the result is a single column.
3477 **                     Store the first column of the first result row
3478 **                     in register pDest->iParm then abandon the rest
3479 **                     of the query.  This destination implies "LIMIT 1".
3480 **
3481 **     SRT_Set         The result must be a single column.  Store each
3482 **                     row of result as the key in table pDest->iParm.
3483 **                     Apply the affinity pDest->affinity before storing
3484 **                     results.  Used to implement "IN (SELECT ...)".
3485 **
3486 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
3487 **
3488 **     SRT_Except      Remove results from the temporary table pDest->iParm.
3489 **
3490 **     SRT_Table       Store results in temporary table pDest->iParm.
3491 **                     This is like SRT_EphemTab except that the table
3492 **                     is assumed to already be open.
3493 **
3494 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
3495 **                     the result there. The cursor is left open after
3496 **                     returning.  This is like SRT_Table except that
3497 **                     this destination uses OP_OpenEphemeral to create
3498 **                     the table first.
3499 **
3500 **     SRT_Coroutine   Generate a co-routine that returns a new row of
3501 **                     results each time it is invoked.  The entry point
3502 **                     of the co-routine is stored in register pDest->iParm.
3503 **
3504 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
3505 **                     set is not empty.
3506 **
3507 **     SRT_Discard     Throw the results away.  This is used by SELECT
3508 **                     statements within triggers whose only purpose is
3509 **                     the side-effects of functions.
3510 **
3511 ** This routine returns the number of errors.  If any errors are
3512 ** encountered, then an appropriate error message is left in
3513 ** pParse->zErrMsg.
3514 **
3515 ** This routine does NOT free the Select structure passed in.  The
3516 ** calling function needs to do that.
3517 */
3518 int sqlite3Select(
3519   Parse *pParse,         /* The parser context */
3520   Select *p,             /* The SELECT statement being coded. */
3521   SelectDest *pDest      /* What to do with the query results */
3522 ){
3523   int i, j;              /* Loop counters */
3524   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
3525   Vdbe *v;               /* The virtual machine under construction */
3526   int isAgg;             /* True for select lists like "count(*)" */
3527   ExprList *pEList;      /* List of columns to extract. */
3528   SrcList *pTabList;     /* List of tables to select from */
3529   Expr *pWhere;          /* The WHERE clause.  May be NULL */
3530   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
3531   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
3532   Expr *pHaving;         /* The HAVING clause.  May be NULL */
3533   int isDistinct;        /* True if the DISTINCT keyword is present */
3534   int distinct;          /* Table to use for the distinct set */
3535   int rc = 1;            /* Value to return from this function */
3536   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
3537   AggInfo sAggInfo;      /* Information used by aggregate queries */
3538   int iEnd;              /* Address of the end of the query */
3539   sqlite3 *db;           /* The database connection */
3540 
3541   db = pParse->db;
3542   if( p==0 || db->mallocFailed || pParse->nErr ){
3543     return 1;
3544   }
3545   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
3546   memset(&sAggInfo, 0, sizeof(sAggInfo));
3547 
3548   if( IgnorableOrderby(pDest) ){
3549     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
3550            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
3551     /* If ORDER BY makes no difference in the output then neither does
3552     ** DISTINCT so it can be removed too. */
3553     sqlite3ExprListDelete(db, p->pOrderBy);
3554     p->pOrderBy = 0;
3555     p->selFlags &= ~SF_Distinct;
3556   }
3557   sqlite3SelectPrep(pParse, p, 0);
3558   pOrderBy = p->pOrderBy;
3559   pTabList = p->pSrc;
3560   pEList = p->pEList;
3561   if( pParse->nErr || db->mallocFailed ){
3562     goto select_end;
3563   }
3564   isAgg = (p->selFlags & SF_Aggregate)!=0;
3565   assert( pEList!=0 );
3566 
3567   /* Begin generating code.
3568   */
3569   v = sqlite3GetVdbe(pParse);
3570   if( v==0 ) goto select_end;
3571 
3572   /* Generate code for all sub-queries in the FROM clause
3573   */
3574 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3575   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
3576     struct SrcList_item *pItem = &pTabList->a[i];
3577     SelectDest dest;
3578     Select *pSub = pItem->pSelect;
3579     int isAggSub;
3580 
3581     if( pSub==0 || pItem->isPopulated ) continue;
3582 
3583     /* Increment Parse.nHeight by the height of the largest expression
3584     ** tree refered to by this, the parent select. The child select
3585     ** may contain expression trees of at most
3586     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
3587     ** more conservative than necessary, but much easier than enforcing
3588     ** an exact limit.
3589     */
3590     pParse->nHeight += sqlite3SelectExprHeight(p);
3591 
3592     /* Check to see if the subquery can be absorbed into the parent. */
3593     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
3594     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
3595       if( isAggSub ){
3596         isAgg = 1;
3597         p->selFlags |= SF_Aggregate;
3598       }
3599       i = -1;
3600     }else{
3601       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
3602       assert( pItem->isPopulated==0 );
3603       sqlite3Select(pParse, pSub, &dest);
3604       pItem->isPopulated = 1;
3605     }
3606     if( /*pParse->nErr ||*/ db->mallocFailed ){
3607       goto select_end;
3608     }
3609     pParse->nHeight -= sqlite3SelectExprHeight(p);
3610     pTabList = p->pSrc;
3611     if( !IgnorableOrderby(pDest) ){
3612       pOrderBy = p->pOrderBy;
3613     }
3614   }
3615   pEList = p->pEList;
3616 #endif
3617   pWhere = p->pWhere;
3618   pGroupBy = p->pGroupBy;
3619   pHaving = p->pHaving;
3620   isDistinct = (p->selFlags & SF_Distinct)!=0;
3621 
3622 #ifndef SQLITE_OMIT_COMPOUND_SELECT
3623   /* If there is are a sequence of queries, do the earlier ones first.
3624   */
3625   if( p->pPrior ){
3626     if( p->pRightmost==0 ){
3627       Select *pLoop, *pRight = 0;
3628       int cnt = 0;
3629       int mxSelect;
3630       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
3631         pLoop->pRightmost = p;
3632         pLoop->pNext = pRight;
3633         pRight = pLoop;
3634       }
3635       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
3636       if( mxSelect && cnt>mxSelect ){
3637         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
3638         return 1;
3639       }
3640     }
3641     return multiSelect(pParse, p, pDest);
3642   }
3643 #endif
3644 
3645   /* If writing to memory or generating a set
3646   ** only a single column may be output.
3647   */
3648 #ifndef SQLITE_OMIT_SUBQUERY
3649   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
3650     goto select_end;
3651   }
3652 #endif
3653 
3654   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
3655   ** GROUP BY might use an index, DISTINCT never does.
3656   */
3657   assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
3658   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
3659     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
3660     pGroupBy = p->pGroupBy;
3661     p->selFlags &= ~SF_Distinct;
3662     isDistinct = 0;
3663   }
3664 
3665   /* If there is an ORDER BY clause, then this sorting
3666   ** index might end up being unused if the data can be
3667   ** extracted in pre-sorted order.  If that is the case, then the
3668   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
3669   ** we figure out that the sorting index is not needed.  The addrSortIndex
3670   ** variable is used to facilitate that change.
3671   */
3672   if( pOrderBy ){
3673     KeyInfo *pKeyInfo;
3674     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
3675     pOrderBy->iECursor = pParse->nTab++;
3676     p->addrOpenEphm[2] = addrSortIndex =
3677       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
3678                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
3679                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
3680   }else{
3681     addrSortIndex = -1;
3682   }
3683 
3684   /* If the output is destined for a temporary table, open that table.
3685   */
3686   if( pDest->eDest==SRT_EphemTab ){
3687     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
3688   }
3689 
3690   /* Set the limiter.
3691   */
3692   iEnd = sqlite3VdbeMakeLabel(v);
3693   computeLimitRegisters(pParse, p, iEnd);
3694 
3695   /* Open a virtual index to use for the distinct set.
3696   */
3697   if( isDistinct ){
3698     KeyInfo *pKeyInfo;
3699     assert( isAgg || pGroupBy );
3700     distinct = pParse->nTab++;
3701     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
3702     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
3703                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
3704   }else{
3705     distinct = -1;
3706   }
3707 
3708   /* Aggregate and non-aggregate queries are handled differently */
3709   if( !isAgg && pGroupBy==0 ){
3710     /* This case is for non-aggregate queries
3711     ** Begin the database scan
3712     */
3713     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
3714     if( pWInfo==0 ) goto select_end;
3715 
3716     /* If sorting index that was created by a prior OP_OpenEphemeral
3717     ** instruction ended up not being needed, then change the OP_OpenEphemeral
3718     ** into an OP_Noop.
3719     */
3720     if( addrSortIndex>=0 && pOrderBy==0 ){
3721       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
3722       p->addrOpenEphm[2] = -1;
3723     }
3724 
3725     /* Use the standard inner loop
3726     */
3727     assert(!isDistinct);
3728     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
3729                     pWInfo->iContinue, pWInfo->iBreak);
3730 
3731     /* End the database scan loop.
3732     */
3733     sqlite3WhereEnd(pWInfo);
3734   }else{
3735     /* This is the processing for aggregate queries */
3736     NameContext sNC;    /* Name context for processing aggregate information */
3737     int iAMem;          /* First Mem address for storing current GROUP BY */
3738     int iBMem;          /* First Mem address for previous GROUP BY */
3739     int iUseFlag;       /* Mem address holding flag indicating that at least
3740                         ** one row of the input to the aggregator has been
3741                         ** processed */
3742     int iAbortFlag;     /* Mem address which causes query abort if positive */
3743     int groupBySort;    /* Rows come from source in GROUP BY order */
3744     int addrEnd;        /* End of processing for this SELECT */
3745 
3746     /* Remove any and all aliases between the result set and the
3747     ** GROUP BY clause.
3748     */
3749     if( pGroupBy ){
3750       int k;                        /* Loop counter */
3751       struct ExprList_item *pItem;  /* For looping over expression in a list */
3752 
3753       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
3754         pItem->iAlias = 0;
3755       }
3756       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
3757         pItem->iAlias = 0;
3758       }
3759     }
3760 
3761 
3762     /* Create a label to jump to when we want to abort the query */
3763     addrEnd = sqlite3VdbeMakeLabel(v);
3764 
3765     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
3766     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
3767     ** SELECT statement.
3768     */
3769     memset(&sNC, 0, sizeof(sNC));
3770     sNC.pParse = pParse;
3771     sNC.pSrcList = pTabList;
3772     sNC.pAggInfo = &sAggInfo;
3773     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
3774     sAggInfo.pGroupBy = pGroupBy;
3775     sqlite3ExprAnalyzeAggList(&sNC, pEList);
3776     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
3777     if( pHaving ){
3778       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
3779     }
3780     sAggInfo.nAccumulator = sAggInfo.nColumn;
3781     for(i=0; i<sAggInfo.nFunc; i++){
3782       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
3783       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
3784     }
3785     if( db->mallocFailed ) goto select_end;
3786 
3787     /* Processing for aggregates with GROUP BY is very different and
3788     ** much more complex than aggregates without a GROUP BY.
3789     */
3790     if( pGroupBy ){
3791       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
3792       int j1;             /* A-vs-B comparision jump */
3793       int addrOutputRow;  /* Start of subroutine that outputs a result row */
3794       int regOutputRow;   /* Return address register for output subroutine */
3795       int addrSetAbort;   /* Set the abort flag and return */
3796       int addrTopOfLoop;  /* Top of the input loop */
3797       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
3798       int addrReset;      /* Subroutine for resetting the accumulator */
3799       int regReset;       /* Return address register for reset subroutine */
3800 
3801       /* If there is a GROUP BY clause we might need a sorting index to
3802       ** implement it.  Allocate that sorting index now.  If it turns out
3803       ** that we do not need it after all, the OpenEphemeral instruction
3804       ** will be converted into a Noop.
3805       */
3806       sAggInfo.sortingIdx = pParse->nTab++;
3807       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
3808       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
3809           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
3810           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
3811 
3812       /* Initialize memory locations used by GROUP BY aggregate processing
3813       */
3814       iUseFlag = ++pParse->nMem;
3815       iAbortFlag = ++pParse->nMem;
3816       regOutputRow = ++pParse->nMem;
3817       addrOutputRow = sqlite3VdbeMakeLabel(v);
3818       regReset = ++pParse->nMem;
3819       addrReset = sqlite3VdbeMakeLabel(v);
3820       iAMem = pParse->nMem + 1;
3821       pParse->nMem += pGroupBy->nExpr;
3822       iBMem = pParse->nMem + 1;
3823       pParse->nMem += pGroupBy->nExpr;
3824       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
3825       VdbeComment((v, "clear abort flag"));
3826       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
3827       VdbeComment((v, "indicate accumulator empty"));
3828 
3829       /* Begin a loop that will extract all source rows in GROUP BY order.
3830       ** This might involve two separate loops with an OP_Sort in between, or
3831       ** it might be a single loop that uses an index to extract information
3832       ** in the right order to begin with.
3833       */
3834       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
3835       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
3836       if( pWInfo==0 ) goto select_end;
3837       if( pGroupBy==0 ){
3838         /* The optimizer is able to deliver rows in group by order so
3839         ** we do not have to sort.  The OP_OpenEphemeral table will be
3840         ** cancelled later because we still need to use the pKeyInfo
3841         */
3842         pGroupBy = p->pGroupBy;
3843         groupBySort = 0;
3844       }else{
3845         /* Rows are coming out in undetermined order.  We have to push
3846         ** each row into a sorting index, terminate the first loop,
3847         ** then loop over the sorting index in order to get the output
3848         ** in sorted order
3849         */
3850         int regBase;
3851         int regRecord;
3852         int nCol;
3853         int nGroupBy;
3854 
3855         groupBySort = 1;
3856         nGroupBy = pGroupBy->nExpr;
3857         nCol = nGroupBy + 1;
3858         j = nGroupBy+1;
3859         for(i=0; i<sAggInfo.nColumn; i++){
3860           if( sAggInfo.aCol[i].iSorterColumn>=j ){
3861             nCol++;
3862             j++;
3863           }
3864         }
3865         regBase = sqlite3GetTempRange(pParse, nCol);
3866         sqlite3ExprCacheClear(pParse);
3867         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
3868         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
3869         j = nGroupBy+1;
3870         for(i=0; i<sAggInfo.nColumn; i++){
3871           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
3872           if( pCol->iSorterColumn>=j ){
3873             int r1 = j + regBase;
3874             int r2;
3875 
3876             r2 = sqlite3ExprCodeGetColumn(pParse,
3877                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
3878             if( r1!=r2 ){
3879               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
3880             }
3881             j++;
3882           }
3883         }
3884         regRecord = sqlite3GetTempReg(pParse);
3885         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
3886         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
3887         sqlite3ReleaseTempReg(pParse, regRecord);
3888         sqlite3ReleaseTempRange(pParse, regBase, nCol);
3889         sqlite3WhereEnd(pWInfo);
3890         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
3891         VdbeComment((v, "GROUP BY sort"));
3892         sAggInfo.useSortingIdx = 1;
3893         sqlite3ExprCacheClear(pParse);
3894       }
3895 
3896       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
3897       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
3898       ** Then compare the current GROUP BY terms against the GROUP BY terms
3899       ** from the previous row currently stored in a0, a1, a2...
3900       */
3901       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
3902       sqlite3ExprCacheClear(pParse);
3903       for(j=0; j<pGroupBy->nExpr; j++){
3904         if( groupBySort ){
3905           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
3906         }else{
3907           sAggInfo.directMode = 1;
3908           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
3909         }
3910       }
3911       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
3912                           (char*)pKeyInfo, P4_KEYINFO);
3913       j1 = sqlite3VdbeCurrentAddr(v);
3914       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
3915 
3916       /* Generate code that runs whenever the GROUP BY changes.
3917       ** Changes in the GROUP BY are detected by the previous code
3918       ** block.  If there were no changes, this block is skipped.
3919       **
3920       ** This code copies current group by terms in b0,b1,b2,...
3921       ** over to a0,a1,a2.  It then calls the output subroutine
3922       ** and resets the aggregate accumulator registers in preparation
3923       ** for the next GROUP BY batch.
3924       */
3925       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
3926       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
3927       VdbeComment((v, "output one row"));
3928       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
3929       VdbeComment((v, "check abort flag"));
3930       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
3931       VdbeComment((v, "reset accumulator"));
3932 
3933       /* Update the aggregate accumulators based on the content of
3934       ** the current row
3935       */
3936       sqlite3VdbeJumpHere(v, j1);
3937       updateAccumulator(pParse, &sAggInfo);
3938       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
3939       VdbeComment((v, "indicate data in accumulator"));
3940 
3941       /* End of the loop
3942       */
3943       if( groupBySort ){
3944         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
3945       }else{
3946         sqlite3WhereEnd(pWInfo);
3947         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
3948       }
3949 
3950       /* Output the final row of result
3951       */
3952       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
3953       VdbeComment((v, "output final row"));
3954 
3955       /* Jump over the subroutines
3956       */
3957       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
3958 
3959       /* Generate a subroutine that outputs a single row of the result
3960       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
3961       ** is less than or equal to zero, the subroutine is a no-op.  If
3962       ** the processing calls for the query to abort, this subroutine
3963       ** increments the iAbortFlag memory location before returning in
3964       ** order to signal the caller to abort.
3965       */
3966       addrSetAbort = sqlite3VdbeCurrentAddr(v);
3967       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
3968       VdbeComment((v, "set abort flag"));
3969       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
3970       sqlite3VdbeResolveLabel(v, addrOutputRow);
3971       addrOutputRow = sqlite3VdbeCurrentAddr(v);
3972       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
3973       VdbeComment((v, "Groupby result generator entry point"));
3974       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
3975       finalizeAggFunctions(pParse, &sAggInfo);
3976       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
3977       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
3978                       distinct, pDest,
3979                       addrOutputRow+1, addrSetAbort);
3980       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
3981       VdbeComment((v, "end groupby result generator"));
3982 
3983       /* Generate a subroutine that will reset the group-by accumulator
3984       */
3985       sqlite3VdbeResolveLabel(v, addrReset);
3986       resetAccumulator(pParse, &sAggInfo);
3987       sqlite3VdbeAddOp1(v, OP_Return, regReset);
3988 
3989     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
3990     else {
3991       ExprList *pDel = 0;
3992 #ifndef SQLITE_OMIT_BTREECOUNT
3993       Table *pTab;
3994       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
3995         /* If isSimpleCount() returns a pointer to a Table structure, then
3996         ** the SQL statement is of the form:
3997         **
3998         **   SELECT count(*) FROM <tbl>
3999         **
4000         ** where the Table structure returned represents table <tbl>.
4001         **
4002         ** This statement is so common that it is optimized specially. The
4003         ** OP_Count instruction is executed either on the intkey table that
4004         ** contains the data for table <tbl> or on one of its indexes. It
4005         ** is better to execute the op on an index, as indexes are almost
4006         ** always spread across less pages than their corresponding tables.
4007         */
4008         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4009         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
4010         Index *pIdx;                         /* Iterator variable */
4011         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
4012         Index *pBest = 0;                    /* Best index found so far */
4013         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
4014 
4015         sqlite3CodeVerifySchema(pParse, iDb);
4016         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
4017 
4018         /* Search for the index that has the least amount of columns. If
4019         ** there is such an index, and it has less columns than the table
4020         ** does, then we can assume that it consumes less space on disk and
4021         ** will therefore be cheaper to scan to determine the query result.
4022         ** In this case set iRoot to the root page number of the index b-tree
4023         ** and pKeyInfo to the KeyInfo structure required to navigate the
4024         ** index.
4025         **
4026         ** In practice the KeyInfo structure will not be used. It is only
4027         ** passed to keep OP_OpenRead happy.
4028         */
4029         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
4030           if( !pBest || pIdx->nColumn<pBest->nColumn ){
4031             pBest = pIdx;
4032           }
4033         }
4034         if( pBest && pBest->nColumn<pTab->nCol ){
4035           iRoot = pBest->tnum;
4036           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
4037         }
4038 
4039         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
4040         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
4041         if( pKeyInfo ){
4042           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
4043         }
4044         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
4045         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
4046       }else
4047 #endif /* SQLITE_OMIT_BTREECOUNT */
4048       {
4049         /* Check if the query is of one of the following forms:
4050         **
4051         **   SELECT min(x) FROM ...
4052         **   SELECT max(x) FROM ...
4053         **
4054         ** If it is, then ask the code in where.c to attempt to sort results
4055         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
4056         ** If where.c is able to produce results sorted in this order, then
4057         ** add vdbe code to break out of the processing loop after the
4058         ** first iteration (since the first iteration of the loop is
4059         ** guaranteed to operate on the row with the minimum or maximum
4060         ** value of x, the only row required).
4061         **
4062         ** A special flag must be passed to sqlite3WhereBegin() to slightly
4063         ** modify behaviour as follows:
4064         **
4065         **   + If the query is a "SELECT min(x)", then the loop coded by
4066         **     where.c should not iterate over any values with a NULL value
4067         **     for x.
4068         **
4069         **   + The optimizer code in where.c (the thing that decides which
4070         **     index or indices to use) should place a different priority on
4071         **     satisfying the 'ORDER BY' clause than it does in other cases.
4072         **     Refer to code and comments in where.c for details.
4073         */
4074         ExprList *pMinMax = 0;
4075         u8 flag = minMaxQuery(p);
4076         if( flag ){
4077           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
4078           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
4079           pDel = pMinMax;
4080           if( pMinMax && !db->mallocFailed ){
4081             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
4082             pMinMax->a[0].pExpr->op = TK_COLUMN;
4083           }
4084         }
4085 
4086         /* This case runs if the aggregate has no GROUP BY clause.  The
4087         ** processing is much simpler since there is only a single row
4088         ** of output.
4089         */
4090         resetAccumulator(pParse, &sAggInfo);
4091         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
4092         if( pWInfo==0 ){
4093           sqlite3ExprListDelete(db, pDel);
4094           goto select_end;
4095         }
4096         updateAccumulator(pParse, &sAggInfo);
4097         if( !pMinMax && flag ){
4098           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
4099           VdbeComment((v, "%s() by index",
4100                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
4101         }
4102         sqlite3WhereEnd(pWInfo);
4103         finalizeAggFunctions(pParse, &sAggInfo);
4104       }
4105 
4106       pOrderBy = 0;
4107       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
4108       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
4109                       pDest, addrEnd, addrEnd);
4110       sqlite3ExprListDelete(db, pDel);
4111     }
4112     sqlite3VdbeResolveLabel(v, addrEnd);
4113 
4114   } /* endif aggregate query */
4115 
4116   /* If there is an ORDER BY clause, then we need to sort the results
4117   ** and send them to the callback one by one.
4118   */
4119   if( pOrderBy ){
4120     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
4121   }
4122 
4123   /* Jump here to skip this query
4124   */
4125   sqlite3VdbeResolveLabel(v, iEnd);
4126 
4127   /* The SELECT was successfully coded.   Set the return code to 0
4128   ** to indicate no errors.
4129   */
4130   rc = 0;
4131 
4132   /* Control jumps to here if an error is encountered above, or upon
4133   ** successful coding of the SELECT.
4134   */
4135 select_end:
4136 
4137   /* Identify column names if results of the SELECT are to be output.
4138   */
4139   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
4140     generateColumnNames(pParse, pTabList, pEList);
4141   }
4142 
4143   sqlite3DbFree(db, sAggInfo.aCol);
4144   sqlite3DbFree(db, sAggInfo.aFunc);
4145   return rc;
4146 }
4147 
4148 #if defined(SQLITE_DEBUG)
4149 /*
4150 *******************************************************************************
4151 ** The following code is used for testing and debugging only.  The code
4152 ** that follows does not appear in normal builds.
4153 **
4154 ** These routines are used to print out the content of all or part of a
4155 ** parse structures such as Select or Expr.  Such printouts are useful
4156 ** for helping to understand what is happening inside the code generator
4157 ** during the execution of complex SELECT statements.
4158 **
4159 ** These routine are not called anywhere from within the normal
4160 ** code base.  Then are intended to be called from within the debugger
4161 ** or from temporary "printf" statements inserted for debugging.
4162 */
4163 void sqlite3PrintExpr(Expr *p){
4164   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
4165     sqlite3DebugPrintf("(%s", p->u.zToken);
4166   }else{
4167     sqlite3DebugPrintf("(%d", p->op);
4168   }
4169   if( p->pLeft ){
4170     sqlite3DebugPrintf(" ");
4171     sqlite3PrintExpr(p->pLeft);
4172   }
4173   if( p->pRight ){
4174     sqlite3DebugPrintf(" ");
4175     sqlite3PrintExpr(p->pRight);
4176   }
4177   sqlite3DebugPrintf(")");
4178 }
4179 void sqlite3PrintExprList(ExprList *pList){
4180   int i;
4181   for(i=0; i<pList->nExpr; i++){
4182     sqlite3PrintExpr(pList->a[i].pExpr);
4183     if( i<pList->nExpr-1 ){
4184       sqlite3DebugPrintf(", ");
4185     }
4186   }
4187 }
4188 void sqlite3PrintSelect(Select *p, int indent){
4189   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
4190   sqlite3PrintExprList(p->pEList);
4191   sqlite3DebugPrintf("\n");
4192   if( p->pSrc ){
4193     char *zPrefix;
4194     int i;
4195     zPrefix = "FROM";
4196     for(i=0; i<p->pSrc->nSrc; i++){
4197       struct SrcList_item *pItem = &p->pSrc->a[i];
4198       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
4199       zPrefix = "";
4200       if( pItem->pSelect ){
4201         sqlite3DebugPrintf("(\n");
4202         sqlite3PrintSelect(pItem->pSelect, indent+10);
4203         sqlite3DebugPrintf("%*s)", indent+8, "");
4204       }else if( pItem->zName ){
4205         sqlite3DebugPrintf("%s", pItem->zName);
4206       }
4207       if( pItem->pTab ){
4208         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
4209       }
4210       if( pItem->zAlias ){
4211         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
4212       }
4213       if( i<p->pSrc->nSrc-1 ){
4214         sqlite3DebugPrintf(",");
4215       }
4216       sqlite3DebugPrintf("\n");
4217     }
4218   }
4219   if( p->pWhere ){
4220     sqlite3DebugPrintf("%*s WHERE ", indent, "");
4221     sqlite3PrintExpr(p->pWhere);
4222     sqlite3DebugPrintf("\n");
4223   }
4224   if( p->pGroupBy ){
4225     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
4226     sqlite3PrintExprList(p->pGroupBy);
4227     sqlite3DebugPrintf("\n");
4228   }
4229   if( p->pHaving ){
4230     sqlite3DebugPrintf("%*s HAVING ", indent, "");
4231     sqlite3PrintExpr(p->pHaving);
4232     sqlite3DebugPrintf("\n");
4233   }
4234   if( p->pOrderBy ){
4235     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
4236     sqlite3PrintExprList(p->pOrderBy);
4237     sqlite3DebugPrintf("\n");
4238   }
4239 }
4240 /* End of the structure debug printing code
4241 *****************************************************************************/
4242 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
4243