xref: /sqlite-3.40.0/src/select.c (revision 962f9669)
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 #include "sqliteInt.h"
16 
17 
18 /*
19 ** Delete all the content of a Select structure but do not deallocate
20 ** the select structure itself.
21 */
22 static void clearSelect(sqlite3 *db, Select *p){
23   sqlite3ExprListDelete(db, p->pEList);
24   sqlite3SrcListDelete(db, p->pSrc);
25   sqlite3ExprDelete(db, p->pWhere);
26   sqlite3ExprListDelete(db, p->pGroupBy);
27   sqlite3ExprDelete(db, p->pHaving);
28   sqlite3ExprListDelete(db, p->pOrderBy);
29   sqlite3SelectDelete(db, p->pPrior);
30   sqlite3ExprDelete(db, p->pLimit);
31   sqlite3ExprDelete(db, p->pOffset);
32   sqlite3WithDelete(db, p->pWith);
33 }
34 
35 /*
36 ** Initialize a SelectDest structure.
37 */
38 void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
39   pDest->eDest = (u8)eDest;
40   pDest->iSDParm = iParm;
41   pDest->affSdst = 0;
42   pDest->iSdst = 0;
43   pDest->nSdst = 0;
44 }
45 
46 
47 /*
48 ** Allocate a new Select structure and return a pointer to that
49 ** structure.
50 */
51 Select *sqlite3SelectNew(
52   Parse *pParse,        /* Parsing context */
53   ExprList *pEList,     /* which columns to include in the result */
54   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
55   Expr *pWhere,         /* the WHERE clause */
56   ExprList *pGroupBy,   /* the GROUP BY clause */
57   Expr *pHaving,        /* the HAVING clause */
58   ExprList *pOrderBy,   /* the ORDER BY clause */
59   u16 selFlags,         /* Flag parameters, such as SF_Distinct */
60   Expr *pLimit,         /* LIMIT value.  NULL means not used */
61   Expr *pOffset         /* OFFSET value.  NULL means no offset */
62 ){
63   Select *pNew;
64   Select standin;
65   sqlite3 *db = pParse->db;
66   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
67   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
68   if( pNew==0 ){
69     assert( db->mallocFailed );
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   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
78   pNew->pSrc = pSrc;
79   pNew->pWhere = pWhere;
80   pNew->pGroupBy = pGroupBy;
81   pNew->pHaving = pHaving;
82   pNew->pOrderBy = pOrderBy;
83   pNew->selFlags = selFlags;
84   pNew->op = TK_SELECT;
85   pNew->pLimit = pLimit;
86   pNew->pOffset = pOffset;
87   assert( pOffset==0 || pLimit!=0 );
88   pNew->addrOpenEphm[0] = -1;
89   pNew->addrOpenEphm[1] = -1;
90   pNew->addrOpenEphm[2] = -1;
91   if( db->mallocFailed ) {
92     clearSelect(db, pNew);
93     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
94     pNew = 0;
95   }else{
96     assert( pNew->pSrc!=0 || pParse->nErr>0 );
97   }
98   assert( pNew!=&standin );
99   return pNew;
100 }
101 
102 /*
103 ** Delete the given Select structure and all of its substructures.
104 */
105 void sqlite3SelectDelete(sqlite3 *db, Select *p){
106   if( p ){
107     clearSelect(db, p);
108     sqlite3DbFree(db, p);
109   }
110 }
111 
112 /*
113 ** Return a pointer to the right-most SELECT statement in a compound.
114 */
115 static Select *findRightmost(Select *p){
116   while( p->pNext ) p = p->pNext;
117   return p;
118 }
119 
120 /*
121 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
122 ** type of join.  Return an integer constant that expresses that type
123 ** in terms of the following bit values:
124 **
125 **     JT_INNER
126 **     JT_CROSS
127 **     JT_OUTER
128 **     JT_NATURAL
129 **     JT_LEFT
130 **     JT_RIGHT
131 **
132 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
133 **
134 ** If an illegal or unsupported join type is seen, then still return
135 ** a join type, but put an error in the pParse structure.
136 */
137 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
138   int jointype = 0;
139   Token *apAll[3];
140   Token *p;
141                              /*   0123456789 123456789 123456789 123 */
142   static const char zKeyText[] = "naturaleftouterightfullinnercross";
143   static const struct {
144     u8 i;        /* Beginning of keyword text in zKeyText[] */
145     u8 nChar;    /* Length of the keyword in characters */
146     u8 code;     /* Join type mask */
147   } aKeyword[] = {
148     /* natural */ { 0,  7, JT_NATURAL                },
149     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
150     /* outer   */ { 10, 5, JT_OUTER                  },
151     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
152     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
153     /* inner   */ { 23, 5, JT_INNER                  },
154     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
155   };
156   int i, j;
157   apAll[0] = pA;
158   apAll[1] = pB;
159   apAll[2] = pC;
160   for(i=0; i<3 && apAll[i]; i++){
161     p = apAll[i];
162     for(j=0; j<ArraySize(aKeyword); j++){
163       if( p->n==aKeyword[j].nChar
164           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
165         jointype |= aKeyword[j].code;
166         break;
167       }
168     }
169     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
170     if( j>=ArraySize(aKeyword) ){
171       jointype |= JT_ERROR;
172       break;
173     }
174   }
175   if(
176      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
177      (jointype & JT_ERROR)!=0
178   ){
179     const char *zSp = " ";
180     assert( pB!=0 );
181     if( pC==0 ){ zSp++; }
182     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
183        "%T %T%s%T", pA, pB, zSp, pC);
184     jointype = JT_INNER;
185   }else if( (jointype & JT_OUTER)!=0
186          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
187     sqlite3ErrorMsg(pParse,
188       "RIGHT and FULL OUTER JOINs are not currently supported");
189     jointype = JT_INNER;
190   }
191   return jointype;
192 }
193 
194 /*
195 ** Return the index of a column in a table.  Return -1 if the column
196 ** is not contained in the table.
197 */
198 static int columnIndex(Table *pTab, const char *zCol){
199   int i;
200   for(i=0; i<pTab->nCol; i++){
201     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
202   }
203   return -1;
204 }
205 
206 /*
207 ** Search the first N tables in pSrc, from left to right, looking for a
208 ** table that has a column named zCol.
209 **
210 ** When found, set *piTab and *piCol to the table index and column index
211 ** of the matching column and return TRUE.
212 **
213 ** If not found, return FALSE.
214 */
215 static int tableAndColumnIndex(
216   SrcList *pSrc,       /* Array of tables to search */
217   int N,               /* Number of tables in pSrc->a[] to search */
218   const char *zCol,    /* Name of the column we are looking for */
219   int *piTab,          /* Write index of pSrc->a[] here */
220   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
221 ){
222   int i;               /* For looping over tables in pSrc */
223   int iCol;            /* Index of column matching zCol */
224 
225   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
226   for(i=0; i<N; i++){
227     iCol = columnIndex(pSrc->a[i].pTab, zCol);
228     if( iCol>=0 ){
229       if( piTab ){
230         *piTab = i;
231         *piCol = iCol;
232       }
233       return 1;
234     }
235   }
236   return 0;
237 }
238 
239 /*
240 ** This function is used to add terms implied by JOIN syntax to the
241 ** WHERE clause expression of a SELECT statement. The new term, which
242 ** is ANDed with the existing WHERE clause, is of the form:
243 **
244 **    (tab1.col1 = tab2.col2)
245 **
246 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
247 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
248 ** column iColRight of tab2.
249 */
250 static void addWhereTerm(
251   Parse *pParse,                  /* Parsing context */
252   SrcList *pSrc,                  /* List of tables in FROM clause */
253   int iLeft,                      /* Index of first table to join in pSrc */
254   int iColLeft,                   /* Index of column in first table */
255   int iRight,                     /* Index of second table in pSrc */
256   int iColRight,                  /* Index of column in second table */
257   int isOuterJoin,                /* True if this is an OUTER join */
258   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
259 ){
260   sqlite3 *db = pParse->db;
261   Expr *pE1;
262   Expr *pE2;
263   Expr *pEq;
264 
265   assert( iLeft<iRight );
266   assert( pSrc->nSrc>iRight );
267   assert( pSrc->a[iLeft].pTab );
268   assert( pSrc->a[iRight].pTab );
269 
270   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
271   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
272 
273   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
274   if( pEq && isOuterJoin ){
275     ExprSetProperty(pEq, EP_FromJoin);
276     assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
277     ExprSetVVAProperty(pEq, EP_NoReduce);
278     pEq->iRightJoinTable = (i16)pE2->iTable;
279   }
280   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
281 }
282 
283 /*
284 ** Set the EP_FromJoin property on all terms of the given expression.
285 ** And set the Expr.iRightJoinTable to iTable for every term in the
286 ** expression.
287 **
288 ** The EP_FromJoin property is used on terms of an expression to tell
289 ** the LEFT OUTER JOIN processing logic that this term is part of the
290 ** join restriction specified in the ON or USING clause and not a part
291 ** of the more general WHERE clause.  These terms are moved over to the
292 ** WHERE clause during join processing but we need to remember that they
293 ** originated in the ON or USING clause.
294 **
295 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
296 ** expression depends on table iRightJoinTable even if that table is not
297 ** explicitly mentioned in the expression.  That information is needed
298 ** for cases like this:
299 **
300 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
301 **
302 ** The where clause needs to defer the handling of the t1.x=5
303 ** term until after the t2 loop of the join.  In that way, a
304 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
305 ** defer the handling of t1.x=5, it will be processed immediately
306 ** after the t1 loop and rows with t1.x!=5 will never appear in
307 ** the output, which is incorrect.
308 */
309 static void setJoinExpr(Expr *p, int iTable){
310   while( p ){
311     ExprSetProperty(p, EP_FromJoin);
312     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
313     ExprSetVVAProperty(p, EP_NoReduce);
314     p->iRightJoinTable = (i16)iTable;
315     setJoinExpr(p->pLeft, iTable);
316     p = p->pRight;
317   }
318 }
319 
320 /*
321 ** This routine processes the join information for a SELECT statement.
322 ** ON and USING clauses are converted into extra terms of the WHERE clause.
323 ** NATURAL joins also create extra WHERE clause terms.
324 **
325 ** The terms of a FROM clause are contained in the Select.pSrc structure.
326 ** The left most table is the first entry in Select.pSrc.  The right-most
327 ** table is the last entry.  The join operator is held in the entry to
328 ** the left.  Thus entry 0 contains the join operator for the join between
329 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
330 ** also attached to the left entry.
331 **
332 ** This routine returns the number of errors encountered.
333 */
334 static int sqliteProcessJoin(Parse *pParse, Select *p){
335   SrcList *pSrc;                  /* All tables in the FROM clause */
336   int i, j;                       /* Loop counters */
337   struct SrcList_item *pLeft;     /* Left table being joined */
338   struct SrcList_item *pRight;    /* Right table being joined */
339 
340   pSrc = p->pSrc;
341   pLeft = &pSrc->a[0];
342   pRight = &pLeft[1];
343   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
344     Table *pLeftTab = pLeft->pTab;
345     Table *pRightTab = pRight->pTab;
346     int isOuter;
347 
348     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
349     isOuter = (pRight->jointype & JT_OUTER)!=0;
350 
351     /* When the NATURAL keyword is present, add WHERE clause terms for
352     ** every column that the two tables have in common.
353     */
354     if( pRight->jointype & JT_NATURAL ){
355       if( pRight->pOn || pRight->pUsing ){
356         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
357            "an ON or USING clause", 0);
358         return 1;
359       }
360       for(j=0; j<pRightTab->nCol; j++){
361         char *zName;   /* Name of column in the right table */
362         int iLeft;     /* Matching left table */
363         int iLeftCol;  /* Matching column in the left table */
364 
365         zName = pRightTab->aCol[j].zName;
366         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
367           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
368                        isOuter, &p->pWhere);
369         }
370       }
371     }
372 
373     /* Disallow both ON and USING clauses in the same join
374     */
375     if( pRight->pOn && pRight->pUsing ){
376       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
377         "clauses in the same join");
378       return 1;
379     }
380 
381     /* Add the ON clause to the end of the WHERE clause, connected by
382     ** an AND operator.
383     */
384     if( pRight->pOn ){
385       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
386       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
387       pRight->pOn = 0;
388     }
389 
390     /* Create extra terms on the WHERE clause for each column named
391     ** in the USING clause.  Example: If the two tables to be joined are
392     ** A and B and the USING clause names X, Y, and Z, then add this
393     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
394     ** Report an error if any column mentioned in the USING clause is
395     ** not contained in both tables to be joined.
396     */
397     if( pRight->pUsing ){
398       IdList *pList = pRight->pUsing;
399       for(j=0; j<pList->nId; j++){
400         char *zName;     /* Name of the term in the USING clause */
401         int iLeft;       /* Table on the left with matching column name */
402         int iLeftCol;    /* Column number of matching column on the left */
403         int iRightCol;   /* Column number of matching column on the right */
404 
405         zName = pList->a[j].zName;
406         iRightCol = columnIndex(pRightTab, zName);
407         if( iRightCol<0
408          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
409         ){
410           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
411             "not present in both tables", zName);
412           return 1;
413         }
414         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
415                      isOuter, &p->pWhere);
416       }
417     }
418   }
419   return 0;
420 }
421 
422 /*
423 ** Insert code into "v" that will push the record on the top of the
424 ** stack into the sorter.
425 */
426 static void pushOntoSorter(
427   Parse *pParse,         /* Parser context */
428   ExprList *pOrderBy,    /* The ORDER BY clause */
429   Select *pSelect,       /* The whole SELECT statement */
430   int regData            /* Register holding data to be sorted */
431 ){
432   Vdbe *v = pParse->pVdbe;
433   int nExpr = pOrderBy->nExpr;
434   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
435   int regRecord = sqlite3GetTempReg(pParse);
436   int op;
437   sqlite3ExprCacheClear(pParse);
438   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
439   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
440   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
441   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
442   if( pSelect->selFlags & SF_UseSorter ){
443     op = OP_SorterInsert;
444   }else{
445     op = OP_IdxInsert;
446   }
447   sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
448   sqlite3ReleaseTempReg(pParse, regRecord);
449   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
450   if( pSelect->iLimit ){
451     int addr1, addr2;
452     int iLimit;
453     if( pSelect->iOffset ){
454       iLimit = pSelect->iOffset+1;
455     }else{
456       iLimit = pSelect->iLimit;
457     }
458     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
459     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
460     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
461     sqlite3VdbeJumpHere(v, addr1);
462     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
463     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
464     sqlite3VdbeJumpHere(v, addr2);
465   }
466 }
467 
468 /*
469 ** Add code to implement the OFFSET
470 */
471 static void codeOffset(
472   Vdbe *v,          /* Generate code into this VM */
473   int iOffset,      /* Register holding the offset counter */
474   int iContinue     /* Jump here to skip the current record */
475 ){
476   if( iOffset>0 && iContinue!=0 ){
477     int addr;
478     sqlite3VdbeAddOp2(v, OP_AddImm, iOffset, -1);
479     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, iOffset);
480     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
481     VdbeComment((v, "skip OFFSET records"));
482     sqlite3VdbeJumpHere(v, addr);
483   }
484 }
485 
486 /*
487 ** Add code that will check to make sure the N registers starting at iMem
488 ** form a distinct entry.  iTab is a sorting index that holds previously
489 ** seen combinations of the N values.  A new entry is made in iTab
490 ** if the current N values are new.
491 **
492 ** A jump to addrRepeat is made and the N+1 values are popped from the
493 ** stack if the top N elements are not distinct.
494 */
495 static void codeDistinct(
496   Parse *pParse,     /* Parsing and code generating context */
497   int iTab,          /* A sorting index used to test for distinctness */
498   int addrRepeat,    /* Jump to here if not distinct */
499   int N,             /* Number of elements */
500   int iMem           /* First element */
501 ){
502   Vdbe *v;
503   int r1;
504 
505   v = pParse->pVdbe;
506   r1 = sqlite3GetTempReg(pParse);
507   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
508   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
509   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
510   sqlite3ReleaseTempReg(pParse, r1);
511 }
512 
513 #ifndef SQLITE_OMIT_SUBQUERY
514 /*
515 ** Generate an error message when a SELECT is used within a subexpression
516 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
517 ** column.  We do this in a subroutine because the error used to occur
518 ** in multiple places.  (The error only occurs in one place now, but we
519 ** retain the subroutine to minimize code disruption.)
520 */
521 static int checkForMultiColumnSelectError(
522   Parse *pParse,       /* Parse context. */
523   SelectDest *pDest,   /* Destination of SELECT results */
524   int nExpr            /* Number of result columns returned by SELECT */
525 ){
526   int eDest = pDest->eDest;
527   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
528     sqlite3ErrorMsg(pParse, "only a single result allowed for "
529        "a SELECT that is part of an expression");
530     return 1;
531   }else{
532     return 0;
533   }
534 }
535 #endif
536 
537 /*
538 ** An instance of the following object is used to record information about
539 ** how to process the DISTINCT keyword, to simplify passing that information
540 ** into the selectInnerLoop() routine.
541 */
542 typedef struct DistinctCtx DistinctCtx;
543 struct DistinctCtx {
544   u8 isTnct;      /* True if the DISTINCT keyword is present */
545   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
546   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
547   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
548 };
549 
550 /*
551 ** This routine generates the code for the inside of the inner loop
552 ** of a SELECT.
553 **
554 ** If srcTab is negative, then the pEList expressions
555 ** are evaluated in order to get the data for this row.  If srcTab is
556 ** zero or more, then data is pulled from srcTab and pEList is used only
557 ** to get number columns and the datatype for each column.
558 */
559 static void selectInnerLoop(
560   Parse *pParse,          /* The parser context */
561   Select *p,              /* The complete select statement being coded */
562   ExprList *pEList,       /* List of values being extracted */
563   int srcTab,             /* Pull data from this table */
564   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
565   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
566   SelectDest *pDest,      /* How to dispose of the results */
567   int iContinue,          /* Jump here to continue with next row */
568   int iBreak              /* Jump here to break out of the inner loop */
569 ){
570   Vdbe *v = pParse->pVdbe;
571   int i;
572   int hasDistinct;        /* True if the DISTINCT keyword is present */
573   int regResult;              /* Start of memory holding result set */
574   int eDest = pDest->eDest;   /* How to dispose of results */
575   int iParm = pDest->iSDParm; /* First argument to disposal method */
576   int nResultCol;             /* Number of result columns */
577 
578   assert( v );
579   assert( pEList!=0 );
580   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
581   if( pOrderBy==0 && !hasDistinct ){
582     codeOffset(v, p->iOffset, iContinue);
583   }
584 
585   /* Pull the requested columns.
586   */
587   nResultCol = pEList->nExpr;
588   if( pDest->iSdst==0 ){
589     pDest->iSdst = pParse->nMem+1;
590     pDest->nSdst = nResultCol;
591     pParse->nMem += nResultCol;
592   }else{
593     assert( pDest->nSdst==nResultCol );
594   }
595   regResult = pDest->iSdst;
596   if( srcTab>=0 ){
597     for(i=0; i<nResultCol; i++){
598       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
599       VdbeComment((v, "%s", pEList->a[i].zName));
600     }
601   }else if( eDest!=SRT_Exists ){
602     /* If the destination is an EXISTS(...) expression, the actual
603     ** values returned by the SELECT are not required.
604     */
605     sqlite3ExprCodeExprList(pParse, pEList, regResult,
606                             (eDest==SRT_Output)?SQLITE_ECEL_DUP:0);
607   }
608 
609   /* If the DISTINCT keyword was present on the SELECT statement
610   ** and this row has been seen before, then do not make this row
611   ** part of the result.
612   */
613   if( hasDistinct ){
614     switch( pDistinct->eTnctType ){
615       case WHERE_DISTINCT_ORDERED: {
616         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
617         int iJump;              /* Jump destination */
618         int regPrev;            /* Previous row content */
619 
620         /* Allocate space for the previous row */
621         regPrev = pParse->nMem+1;
622         pParse->nMem += nResultCol;
623 
624         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
625         ** sets the MEM_Cleared bit on the first register of the
626         ** previous value.  This will cause the OP_Ne below to always
627         ** fail on the first iteration of the loop even if the first
628         ** row is all NULLs.
629         */
630         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
631         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
632         pOp->opcode = OP_Null;
633         pOp->p1 = 1;
634         pOp->p2 = regPrev;
635 
636         iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
637         for(i=0; i<nResultCol; i++){
638           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
639           if( i<nResultCol-1 ){
640             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
641           }else{
642             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
643           }
644           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
645           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
646         }
647         assert( sqlite3VdbeCurrentAddr(v)==iJump );
648         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
649         break;
650       }
651 
652       case WHERE_DISTINCT_UNIQUE: {
653         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
654         break;
655       }
656 
657       default: {
658         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
659         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult);
660         break;
661       }
662     }
663     if( pOrderBy==0 ){
664       codeOffset(v, p->iOffset, iContinue);
665     }
666   }
667 
668   switch( eDest ){
669     /* In this mode, write each query result to the key of the temporary
670     ** table iParm.
671     */
672 #ifndef SQLITE_OMIT_COMPOUND_SELECT
673     case SRT_Union: {
674       int r1;
675       r1 = sqlite3GetTempReg(pParse);
676       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
677       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
678       sqlite3ReleaseTempReg(pParse, r1);
679       break;
680     }
681 
682     /* Construct a record from the query result, but instead of
683     ** saving that record, use it as a key to delete elements from
684     ** the temporary table iParm.
685     */
686     case SRT_Except: {
687       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
688       break;
689     }
690 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
691 
692     /* Store the result as data using a unique key.
693     */
694     case SRT_DistTable:
695     case SRT_Table:
696     case SRT_EphemTab: {
697       int r1 = sqlite3GetTempReg(pParse);
698       testcase( eDest==SRT_Table );
699       testcase( eDest==SRT_EphemTab );
700       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
701 #ifndef SQLITE_OMIT_CTE
702       if( eDest==SRT_DistTable ){
703         /* If the destination is DistTable, then cursor (iParm+1) is open
704         ** on an ephemeral index. If the current row is already present
705         ** in the index, do not write it to the output. If not, add the
706         ** current row to the index and proceed with writing it to the
707         ** output table as well.  */
708         int addr = sqlite3VdbeCurrentAddr(v) + 4;
709         sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
710         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
711         assert( pOrderBy==0 );
712       }
713 #endif
714       if( pOrderBy ){
715         pushOntoSorter(pParse, pOrderBy, p, r1);
716       }else{
717         int r2 = sqlite3GetTempReg(pParse);
718         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
719         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
720         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
721         sqlite3ReleaseTempReg(pParse, r2);
722       }
723       sqlite3ReleaseTempReg(pParse, r1);
724       break;
725     }
726 
727 #ifndef SQLITE_OMIT_SUBQUERY
728     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
729     ** then there should be a single item on the stack.  Write this
730     ** item into the set table with bogus data.
731     */
732     case SRT_Set: {
733       assert( nResultCol==1 );
734       pDest->affSdst =
735                   sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
736       if( pOrderBy ){
737         /* At first glance you would think we could optimize out the
738         ** ORDER BY in this case since the order of entries in the set
739         ** does not matter.  But there might be a LIMIT clause, in which
740         ** case the order does matter */
741         pushOntoSorter(pParse, pOrderBy, p, regResult);
742       }else{
743         int r1 = sqlite3GetTempReg(pParse);
744         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
745         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
746         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
747         sqlite3ReleaseTempReg(pParse, r1);
748       }
749       break;
750     }
751 
752     /* If any row exist in the result set, record that fact and abort.
753     */
754     case SRT_Exists: {
755       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
756       /* The LIMIT clause will terminate the loop for us */
757       break;
758     }
759 
760     /* If this is a scalar select that is part of an expression, then
761     ** store the results in the appropriate memory cell and break out
762     ** of the scan loop.
763     */
764     case SRT_Mem: {
765       assert( nResultCol==1 );
766       if( pOrderBy ){
767         pushOntoSorter(pParse, pOrderBy, p, regResult);
768       }else{
769         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
770         /* The LIMIT clause will jump out of the loop for us */
771       }
772       break;
773     }
774 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
775 
776     case SRT_Coroutine:       /* Send data to a co-routine */
777     case SRT_Output: {        /* Return the results */
778       testcase( eDest==SRT_Coroutine );
779       testcase( eDest==SRT_Output );
780       if( pOrderBy ){
781         int r1 = sqlite3GetTempReg(pParse);
782         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
783         pushOntoSorter(pParse, pOrderBy, p, r1);
784         sqlite3ReleaseTempReg(pParse, r1);
785       }else if( eDest==SRT_Coroutine ){
786         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
787       }else{
788         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
789         sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
790       }
791       break;
792     }
793 
794 #ifndef SQLITE_OMIT_CTE
795     /* Write the results into a priority queue that is order according to
796     ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
797     ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
798     ** pSO->nExpr columns, then make sure all keys are unique by adding a
799     ** final OP_Sequence column.  The last column is the record as a blob.
800     */
801     case SRT_DistQueue:
802     case SRT_Queue: {
803       int nKey;
804       int r1, r2, r3;
805       int addrTest = 0;
806       ExprList *pSO;
807       pSO = pDest->pOrderBy;
808       assert( pSO );
809       nKey = pSO->nExpr;
810       r1 = sqlite3GetTempReg(pParse);
811       r2 = sqlite3GetTempRange(pParse, nKey+2);
812       r3 = r2+nKey+1;
813       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
814       if( eDest==SRT_DistQueue ){
815         /* If the destination is DistQueue, then cursor (iParm+1) is open
816         ** on a second ephemeral index that holds all values every previously
817         ** added to the queue.  Only add this new value if it has never before
818         ** been added */
819         addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, r3, 0);
820         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
821         sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
822       }
823       for(i=0; i<nKey; i++){
824         sqlite3VdbeAddOp2(v, OP_SCopy,
825                           regResult + pSO->a[i].u.x.iOrderByCol - 1,
826                           r2+i);
827       }
828       sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
829       sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
830       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
831       if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
832       sqlite3ReleaseTempReg(pParse, r1);
833       sqlite3ReleaseTempRange(pParse, r2, nKey+2);
834       break;
835     }
836 #endif /* SQLITE_OMIT_CTE */
837 
838 
839 
840 #if !defined(SQLITE_OMIT_TRIGGER)
841     /* Discard the results.  This is used for SELECT statements inside
842     ** the body of a TRIGGER.  The purpose of such selects is to call
843     ** user-defined functions that have side effects.  We do not care
844     ** about the actual results of the select.
845     */
846     default: {
847       assert( eDest==SRT_Discard );
848       break;
849     }
850 #endif
851   }
852 
853   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
854   ** there is a sorter, in which case the sorter has already limited
855   ** the output for us.
856   */
857   if( pOrderBy==0 && p->iLimit ){
858     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
859   }
860 }
861 
862 /*
863 ** Allocate a KeyInfo object sufficient for an index of N key columns and
864 ** X extra columns.
865 */
866 KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
867   KeyInfo *p = sqlite3DbMallocZero(0,
868                    sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
869   if( p ){
870     p->aSortOrder = (u8*)&p->aColl[N+X];
871     p->nField = (u16)N;
872     p->nXField = (u16)X;
873     p->enc = ENC(db);
874     p->db = db;
875     p->nRef = 1;
876   }else{
877     db->mallocFailed = 1;
878   }
879   return p;
880 }
881 
882 /*
883 ** Deallocate a KeyInfo object
884 */
885 void sqlite3KeyInfoUnref(KeyInfo *p){
886   if( p ){
887     assert( p->nRef>0 );
888     p->nRef--;
889     if( p->nRef==0 ) sqlite3DbFree(0, p);
890   }
891 }
892 
893 /*
894 ** Make a new pointer to a KeyInfo object
895 */
896 KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
897   if( p ){
898     assert( p->nRef>0 );
899     p->nRef++;
900   }
901   return p;
902 }
903 
904 #ifdef SQLITE_DEBUG
905 /*
906 ** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
907 ** can only be changed if this is just a single reference to the object.
908 **
909 ** This routine is used only inside of assert() statements.
910 */
911 int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
912 #endif /* SQLITE_DEBUG */
913 
914 /*
915 ** Given an expression list, generate a KeyInfo structure that records
916 ** the collating sequence for each expression in that expression list.
917 **
918 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
919 ** KeyInfo structure is appropriate for initializing a virtual index to
920 ** implement that clause.  If the ExprList is the result set of a SELECT
921 ** then the KeyInfo structure is appropriate for initializing a virtual
922 ** index to implement a DISTINCT test.
923 **
924 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
925 ** function is responsible for seeing that this structure is eventually
926 ** freed.
927 */
928 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList, int nExtra){
929   int nExpr;
930   KeyInfo *pInfo;
931   struct ExprList_item *pItem;
932   sqlite3 *db = pParse->db;
933   int i;
934 
935   nExpr = pList->nExpr;
936   pInfo = sqlite3KeyInfoAlloc(db, nExpr+nExtra, 1);
937   if( pInfo ){
938     assert( sqlite3KeyInfoIsWriteable(pInfo) );
939     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
940       CollSeq *pColl;
941       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
942       if( !pColl ) pColl = db->pDfltColl;
943       pInfo->aColl[i] = pColl;
944       pInfo->aSortOrder[i] = pItem->sortOrder;
945     }
946   }
947   return pInfo;
948 }
949 
950 #ifndef SQLITE_OMIT_COMPOUND_SELECT
951 /*
952 ** Name of the connection operator, used for error messages.
953 */
954 static const char *selectOpName(int id){
955   char *z;
956   switch( id ){
957     case TK_ALL:       z = "UNION ALL";   break;
958     case TK_INTERSECT: z = "INTERSECT";   break;
959     case TK_EXCEPT:    z = "EXCEPT";      break;
960     default:           z = "UNION";       break;
961   }
962   return z;
963 }
964 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
965 
966 #ifndef SQLITE_OMIT_EXPLAIN
967 /*
968 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
969 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
970 ** where the caption is of the form:
971 **
972 **   "USE TEMP B-TREE FOR xxx"
973 **
974 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
975 ** is determined by the zUsage argument.
976 */
977 static void explainTempTable(Parse *pParse, const char *zUsage){
978   if( pParse->explain==2 ){
979     Vdbe *v = pParse->pVdbe;
980     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
981     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
982   }
983 }
984 
985 /*
986 ** Assign expression b to lvalue a. A second, no-op, version of this macro
987 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
988 ** in sqlite3Select() to assign values to structure member variables that
989 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
990 ** code with #ifndef directives.
991 */
992 # define explainSetInteger(a, b) a = b
993 
994 #else
995 /* No-op versions of the explainXXX() functions and macros. */
996 # define explainTempTable(y,z)
997 # define explainSetInteger(y,z)
998 #endif
999 
1000 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
1001 /*
1002 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
1003 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
1004 ** where the caption is of one of the two forms:
1005 **
1006 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
1007 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
1008 **
1009 ** where iSub1 and iSub2 are the integers passed as the corresponding
1010 ** function parameters, and op is the text representation of the parameter
1011 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
1012 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
1013 ** false, or the second form if it is true.
1014 */
1015 static void explainComposite(
1016   Parse *pParse,                  /* Parse context */
1017   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
1018   int iSub1,                      /* Subquery id 1 */
1019   int iSub2,                      /* Subquery id 2 */
1020   int bUseTmp                     /* True if a temp table was used */
1021 ){
1022   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
1023   if( pParse->explain==2 ){
1024     Vdbe *v = pParse->pVdbe;
1025     char *zMsg = sqlite3MPrintf(
1026         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
1027         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
1028     );
1029     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
1030   }
1031 }
1032 #else
1033 /* No-op versions of the explainXXX() functions and macros. */
1034 # define explainComposite(v,w,x,y,z)
1035 #endif
1036 
1037 /*
1038 ** If the inner loop was generated using a non-null pOrderBy argument,
1039 ** then the results were placed in a sorter.  After the loop is terminated
1040 ** we need to run the sorter and output the results.  The following
1041 ** routine generates the code needed to do that.
1042 */
1043 static void generateSortTail(
1044   Parse *pParse,    /* Parsing context */
1045   Select *p,        /* The SELECT statement */
1046   Vdbe *v,          /* Generate code into this VDBE */
1047   int nColumn,      /* Number of columns of data */
1048   SelectDest *pDest /* Write the sorted results here */
1049 ){
1050   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
1051   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
1052   int addr;
1053   int iTab;
1054   int pseudoTab = 0;
1055   ExprList *pOrderBy = p->pOrderBy;
1056 
1057   int eDest = pDest->eDest;
1058   int iParm = pDest->iSDParm;
1059 
1060   int regRow;
1061   int regRowid;
1062 
1063   iTab = pOrderBy->iECursor;
1064   regRow = sqlite3GetTempReg(pParse);
1065   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
1066     pseudoTab = pParse->nTab++;
1067     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
1068     regRowid = 0;
1069   }else{
1070     regRowid = sqlite3GetTempReg(pParse);
1071   }
1072   if( p->selFlags & SF_UseSorter ){
1073     int regSortOut = ++pParse->nMem;
1074     int ptab2 = pParse->nTab++;
1075     sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
1076     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
1077     codeOffset(v, p->iOffset, addrContinue);
1078     sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
1079     sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
1080     sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
1081   }else{
1082     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
1083     codeOffset(v, p->iOffset, addrContinue);
1084     sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
1085   }
1086   switch( eDest ){
1087     case SRT_Table:
1088     case SRT_EphemTab: {
1089       testcase( eDest==SRT_Table );
1090       testcase( eDest==SRT_EphemTab );
1091       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
1092       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
1093       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1094       break;
1095     }
1096 #ifndef SQLITE_OMIT_SUBQUERY
1097     case SRT_Set: {
1098       assert( nColumn==1 );
1099       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
1100                         &pDest->affSdst, 1);
1101       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
1102       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
1103       break;
1104     }
1105     case SRT_Mem: {
1106       assert( nColumn==1 );
1107       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
1108       /* The LIMIT clause will terminate the loop for us */
1109       break;
1110     }
1111 #endif
1112     default: {
1113       int i;
1114       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
1115       testcase( eDest==SRT_Output );
1116       testcase( eDest==SRT_Coroutine );
1117       for(i=0; i<nColumn; i++){
1118         assert( regRow!=pDest->iSdst+i );
1119         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
1120         if( i==0 ){
1121           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
1122         }
1123       }
1124       if( eDest==SRT_Output ){
1125         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
1126         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
1127       }else{
1128         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1129       }
1130       break;
1131     }
1132   }
1133   sqlite3ReleaseTempReg(pParse, regRow);
1134   sqlite3ReleaseTempReg(pParse, regRowid);
1135 
1136   /* The bottom of the loop
1137   */
1138   sqlite3VdbeResolveLabel(v, addrContinue);
1139   if( p->selFlags & SF_UseSorter ){
1140     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
1141   }else{
1142     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
1143   }
1144   sqlite3VdbeResolveLabel(v, addrBreak);
1145   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
1146     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
1147   }
1148 }
1149 
1150 /*
1151 ** Return a pointer to a string containing the 'declaration type' of the
1152 ** expression pExpr. The string may be treated as static by the caller.
1153 **
1154 ** Also try to estimate the size of the returned value and return that
1155 ** result in *pEstWidth.
1156 **
1157 ** The declaration type is the exact datatype definition extracted from the
1158 ** original CREATE TABLE statement if the expression is a column. The
1159 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
1160 ** is considered a column can be complex in the presence of subqueries. The
1161 ** result-set expression in all of the following SELECT statements is
1162 ** considered a column by this function.
1163 **
1164 **   SELECT col FROM tbl;
1165 **   SELECT (SELECT col FROM tbl;
1166 **   SELECT (SELECT col FROM tbl);
1167 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
1168 **
1169 ** The declaration type for any expression other than a column is NULL.
1170 **
1171 ** This routine has either 3 or 6 parameters depending on whether or not
1172 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
1173 */
1174 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1175 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
1176 static const char *columnTypeImpl(
1177   NameContext *pNC,
1178   Expr *pExpr,
1179   const char **pzOrigDb,
1180   const char **pzOrigTab,
1181   const char **pzOrigCol,
1182   u8 *pEstWidth
1183 ){
1184   char const *zOrigDb = 0;
1185   char const *zOrigTab = 0;
1186   char const *zOrigCol = 0;
1187 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
1188 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
1189 static const char *columnTypeImpl(
1190   NameContext *pNC,
1191   Expr *pExpr,
1192   u8 *pEstWidth
1193 ){
1194 #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
1195   char const *zType = 0;
1196   int j;
1197   u8 estWidth = 1;
1198 
1199   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
1200   switch( pExpr->op ){
1201     case TK_AGG_COLUMN:
1202     case TK_COLUMN: {
1203       /* The expression is a column. Locate the table the column is being
1204       ** extracted from in NameContext.pSrcList. This table may be real
1205       ** database table or a subquery.
1206       */
1207       Table *pTab = 0;            /* Table structure column is extracted from */
1208       Select *pS = 0;             /* Select the column is extracted from */
1209       int iCol = pExpr->iColumn;  /* Index of column in pTab */
1210       testcase( pExpr->op==TK_AGG_COLUMN );
1211       testcase( pExpr->op==TK_COLUMN );
1212       while( pNC && !pTab ){
1213         SrcList *pTabList = pNC->pSrcList;
1214         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
1215         if( j<pTabList->nSrc ){
1216           pTab = pTabList->a[j].pTab;
1217           pS = pTabList->a[j].pSelect;
1218         }else{
1219           pNC = pNC->pNext;
1220         }
1221       }
1222 
1223       if( pTab==0 ){
1224         /* At one time, code such as "SELECT new.x" within a trigger would
1225         ** cause this condition to run.  Since then, we have restructured how
1226         ** trigger code is generated and so this condition is no longer
1227         ** possible. However, it can still be true for statements like
1228         ** the following:
1229         **
1230         **   CREATE TABLE t1(col INTEGER);
1231         **   SELECT (SELECT t1.col) FROM FROM t1;
1232         **
1233         ** when columnType() is called on the expression "t1.col" in the
1234         ** sub-select. In this case, set the column type to NULL, even
1235         ** though it should really be "INTEGER".
1236         **
1237         ** This is not a problem, as the column type of "t1.col" is never
1238         ** used. When columnType() is called on the expression
1239         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
1240         ** branch below.  */
1241         break;
1242       }
1243 
1244       assert( pTab && pExpr->pTab==pTab );
1245       if( pS ){
1246         /* The "table" is actually a sub-select or a view in the FROM clause
1247         ** of the SELECT statement. Return the declaration type and origin
1248         ** data for the result-set column of the sub-select.
1249         */
1250         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
1251           /* If iCol is less than zero, then the expression requests the
1252           ** rowid of the sub-select or view. This expression is legal (see
1253           ** test case misc2.2.2) - it always evaluates to NULL.
1254           */
1255           NameContext sNC;
1256           Expr *p = pS->pEList->a[iCol].pExpr;
1257           sNC.pSrcList = pS->pSrc;
1258           sNC.pNext = pNC;
1259           sNC.pParse = pNC->pParse;
1260           zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
1261         }
1262       }else if( pTab->pSchema ){
1263         /* A real table */
1264         assert( !pS );
1265         if( iCol<0 ) iCol = pTab->iPKey;
1266         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1267 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1268         if( iCol<0 ){
1269           zType = "INTEGER";
1270           zOrigCol = "rowid";
1271         }else{
1272           zType = pTab->aCol[iCol].zType;
1273           zOrigCol = pTab->aCol[iCol].zName;
1274           estWidth = pTab->aCol[iCol].szEst;
1275         }
1276         zOrigTab = pTab->zName;
1277         if( pNC->pParse ){
1278           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
1279           zOrigDb = pNC->pParse->db->aDb[iDb].zName;
1280         }
1281 #else
1282         if( iCol<0 ){
1283           zType = "INTEGER";
1284         }else{
1285           zType = pTab->aCol[iCol].zType;
1286           estWidth = pTab->aCol[iCol].szEst;
1287         }
1288 #endif
1289       }
1290       break;
1291     }
1292 #ifndef SQLITE_OMIT_SUBQUERY
1293     case TK_SELECT: {
1294       /* The expression is a sub-select. Return the declaration type and
1295       ** origin info for the single column in the result set of the SELECT
1296       ** statement.
1297       */
1298       NameContext sNC;
1299       Select *pS = pExpr->x.pSelect;
1300       Expr *p = pS->pEList->a[0].pExpr;
1301       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
1302       sNC.pSrcList = pS->pSrc;
1303       sNC.pNext = pNC;
1304       sNC.pParse = pNC->pParse;
1305       zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
1306       break;
1307     }
1308 #endif
1309   }
1310 
1311 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1312   if( pzOrigDb ){
1313     assert( pzOrigTab && pzOrigCol );
1314     *pzOrigDb = zOrigDb;
1315     *pzOrigTab = zOrigTab;
1316     *pzOrigCol = zOrigCol;
1317   }
1318 #endif
1319   if( pEstWidth ) *pEstWidth = estWidth;
1320   return zType;
1321 }
1322 
1323 /*
1324 ** Generate code that will tell the VDBE the declaration types of columns
1325 ** in the result set.
1326 */
1327 static void generateColumnTypes(
1328   Parse *pParse,      /* Parser context */
1329   SrcList *pTabList,  /* List of tables */
1330   ExprList *pEList    /* Expressions defining the result set */
1331 ){
1332 #ifndef SQLITE_OMIT_DECLTYPE
1333   Vdbe *v = pParse->pVdbe;
1334   int i;
1335   NameContext sNC;
1336   sNC.pSrcList = pTabList;
1337   sNC.pParse = pParse;
1338   for(i=0; i<pEList->nExpr; i++){
1339     Expr *p = pEList->a[i].pExpr;
1340     const char *zType;
1341 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1342     const char *zOrigDb = 0;
1343     const char *zOrigTab = 0;
1344     const char *zOrigCol = 0;
1345     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
1346 
1347     /* The vdbe must make its own copy of the column-type and other
1348     ** column specific strings, in case the schema is reset before this
1349     ** virtual machine is deleted.
1350     */
1351     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
1352     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
1353     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
1354 #else
1355     zType = columnType(&sNC, p, 0, 0, 0, 0);
1356 #endif
1357     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
1358   }
1359 #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
1360 }
1361 
1362 /*
1363 ** Generate code that will tell the VDBE the names of columns
1364 ** in the result set.  This information is used to provide the
1365 ** azCol[] values in the callback.
1366 */
1367 static void generateColumnNames(
1368   Parse *pParse,      /* Parser context */
1369   SrcList *pTabList,  /* List of tables */
1370   ExprList *pEList    /* Expressions defining the result set */
1371 ){
1372   Vdbe *v = pParse->pVdbe;
1373   int i, j;
1374   sqlite3 *db = pParse->db;
1375   int fullNames, shortNames;
1376 
1377 #ifndef SQLITE_OMIT_EXPLAIN
1378   /* If this is an EXPLAIN, skip this step */
1379   if( pParse->explain ){
1380     return;
1381   }
1382 #endif
1383 
1384   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
1385   pParse->colNamesSet = 1;
1386   fullNames = (db->flags & SQLITE_FullColNames)!=0;
1387   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
1388   sqlite3VdbeSetNumCols(v, pEList->nExpr);
1389   for(i=0; i<pEList->nExpr; i++){
1390     Expr *p;
1391     p = pEList->a[i].pExpr;
1392     if( NEVER(p==0) ) continue;
1393     if( pEList->a[i].zName ){
1394       char *zName = pEList->a[i].zName;
1395       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
1396     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
1397       Table *pTab;
1398       char *zCol;
1399       int iCol = p->iColumn;
1400       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
1401         if( pTabList->a[j].iCursor==p->iTable ) break;
1402       }
1403       assert( j<pTabList->nSrc );
1404       pTab = pTabList->a[j].pTab;
1405       if( iCol<0 ) iCol = pTab->iPKey;
1406       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1407       if( iCol<0 ){
1408         zCol = "rowid";
1409       }else{
1410         zCol = pTab->aCol[iCol].zName;
1411       }
1412       if( !shortNames && !fullNames ){
1413         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
1414             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
1415       }else if( fullNames ){
1416         char *zName = 0;
1417         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
1418         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
1419       }else{
1420         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
1421       }
1422     }else{
1423       const char *z = pEList->a[i].zSpan;
1424       z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
1425       sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
1426     }
1427   }
1428   generateColumnTypes(pParse, pTabList, pEList);
1429 }
1430 
1431 /*
1432 ** Given a an expression list (which is really the list of expressions
1433 ** that form the result set of a SELECT statement) compute appropriate
1434 ** column names for a table that would hold the expression list.
1435 **
1436 ** All column names will be unique.
1437 **
1438 ** Only the column names are computed.  Column.zType, Column.zColl,
1439 ** and other fields of Column are zeroed.
1440 **
1441 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
1442 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
1443 */
1444 static int selectColumnsFromExprList(
1445   Parse *pParse,          /* Parsing context */
1446   ExprList *pEList,       /* Expr list from which to derive column names */
1447   i16 *pnCol,             /* Write the number of columns here */
1448   Column **paCol          /* Write the new column list here */
1449 ){
1450   sqlite3 *db = pParse->db;   /* Database connection */
1451   int i, j;                   /* Loop counters */
1452   int cnt;                    /* Index added to make the name unique */
1453   Column *aCol, *pCol;        /* For looping over result columns */
1454   int nCol;                   /* Number of columns in the result set */
1455   Expr *p;                    /* Expression for a single result column */
1456   char *zName;                /* Column name */
1457   int nName;                  /* Size of name in zName[] */
1458 
1459   if( pEList ){
1460     nCol = pEList->nExpr;
1461     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
1462     testcase( aCol==0 );
1463   }else{
1464     nCol = 0;
1465     aCol = 0;
1466   }
1467   *pnCol = nCol;
1468   *paCol = aCol;
1469 
1470   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
1471     /* Get an appropriate name for the column
1472     */
1473     p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
1474     if( (zName = pEList->a[i].zName)!=0 ){
1475       /* If the column contains an "AS <name>" phrase, use <name> as the name */
1476       zName = sqlite3DbStrDup(db, zName);
1477     }else{
1478       Expr *pColExpr = p;  /* The expression that is the result column name */
1479       Table *pTab;         /* Table associated with this expression */
1480       while( pColExpr->op==TK_DOT ){
1481         pColExpr = pColExpr->pRight;
1482         assert( pColExpr!=0 );
1483       }
1484       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
1485         /* For columns use the column name name */
1486         int iCol = pColExpr->iColumn;
1487         pTab = pColExpr->pTab;
1488         if( iCol<0 ) iCol = pTab->iPKey;
1489         zName = sqlite3MPrintf(db, "%s",
1490                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
1491       }else if( pColExpr->op==TK_ID ){
1492         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
1493         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
1494       }else{
1495         /* Use the original text of the column expression as its name */
1496         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
1497       }
1498     }
1499     if( db->mallocFailed ){
1500       sqlite3DbFree(db, zName);
1501       break;
1502     }
1503 
1504     /* Make sure the column name is unique.  If the name is not unique,
1505     ** append a integer to the name so that it becomes unique.
1506     */
1507     nName = sqlite3Strlen30(zName);
1508     for(j=cnt=0; j<i; j++){
1509       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
1510         char *zNewName;
1511         int k;
1512         for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
1513         if( zName[k]==':' ) nName = k;
1514         zName[nName] = 0;
1515         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
1516         sqlite3DbFree(db, zName);
1517         zName = zNewName;
1518         j = -1;
1519         if( zName==0 ) break;
1520       }
1521     }
1522     pCol->zName = zName;
1523   }
1524   if( db->mallocFailed ){
1525     for(j=0; j<i; j++){
1526       sqlite3DbFree(db, aCol[j].zName);
1527     }
1528     sqlite3DbFree(db, aCol);
1529     *paCol = 0;
1530     *pnCol = 0;
1531     return SQLITE_NOMEM;
1532   }
1533   return SQLITE_OK;
1534 }
1535 
1536 /*
1537 ** Add type and collation information to a column list based on
1538 ** a SELECT statement.
1539 **
1540 ** The column list presumably came from selectColumnNamesFromExprList().
1541 ** The column list has only names, not types or collations.  This
1542 ** routine goes through and adds the types and collations.
1543 **
1544 ** This routine requires that all identifiers in the SELECT
1545 ** statement be resolved.
1546 */
1547 static void selectAddColumnTypeAndCollation(
1548   Parse *pParse,        /* Parsing contexts */
1549   Table *pTab,          /* Add column type information to this table */
1550   Select *pSelect       /* SELECT used to determine types and collations */
1551 ){
1552   sqlite3 *db = pParse->db;
1553   NameContext sNC;
1554   Column *pCol;
1555   CollSeq *pColl;
1556   int i;
1557   Expr *p;
1558   struct ExprList_item *a;
1559   u64 szAll = 0;
1560 
1561   assert( pSelect!=0 );
1562   assert( (pSelect->selFlags & SF_Resolved)!=0 );
1563   assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
1564   if( db->mallocFailed ) return;
1565   memset(&sNC, 0, sizeof(sNC));
1566   sNC.pSrcList = pSelect->pSrc;
1567   a = pSelect->pEList->a;
1568   for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
1569     p = a[i].pExpr;
1570     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
1571     szAll += pCol->szEst;
1572     pCol->affinity = sqlite3ExprAffinity(p);
1573     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
1574     pColl = sqlite3ExprCollSeq(pParse, p);
1575     if( pColl ){
1576       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
1577     }
1578   }
1579   pTab->szTabRow = sqlite3LogEst(szAll*4);
1580 }
1581 
1582 /*
1583 ** Given a SELECT statement, generate a Table structure that describes
1584 ** the result set of that SELECT.
1585 */
1586 Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
1587   Table *pTab;
1588   sqlite3 *db = pParse->db;
1589   int savedFlags;
1590 
1591   savedFlags = db->flags;
1592   db->flags &= ~SQLITE_FullColNames;
1593   db->flags |= SQLITE_ShortColNames;
1594   sqlite3SelectPrep(pParse, pSelect, 0);
1595   if( pParse->nErr ) return 0;
1596   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
1597   db->flags = savedFlags;
1598   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
1599   if( pTab==0 ){
1600     return 0;
1601   }
1602   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
1603   ** is disabled */
1604   assert( db->lookaside.bEnabled==0 );
1605   pTab->nRef = 1;
1606   pTab->zName = 0;
1607   pTab->nRowEst = 1048576;
1608   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
1609   selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
1610   pTab->iPKey = -1;
1611   if( db->mallocFailed ){
1612     sqlite3DeleteTable(db, pTab);
1613     return 0;
1614   }
1615   return pTab;
1616 }
1617 
1618 /*
1619 ** Get a VDBE for the given parser context.  Create a new one if necessary.
1620 ** If an error occurs, return NULL and leave a message in pParse.
1621 */
1622 Vdbe *sqlite3GetVdbe(Parse *pParse){
1623   Vdbe *v = pParse->pVdbe;
1624   if( v==0 ){
1625     v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
1626     if( v ) sqlite3VdbeAddOp0(v, OP_Init);
1627     if( pParse->pToplevel==0
1628      && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
1629     ){
1630       pParse->okConstFactor = 1;
1631     }
1632 
1633   }
1634   return v;
1635 }
1636 
1637 
1638 /*
1639 ** Compute the iLimit and iOffset fields of the SELECT based on the
1640 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
1641 ** that appear in the original SQL statement after the LIMIT and OFFSET
1642 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1643 ** are the integer memory register numbers for counters used to compute
1644 ** the limit and offset.  If there is no limit and/or offset, then
1645 ** iLimit and iOffset are negative.
1646 **
1647 ** This routine changes the values of iLimit and iOffset only if
1648 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
1649 ** iOffset should have been preset to appropriate default values (zero)
1650 ** prior to calling this routine.
1651 **
1652 ** The iOffset register (if it exists) is initialized to the value
1653 ** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
1654 ** iOffset+1 is initialized to LIMIT+OFFSET.
1655 **
1656 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
1657 ** redefined.  The UNION ALL operator uses this property to force
1658 ** the reuse of the same limit and offset registers across multiple
1659 ** SELECT statements.
1660 */
1661 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
1662   Vdbe *v = 0;
1663   int iLimit = 0;
1664   int iOffset;
1665   int addr1, n;
1666   if( p->iLimit ) return;
1667 
1668   /*
1669   ** "LIMIT -1" always shows all rows.  There is some
1670   ** controversy about what the correct behavior should be.
1671   ** The current implementation interprets "LIMIT 0" to mean
1672   ** no rows.
1673   */
1674   sqlite3ExprCacheClear(pParse);
1675   assert( p->pOffset==0 || p->pLimit!=0 );
1676   if( p->pLimit ){
1677     p->iLimit = iLimit = ++pParse->nMem;
1678     v = sqlite3GetVdbe(pParse);
1679     assert( v!=0 );
1680     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
1681       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
1682       VdbeComment((v, "LIMIT counter"));
1683       if( n==0 ){
1684         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
1685       }else if( n>=0 && p->nSelectRow>(u64)n ){
1686         p->nSelectRow = n;
1687       }
1688     }else{
1689       sqlite3ExprCode(pParse, p->pLimit, iLimit);
1690       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
1691       VdbeComment((v, "LIMIT counter"));
1692       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
1693     }
1694     if( p->pOffset ){
1695       p->iOffset = iOffset = ++pParse->nMem;
1696       pParse->nMem++;   /* Allocate an extra register for limit+offset */
1697       sqlite3ExprCode(pParse, p->pOffset, iOffset);
1698       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
1699       VdbeComment((v, "OFFSET counter"));
1700       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
1701       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
1702       sqlite3VdbeJumpHere(v, addr1);
1703       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
1704       VdbeComment((v, "LIMIT+OFFSET"));
1705       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
1706       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
1707       sqlite3VdbeJumpHere(v, addr1);
1708     }
1709   }
1710 }
1711 
1712 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1713 /*
1714 ** Return the appropriate collating sequence for the iCol-th column of
1715 ** the result set for the compound-select statement "p".  Return NULL if
1716 ** the column has no default collating sequence.
1717 **
1718 ** The collating sequence for the compound select is taken from the
1719 ** left-most term of the select that has a collating sequence.
1720 */
1721 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1722   CollSeq *pRet;
1723   if( p->pPrior ){
1724     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1725   }else{
1726     pRet = 0;
1727   }
1728   assert( iCol>=0 );
1729   if( pRet==0 && iCol<p->pEList->nExpr ){
1730     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1731   }
1732   return pRet;
1733 }
1734 
1735 /*
1736 ** The select statement passed as the second parameter is a compound SELECT
1737 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
1738 ** structure suitable for implementing the ORDER BY.
1739 **
1740 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
1741 ** function is responsible for ensuring that this structure is eventually
1742 ** freed.
1743 */
1744 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
1745   ExprList *pOrderBy = p->pOrderBy;
1746   int nOrderBy = p->pOrderBy->nExpr;
1747   sqlite3 *db = pParse->db;
1748   KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
1749   if( pRet ){
1750     int i;
1751     for(i=0; i<nOrderBy; i++){
1752       struct ExprList_item *pItem = &pOrderBy->a[i];
1753       Expr *pTerm = pItem->pExpr;
1754       CollSeq *pColl;
1755 
1756       if( pTerm->flags & EP_Collate ){
1757         pColl = sqlite3ExprCollSeq(pParse, pTerm);
1758       }else{
1759         pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
1760         if( pColl==0 ) pColl = db->pDfltColl;
1761         pOrderBy->a[i].pExpr =
1762           sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
1763       }
1764       assert( sqlite3KeyInfoIsWriteable(pRet) );
1765       pRet->aColl[i] = pColl;
1766       pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
1767     }
1768   }
1769 
1770   return pRet;
1771 }
1772 
1773 #ifndef SQLITE_OMIT_CTE
1774 /*
1775 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
1776 ** query of the form:
1777 **
1778 **   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
1779 **                         \___________/             \_______________/
1780 **                           p->pPrior                      p
1781 **
1782 **
1783 ** There is exactly one reference to the recursive-table in the FROM clause
1784 ** of recursive-query, marked with the SrcList->a[].isRecursive flag.
1785 **
1786 ** The setup-query runs once to generate an initial set of rows that go
1787 ** into a Queue table.  Rows are extracted from the Queue table one by
1788 ** one.  Each row extracted from Queue is output to pDest.  Then the single
1789 ** extracted row (now in the iCurrent table) becomes the content of the
1790 ** recursive-table for a recursive-query run.  The output of the recursive-query
1791 ** is added back into the Queue table.  Then another row is extracted from Queue
1792 ** and the iteration continues until the Queue table is empty.
1793 **
1794 ** If the compound query operator is UNION then no duplicate rows are ever
1795 ** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
1796 ** that have ever been inserted into Queue and causes duplicates to be
1797 ** discarded.  If the operator is UNION ALL, then duplicates are allowed.
1798 **
1799 ** If the query has an ORDER BY, then entries in the Queue table are kept in
1800 ** ORDER BY order and the first entry is extracted for each cycle.  Without
1801 ** an ORDER BY, the Queue table is just a FIFO.
1802 **
1803 ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
1804 ** have been output to pDest.  A LIMIT of zero means to output no rows and a
1805 ** negative LIMIT means to output all rows.  If there is also an OFFSET clause
1806 ** with a positive value, then the first OFFSET outputs are discarded rather
1807 ** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
1808 ** rows have been skipped.
1809 */
1810 static void generateWithRecursiveQuery(
1811   Parse *pParse,        /* Parsing context */
1812   Select *p,            /* The recursive SELECT to be coded */
1813   SelectDest *pDest     /* What to do with query results */
1814 ){
1815   SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
1816   int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
1817   Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
1818   Select *pSetup = p->pPrior;   /* The setup query */
1819   int addrTop;                  /* Top of the loop */
1820   int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
1821   int iCurrent = 0;             /* The Current table */
1822   int regCurrent;               /* Register holding Current table */
1823   int iQueue;                   /* The Queue table */
1824   int iDistinct = 0;            /* To ensure unique results if UNION */
1825   int eDest = SRT_Table;        /* How to write to Queue */
1826   SelectDest destQueue;         /* SelectDest targetting the Queue table */
1827   int i;                        /* Loop counter */
1828   int rc;                       /* Result code */
1829   ExprList *pOrderBy;           /* The ORDER BY clause */
1830   Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
1831   int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
1832 
1833   /* Obtain authorization to do a recursive query */
1834   if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
1835 
1836   /* Process the LIMIT and OFFSET clauses, if they exist */
1837   addrBreak = sqlite3VdbeMakeLabel(v);
1838   computeLimitRegisters(pParse, p, addrBreak);
1839   pLimit = p->pLimit;
1840   pOffset = p->pOffset;
1841   regLimit = p->iLimit;
1842   regOffset = p->iOffset;
1843   p->pLimit = p->pOffset = 0;
1844   p->iLimit = p->iOffset = 0;
1845   pOrderBy = p->pOrderBy;
1846 
1847   /* Locate the cursor number of the Current table */
1848   for(i=0; ALWAYS(i<pSrc->nSrc); i++){
1849     if( pSrc->a[i].isRecursive ){
1850       iCurrent = pSrc->a[i].iCursor;
1851       break;
1852     }
1853   }
1854 
1855   /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
1856   ** the Distinct table must be exactly one greater than Queue in order
1857   ** for the SRT_DistTable and SRT_DistQueue destinations to work. */
1858   iQueue = pParse->nTab++;
1859   if( p->op==TK_UNION ){
1860     eDest = pOrderBy ? SRT_DistQueue : SRT_DistTable;
1861     iDistinct = pParse->nTab++;
1862   }else{
1863     eDest = pOrderBy ? SRT_Queue : SRT_Table;
1864   }
1865   sqlite3SelectDestInit(&destQueue, eDest, iQueue);
1866 
1867   /* Allocate cursors for Current, Queue, and Distinct. */
1868   regCurrent = ++pParse->nMem;
1869   sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
1870   if( pOrderBy ){
1871     KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
1872     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
1873                       (char*)pKeyInfo, P4_KEYINFO);
1874     destQueue.pOrderBy = pOrderBy;
1875   }else{
1876     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
1877   }
1878   VdbeComment((v, "Queue table"));
1879   if( iDistinct ){
1880     p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
1881     p->selFlags |= SF_UsesEphemeral;
1882   }
1883 
1884   /* Detach the ORDER BY clause from the compound SELECT */
1885   p->pOrderBy = 0;
1886 
1887   /* Store the results of the setup-query in Queue. */
1888   pSetup->pNext = 0;
1889   rc = sqlite3Select(pParse, pSetup, &destQueue);
1890   pSetup->pNext = p;
1891   if( rc ) goto end_of_recursive_query;
1892 
1893   /* Find the next row in the Queue and output that row */
1894   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak);
1895 
1896   /* Transfer the next row in Queue over to Current */
1897   sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
1898   if( pOrderBy ){
1899     sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
1900   }else{
1901     sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
1902   }
1903   sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
1904 
1905   /* Output the single row in Current */
1906   addrCont = sqlite3VdbeMakeLabel(v);
1907   codeOffset(v, regOffset, addrCont);
1908   selectInnerLoop(pParse, p, p->pEList, iCurrent,
1909       0, 0, pDest, addrCont, addrBreak);
1910   if( regLimit ) sqlite3VdbeAddOp3(v, OP_IfZero, regLimit, addrBreak, -1);
1911   sqlite3VdbeResolveLabel(v, addrCont);
1912 
1913   /* Execute the recursive SELECT taking the single row in Current as
1914   ** the value for the recursive-table. Store the results in the Queue.
1915   */
1916   p->pPrior = 0;
1917   sqlite3Select(pParse, p, &destQueue);
1918   assert( p->pPrior==0 );
1919   p->pPrior = pSetup;
1920 
1921   /* Keep running the loop until the Queue is empty */
1922   sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
1923   sqlite3VdbeResolveLabel(v, addrBreak);
1924 
1925 end_of_recursive_query:
1926   p->pOrderBy = pOrderBy;
1927   p->pLimit = pLimit;
1928   p->pOffset = pOffset;
1929   return;
1930 }
1931 #endif /* SQLITE_OMIT_CTE */
1932 
1933 /* Forward references */
1934 static int multiSelectOrderBy(
1935   Parse *pParse,        /* Parsing context */
1936   Select *p,            /* The right-most of SELECTs to be coded */
1937   SelectDest *pDest     /* What to do with query results */
1938 );
1939 
1940 
1941 /*
1942 ** This routine is called to process a compound query form from
1943 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
1944 ** INTERSECT
1945 **
1946 ** "p" points to the right-most of the two queries.  the query on the
1947 ** left is p->pPrior.  The left query could also be a compound query
1948 ** in which case this routine will be called recursively.
1949 **
1950 ** The results of the total query are to be written into a destination
1951 ** of type eDest with parameter iParm.
1952 **
1953 ** Example 1:  Consider a three-way compound SQL statement.
1954 **
1955 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1956 **
1957 ** This statement is parsed up as follows:
1958 **
1959 **     SELECT c FROM t3
1960 **      |
1961 **      `----->  SELECT b FROM t2
1962 **                |
1963 **                `------>  SELECT a FROM t1
1964 **
1965 ** The arrows in the diagram above represent the Select.pPrior pointer.
1966 ** So if this routine is called with p equal to the t3 query, then
1967 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1968 **
1969 ** Notice that because of the way SQLite parses compound SELECTs, the
1970 ** individual selects always group from left to right.
1971 */
1972 static int multiSelect(
1973   Parse *pParse,        /* Parsing context */
1974   Select *p,            /* The right-most of SELECTs to be coded */
1975   SelectDest *pDest     /* What to do with query results */
1976 ){
1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
1978   Select *pPrior;       /* Another SELECT immediately to our left */
1979   Vdbe *v;              /* Generate code to this VDBE */
1980   SelectDest dest;      /* Alternative data destination */
1981   Select *pDelete = 0;  /* Chain of simple selects to delete */
1982   sqlite3 *db;          /* Database connection */
1983 #ifndef SQLITE_OMIT_EXPLAIN
1984   int iSub1 = 0;        /* EQP id of left-hand query */
1985   int iSub2 = 0;        /* EQP id of right-hand query */
1986 #endif
1987 
1988   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1989   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
1990   */
1991   assert( p && p->pPrior );  /* Calling function guarantees this much */
1992   assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
1993   db = pParse->db;
1994   pPrior = p->pPrior;
1995   dest = *pDest;
1996   if( pPrior->pOrderBy ){
1997     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1998       selectOpName(p->op));
1999     rc = 1;
2000     goto multi_select_end;
2001   }
2002   if( pPrior->pLimit ){
2003     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
2004       selectOpName(p->op));
2005     rc = 1;
2006     goto multi_select_end;
2007   }
2008 
2009   v = sqlite3GetVdbe(pParse);
2010   assert( v!=0 );  /* The VDBE already created by calling function */
2011 
2012   /* Create the destination temporary table if necessary
2013   */
2014   if( dest.eDest==SRT_EphemTab ){
2015     assert( p->pEList );
2016     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
2017     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
2018     dest.eDest = SRT_Table;
2019   }
2020 
2021   /* Make sure all SELECTs in the statement have the same number of elements
2022   ** in their result sets.
2023   */
2024   assert( p->pEList && pPrior->pEList );
2025   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
2026     if( p->selFlags & SF_Values ){
2027       sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
2028     }else{
2029       sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
2030         " do not have the same number of result columns", selectOpName(p->op));
2031     }
2032     rc = 1;
2033     goto multi_select_end;
2034   }
2035 
2036 #ifndef SQLITE_OMIT_CTE
2037   if( p->selFlags & SF_Recursive ){
2038     generateWithRecursiveQuery(pParse, p, &dest);
2039   }else
2040 #endif
2041 
2042   /* Compound SELECTs that have an ORDER BY clause are handled separately.
2043   */
2044   if( p->pOrderBy ){
2045     return multiSelectOrderBy(pParse, p, pDest);
2046   }else
2047 
2048   /* Generate code for the left and right SELECT statements.
2049   */
2050   switch( p->op ){
2051     case TK_ALL: {
2052       int addr = 0;
2053       int nLimit;
2054       assert( !pPrior->pLimit );
2055       pPrior->iLimit = p->iLimit;
2056       pPrior->iOffset = p->iOffset;
2057       pPrior->pLimit = p->pLimit;
2058       pPrior->pOffset = p->pOffset;
2059       explainSetInteger(iSub1, pParse->iNextSelectId);
2060       rc = sqlite3Select(pParse, pPrior, &dest);
2061       p->pLimit = 0;
2062       p->pOffset = 0;
2063       if( rc ){
2064         goto multi_select_end;
2065       }
2066       p->pPrior = 0;
2067       p->iLimit = pPrior->iLimit;
2068       p->iOffset = pPrior->iOffset;
2069       if( p->iLimit ){
2070         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
2071         VdbeComment((v, "Jump ahead if LIMIT reached"));
2072       }
2073       explainSetInteger(iSub2, pParse->iNextSelectId);
2074       rc = sqlite3Select(pParse, p, &dest);
2075       testcase( rc!=SQLITE_OK );
2076       pDelete = p->pPrior;
2077       p->pPrior = pPrior;
2078       p->nSelectRow += pPrior->nSelectRow;
2079       if( pPrior->pLimit
2080        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
2081        && nLimit>0 && p->nSelectRow > (u64)nLimit
2082       ){
2083         p->nSelectRow = nLimit;
2084       }
2085       if( addr ){
2086         sqlite3VdbeJumpHere(v, addr);
2087       }
2088       break;
2089     }
2090     case TK_EXCEPT:
2091     case TK_UNION: {
2092       int unionTab;    /* Cursor number of the temporary table holding result */
2093       u8 op = 0;       /* One of the SRT_ operations to apply to self */
2094       int priorOp;     /* The SRT_ operation to apply to prior selects */
2095       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
2096       int addr;
2097       SelectDest uniondest;
2098 
2099       testcase( p->op==TK_EXCEPT );
2100       testcase( p->op==TK_UNION );
2101       priorOp = SRT_Union;
2102       if( dest.eDest==priorOp ){
2103         /* We can reuse a temporary table generated by a SELECT to our
2104         ** right.
2105         */
2106         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
2107         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
2108         unionTab = dest.iSDParm;
2109       }else{
2110         /* We will need to create our own temporary table to hold the
2111         ** intermediate results.
2112         */
2113         unionTab = pParse->nTab++;
2114         assert( p->pOrderBy==0 );
2115         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
2116         assert( p->addrOpenEphm[0] == -1 );
2117         p->addrOpenEphm[0] = addr;
2118         findRightmost(p)->selFlags |= SF_UsesEphemeral;
2119         assert( p->pEList );
2120       }
2121 
2122       /* Code the SELECT statements to our left
2123       */
2124       assert( !pPrior->pOrderBy );
2125       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
2126       explainSetInteger(iSub1, pParse->iNextSelectId);
2127       rc = sqlite3Select(pParse, pPrior, &uniondest);
2128       if( rc ){
2129         goto multi_select_end;
2130       }
2131 
2132       /* Code the current SELECT statement
2133       */
2134       if( p->op==TK_EXCEPT ){
2135         op = SRT_Except;
2136       }else{
2137         assert( p->op==TK_UNION );
2138         op = SRT_Union;
2139       }
2140       p->pPrior = 0;
2141       pLimit = p->pLimit;
2142       p->pLimit = 0;
2143       pOffset = p->pOffset;
2144       p->pOffset = 0;
2145       uniondest.eDest = op;
2146       explainSetInteger(iSub2, pParse->iNextSelectId);
2147       rc = sqlite3Select(pParse, p, &uniondest);
2148       testcase( rc!=SQLITE_OK );
2149       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
2150       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
2151       sqlite3ExprListDelete(db, p->pOrderBy);
2152       pDelete = p->pPrior;
2153       p->pPrior = pPrior;
2154       p->pOrderBy = 0;
2155       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
2156       sqlite3ExprDelete(db, p->pLimit);
2157       p->pLimit = pLimit;
2158       p->pOffset = pOffset;
2159       p->iLimit = 0;
2160       p->iOffset = 0;
2161 
2162       /* Convert the data in the temporary table into whatever form
2163       ** it is that we currently need.
2164       */
2165       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
2166       if( dest.eDest!=priorOp ){
2167         int iCont, iBreak, iStart;
2168         assert( p->pEList );
2169         if( dest.eDest==SRT_Output ){
2170           Select *pFirst = p;
2171           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
2172           generateColumnNames(pParse, 0, pFirst->pEList);
2173         }
2174         iBreak = sqlite3VdbeMakeLabel(v);
2175         iCont = sqlite3VdbeMakeLabel(v);
2176         computeLimitRegisters(pParse, p, iBreak);
2177         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
2178         iStart = sqlite3VdbeCurrentAddr(v);
2179         selectInnerLoop(pParse, p, p->pEList, unionTab,
2180                         0, 0, &dest, iCont, iBreak);
2181         sqlite3VdbeResolveLabel(v, iCont);
2182         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
2183         sqlite3VdbeResolveLabel(v, iBreak);
2184         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
2185       }
2186       break;
2187     }
2188     default: assert( p->op==TK_INTERSECT ); {
2189       int tab1, tab2;
2190       int iCont, iBreak, iStart;
2191       Expr *pLimit, *pOffset;
2192       int addr;
2193       SelectDest intersectdest;
2194       int r1;
2195 
2196       /* INTERSECT is different from the others since it requires
2197       ** two temporary tables.  Hence it has its own case.  Begin
2198       ** by allocating the tables we will need.
2199       */
2200       tab1 = pParse->nTab++;
2201       tab2 = pParse->nTab++;
2202       assert( p->pOrderBy==0 );
2203 
2204       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
2205       assert( p->addrOpenEphm[0] == -1 );
2206       p->addrOpenEphm[0] = addr;
2207       findRightmost(p)->selFlags |= SF_UsesEphemeral;
2208       assert( p->pEList );
2209 
2210       /* Code the SELECTs to our left into temporary table "tab1".
2211       */
2212       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
2213       explainSetInteger(iSub1, pParse->iNextSelectId);
2214       rc = sqlite3Select(pParse, pPrior, &intersectdest);
2215       if( rc ){
2216         goto multi_select_end;
2217       }
2218 
2219       /* Code the current SELECT into temporary table "tab2"
2220       */
2221       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
2222       assert( p->addrOpenEphm[1] == -1 );
2223       p->addrOpenEphm[1] = addr;
2224       p->pPrior = 0;
2225       pLimit = p->pLimit;
2226       p->pLimit = 0;
2227       pOffset = p->pOffset;
2228       p->pOffset = 0;
2229       intersectdest.iSDParm = tab2;
2230       explainSetInteger(iSub2, pParse->iNextSelectId);
2231       rc = sqlite3Select(pParse, p, &intersectdest);
2232       testcase( rc!=SQLITE_OK );
2233       pDelete = p->pPrior;
2234       p->pPrior = pPrior;
2235       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
2236       sqlite3ExprDelete(db, p->pLimit);
2237       p->pLimit = pLimit;
2238       p->pOffset = pOffset;
2239 
2240       /* Generate code to take the intersection of the two temporary
2241       ** tables.
2242       */
2243       assert( p->pEList );
2244       if( dest.eDest==SRT_Output ){
2245         Select *pFirst = p;
2246         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
2247         generateColumnNames(pParse, 0, pFirst->pEList);
2248       }
2249       iBreak = sqlite3VdbeMakeLabel(v);
2250       iCont = sqlite3VdbeMakeLabel(v);
2251       computeLimitRegisters(pParse, p, iBreak);
2252       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
2253       r1 = sqlite3GetTempReg(pParse);
2254       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
2255       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
2256       sqlite3ReleaseTempReg(pParse, r1);
2257       selectInnerLoop(pParse, p, p->pEList, tab1,
2258                       0, 0, &dest, iCont, iBreak);
2259       sqlite3VdbeResolveLabel(v, iCont);
2260       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
2261       sqlite3VdbeResolveLabel(v, iBreak);
2262       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
2263       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
2264       break;
2265     }
2266   }
2267 
2268   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
2269 
2270   /* Compute collating sequences used by
2271   ** temporary tables needed to implement the compound select.
2272   ** Attach the KeyInfo structure to all temporary tables.
2273   **
2274   ** This section is run by the right-most SELECT statement only.
2275   ** SELECT statements to the left always skip this part.  The right-most
2276   ** SELECT might also skip this part if it has no ORDER BY clause and
2277   ** no temp tables are required.
2278   */
2279   if( p->selFlags & SF_UsesEphemeral ){
2280     int i;                        /* Loop counter */
2281     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
2282     Select *pLoop;                /* For looping through SELECT statements */
2283     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
2284     int nCol;                     /* Number of columns in result set */
2285 
2286     assert( p->pNext==0 );
2287     nCol = p->pEList->nExpr;
2288     pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
2289     if( !pKeyInfo ){
2290       rc = SQLITE_NOMEM;
2291       goto multi_select_end;
2292     }
2293     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
2294       *apColl = multiSelectCollSeq(pParse, p, i);
2295       if( 0==*apColl ){
2296         *apColl = db->pDfltColl;
2297       }
2298     }
2299 
2300     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
2301       for(i=0; i<2; i++){
2302         int addr = pLoop->addrOpenEphm[i];
2303         if( addr<0 ){
2304           /* If [0] is unused then [1] is also unused.  So we can
2305           ** always safely abort as soon as the first unused slot is found */
2306           assert( pLoop->addrOpenEphm[1]<0 );
2307           break;
2308         }
2309         sqlite3VdbeChangeP2(v, addr, nCol);
2310         sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
2311                             P4_KEYINFO);
2312         pLoop->addrOpenEphm[i] = -1;
2313       }
2314     }
2315     sqlite3KeyInfoUnref(pKeyInfo);
2316   }
2317 
2318 multi_select_end:
2319   pDest->iSdst = dest.iSdst;
2320   pDest->nSdst = dest.nSdst;
2321   sqlite3SelectDelete(db, pDelete);
2322   return rc;
2323 }
2324 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
2325 
2326 /*
2327 ** Code an output subroutine for a coroutine implementation of a
2328 ** SELECT statment.
2329 **
2330 ** The data to be output is contained in pIn->iSdst.  There are
2331 ** pIn->nSdst columns to be output.  pDest is where the output should
2332 ** be sent.
2333 **
2334 ** regReturn is the number of the register holding the subroutine
2335 ** return address.
2336 **
2337 ** If regPrev>0 then it is the first register in a vector that
2338 ** records the previous output.  mem[regPrev] is a flag that is false
2339 ** if there has been no previous output.  If regPrev>0 then code is
2340 ** generated to suppress duplicates.  pKeyInfo is used for comparing
2341 ** keys.
2342 **
2343 ** If the LIMIT found in p->iLimit is reached, jump immediately to
2344 ** iBreak.
2345 */
2346 static int generateOutputSubroutine(
2347   Parse *pParse,          /* Parsing context */
2348   Select *p,              /* The SELECT statement */
2349   SelectDest *pIn,        /* Coroutine supplying data */
2350   SelectDest *pDest,      /* Where to send the data */
2351   int regReturn,          /* The return address register */
2352   int regPrev,            /* Previous result register.  No uniqueness if 0 */
2353   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
2354   int iBreak              /* Jump here if we hit the LIMIT */
2355 ){
2356   Vdbe *v = pParse->pVdbe;
2357   int iContinue;
2358   int addr;
2359 
2360   addr = sqlite3VdbeCurrentAddr(v);
2361   iContinue = sqlite3VdbeMakeLabel(v);
2362 
2363   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
2364   */
2365   if( regPrev ){
2366     int j1, j2;
2367     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
2368     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
2369                               (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
2370     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
2371     sqlite3VdbeJumpHere(v, j1);
2372     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
2373     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
2374   }
2375   if( pParse->db->mallocFailed ) return 0;
2376 
2377   /* Suppress the first OFFSET entries if there is an OFFSET clause
2378   */
2379   codeOffset(v, p->iOffset, iContinue);
2380 
2381   switch( pDest->eDest ){
2382     /* Store the result as data using a unique key.
2383     */
2384     case SRT_Table:
2385     case SRT_EphemTab: {
2386       int r1 = sqlite3GetTempReg(pParse);
2387       int r2 = sqlite3GetTempReg(pParse);
2388       testcase( pDest->eDest==SRT_Table );
2389       testcase( pDest->eDest==SRT_EphemTab );
2390       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
2391       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
2392       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
2393       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
2394       sqlite3ReleaseTempReg(pParse, r2);
2395       sqlite3ReleaseTempReg(pParse, r1);
2396       break;
2397     }
2398 
2399 #ifndef SQLITE_OMIT_SUBQUERY
2400     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
2401     ** then there should be a single item on the stack.  Write this
2402     ** item into the set table with bogus data.
2403     */
2404     case SRT_Set: {
2405       int r1;
2406       assert( pIn->nSdst==1 );
2407       pDest->affSdst =
2408          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
2409       r1 = sqlite3GetTempReg(pParse);
2410       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
2411       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
2412       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
2413       sqlite3ReleaseTempReg(pParse, r1);
2414       break;
2415     }
2416 
2417 #if 0  /* Never occurs on an ORDER BY query */
2418     /* If any row exist in the result set, record that fact and abort.
2419     */
2420     case SRT_Exists: {
2421       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
2422       /* The LIMIT clause will terminate the loop for us */
2423       break;
2424     }
2425 #endif
2426 
2427     /* If this is a scalar select that is part of an expression, then
2428     ** store the results in the appropriate memory cell and break out
2429     ** of the scan loop.
2430     */
2431     case SRT_Mem: {
2432       assert( pIn->nSdst==1 );
2433       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
2434       /* The LIMIT clause will jump out of the loop for us */
2435       break;
2436     }
2437 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
2438 
2439     /* The results are stored in a sequence of registers
2440     ** starting at pDest->iSdst.  Then the co-routine yields.
2441     */
2442     case SRT_Coroutine: {
2443       if( pDest->iSdst==0 ){
2444         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
2445         pDest->nSdst = pIn->nSdst;
2446       }
2447       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
2448       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
2449       break;
2450     }
2451 
2452     /* If none of the above, then the result destination must be
2453     ** SRT_Output.  This routine is never called with any other
2454     ** destination other than the ones handled above or SRT_Output.
2455     **
2456     ** For SRT_Output, results are stored in a sequence of registers.
2457     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
2458     ** return the next row of result.
2459     */
2460     default: {
2461       assert( pDest->eDest==SRT_Output );
2462       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
2463       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
2464       break;
2465     }
2466   }
2467 
2468   /* Jump to the end of the loop if the LIMIT is reached.
2469   */
2470   if( p->iLimit ){
2471     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
2472   }
2473 
2474   /* Generate the subroutine return
2475   */
2476   sqlite3VdbeResolveLabel(v, iContinue);
2477   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
2478 
2479   return addr;
2480 }
2481 
2482 /*
2483 ** Alternative compound select code generator for cases when there
2484 ** is an ORDER BY clause.
2485 **
2486 ** We assume a query of the following form:
2487 **
2488 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
2489 **
2490 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
2491 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
2492 ** co-routines.  Then run the co-routines in parallel and merge the results
2493 ** into the output.  In addition to the two coroutines (called selectA and
2494 ** selectB) there are 7 subroutines:
2495 **
2496 **    outA:    Move the output of the selectA coroutine into the output
2497 **             of the compound query.
2498 **
2499 **    outB:    Move the output of the selectB coroutine into the output
2500 **             of the compound query.  (Only generated for UNION and
2501 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
2502 **             appears only in B.)
2503 **
2504 **    AltB:    Called when there is data from both coroutines and A<B.
2505 **
2506 **    AeqB:    Called when there is data from both coroutines and A==B.
2507 **
2508 **    AgtB:    Called when there is data from both coroutines and A>B.
2509 **
2510 **    EofA:    Called when data is exhausted from selectA.
2511 **
2512 **    EofB:    Called when data is exhausted from selectB.
2513 **
2514 ** The implementation of the latter five subroutines depend on which
2515 ** <operator> is used:
2516 **
2517 **
2518 **             UNION ALL         UNION            EXCEPT          INTERSECT
2519 **          -------------  -----------------  --------------  -----------------
2520 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
2521 **
2522 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
2523 **
2524 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
2525 **
2526 **   EofA:   outB, nextB      outB, nextB          halt             halt
2527 **
2528 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
2529 **
2530 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
2531 ** causes an immediate jump to EofA and an EOF on B following nextB causes
2532 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
2533 ** following nextX causes a jump to the end of the select processing.
2534 **
2535 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
2536 ** within the output subroutine.  The regPrev register set holds the previously
2537 ** output value.  A comparison is made against this value and the output
2538 ** is skipped if the next results would be the same as the previous.
2539 **
2540 ** The implementation plan is to implement the two coroutines and seven
2541 ** subroutines first, then put the control logic at the bottom.  Like this:
2542 **
2543 **          goto Init
2544 **     coA: coroutine for left query (A)
2545 **     coB: coroutine for right query (B)
2546 **    outA: output one row of A
2547 **    outB: output one row of B (UNION and UNION ALL only)
2548 **    EofA: ...
2549 **    EofB: ...
2550 **    AltB: ...
2551 **    AeqB: ...
2552 **    AgtB: ...
2553 **    Init: initialize coroutine registers
2554 **          yield coA
2555 **          if eof(A) goto EofA
2556 **          yield coB
2557 **          if eof(B) goto EofB
2558 **    Cmpr: Compare A, B
2559 **          Jump AltB, AeqB, AgtB
2560 **     End: ...
2561 **
2562 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
2563 ** actually called using Gosub and they do not Return.  EofA and EofB loop
2564 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
2565 ** and AgtB jump to either L2 or to one of EofA or EofB.
2566 */
2567 #ifndef SQLITE_OMIT_COMPOUND_SELECT
2568 static int multiSelectOrderBy(
2569   Parse *pParse,        /* Parsing context */
2570   Select *p,            /* The right-most of SELECTs to be coded */
2571   SelectDest *pDest     /* What to do with query results */
2572 ){
2573   int i, j;             /* Loop counters */
2574   Select *pPrior;       /* Another SELECT immediately to our left */
2575   Vdbe *v;              /* Generate code to this VDBE */
2576   SelectDest destA;     /* Destination for coroutine A */
2577   SelectDest destB;     /* Destination for coroutine B */
2578   int regAddrA;         /* Address register for select-A coroutine */
2579   int regAddrB;         /* Address register for select-B coroutine */
2580   int addrSelectA;      /* Address of the select-A coroutine */
2581   int addrSelectB;      /* Address of the select-B coroutine */
2582   int regOutA;          /* Address register for the output-A subroutine */
2583   int regOutB;          /* Address register for the output-B subroutine */
2584   int addrOutA;         /* Address of the output-A subroutine */
2585   int addrOutB = 0;     /* Address of the output-B subroutine */
2586   int addrEofA;         /* Address of the select-A-exhausted subroutine */
2587   int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
2588   int addrEofB;         /* Address of the select-B-exhausted subroutine */
2589   int addrAltB;         /* Address of the A<B subroutine */
2590   int addrAeqB;         /* Address of the A==B subroutine */
2591   int addrAgtB;         /* Address of the A>B subroutine */
2592   int regLimitA;        /* Limit register for select-A */
2593   int regLimitB;        /* Limit register for select-A */
2594   int regPrev;          /* A range of registers to hold previous output */
2595   int savedLimit;       /* Saved value of p->iLimit */
2596   int savedOffset;      /* Saved value of p->iOffset */
2597   int labelCmpr;        /* Label for the start of the merge algorithm */
2598   int labelEnd;         /* Label for the end of the overall SELECT stmt */
2599   int j1;               /* Jump instructions that get retargetted */
2600   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
2601   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
2602   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
2603   sqlite3 *db;          /* Database connection */
2604   ExprList *pOrderBy;   /* The ORDER BY clause */
2605   int nOrderBy;         /* Number of terms in the ORDER BY clause */
2606   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
2607 #ifndef SQLITE_OMIT_EXPLAIN
2608   int iSub1;            /* EQP id of left-hand query */
2609   int iSub2;            /* EQP id of right-hand query */
2610 #endif
2611 
2612   assert( p->pOrderBy!=0 );
2613   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
2614   db = pParse->db;
2615   v = pParse->pVdbe;
2616   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
2617   labelEnd = sqlite3VdbeMakeLabel(v);
2618   labelCmpr = sqlite3VdbeMakeLabel(v);
2619 
2620 
2621   /* Patch up the ORDER BY clause
2622   */
2623   op = p->op;
2624   pPrior = p->pPrior;
2625   assert( pPrior->pOrderBy==0 );
2626   pOrderBy = p->pOrderBy;
2627   assert( pOrderBy );
2628   nOrderBy = pOrderBy->nExpr;
2629 
2630   /* For operators other than UNION ALL we have to make sure that
2631   ** the ORDER BY clause covers every term of the result set.  Add
2632   ** terms to the ORDER BY clause as necessary.
2633   */
2634   if( op!=TK_ALL ){
2635     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
2636       struct ExprList_item *pItem;
2637       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
2638         assert( pItem->u.x.iOrderByCol>0 );
2639         if( pItem->u.x.iOrderByCol==i ) break;
2640       }
2641       if( j==nOrderBy ){
2642         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
2643         if( pNew==0 ) return SQLITE_NOMEM;
2644         pNew->flags |= EP_IntValue;
2645         pNew->u.iValue = i;
2646         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
2647         if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
2648       }
2649     }
2650   }
2651 
2652   /* Compute the comparison permutation and keyinfo that is used with
2653   ** the permutation used to determine if the next
2654   ** row of results comes from selectA or selectB.  Also add explicit
2655   ** collations to the ORDER BY clause terms so that when the subqueries
2656   ** to the right and the left are evaluated, they use the correct
2657   ** collation.
2658   */
2659   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
2660   if( aPermute ){
2661     struct ExprList_item *pItem;
2662     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
2663       assert( pItem->u.x.iOrderByCol>0
2664           && pItem->u.x.iOrderByCol<=p->pEList->nExpr );
2665       aPermute[i] = pItem->u.x.iOrderByCol - 1;
2666     }
2667     pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
2668   }else{
2669     pKeyMerge = 0;
2670   }
2671 
2672   /* Reattach the ORDER BY clause to the query.
2673   */
2674   p->pOrderBy = pOrderBy;
2675   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
2676 
2677   /* Allocate a range of temporary registers and the KeyInfo needed
2678   ** for the logic that removes duplicate result rows when the
2679   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
2680   */
2681   if( op==TK_ALL ){
2682     regPrev = 0;
2683   }else{
2684     int nExpr = p->pEList->nExpr;
2685     assert( nOrderBy>=nExpr || db->mallocFailed );
2686     regPrev = pParse->nMem+1;
2687     pParse->nMem += nExpr+1;
2688     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
2689     pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
2690     if( pKeyDup ){
2691       assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
2692       for(i=0; i<nExpr; i++){
2693         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
2694         pKeyDup->aSortOrder[i] = 0;
2695       }
2696     }
2697   }
2698 
2699   /* Separate the left and the right query from one another
2700   */
2701   p->pPrior = 0;
2702   pPrior->pNext = 0;
2703   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
2704   if( pPrior->pPrior==0 ){
2705     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
2706   }
2707 
2708   /* Compute the limit registers */
2709   computeLimitRegisters(pParse, p, labelEnd);
2710   if( p->iLimit && op==TK_ALL ){
2711     regLimitA = ++pParse->nMem;
2712     regLimitB = ++pParse->nMem;
2713     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
2714                                   regLimitA);
2715     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
2716   }else{
2717     regLimitA = regLimitB = 0;
2718   }
2719   sqlite3ExprDelete(db, p->pLimit);
2720   p->pLimit = 0;
2721   sqlite3ExprDelete(db, p->pOffset);
2722   p->pOffset = 0;
2723 
2724   regAddrA = ++pParse->nMem;
2725   regAddrB = ++pParse->nMem;
2726   regOutA = ++pParse->nMem;
2727   regOutB = ++pParse->nMem;
2728   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
2729   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
2730 
2731   /* Generate a coroutine to evaluate the SELECT statement to the
2732   ** left of the compound operator - the "A" select.
2733   */
2734   addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
2735   j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
2736   VdbeComment((v, "left SELECT"));
2737   pPrior->iLimit = regLimitA;
2738   explainSetInteger(iSub1, pParse->iNextSelectId);
2739   sqlite3Select(pParse, pPrior, &destA);
2740   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
2741   sqlite3VdbeJumpHere(v, j1);
2742 
2743   /* Generate a coroutine to evaluate the SELECT statement on
2744   ** the right - the "B" select
2745   */
2746   addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
2747   j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
2748   VdbeComment((v, "right SELECT"));
2749   savedLimit = p->iLimit;
2750   savedOffset = p->iOffset;
2751   p->iLimit = regLimitB;
2752   p->iOffset = 0;
2753   explainSetInteger(iSub2, pParse->iNextSelectId);
2754   sqlite3Select(pParse, p, &destB);
2755   p->iLimit = savedLimit;
2756   p->iOffset = savedOffset;
2757   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
2758 
2759   /* Generate a subroutine that outputs the current row of the A
2760   ** select as the next output row of the compound select.
2761   */
2762   VdbeNoopComment((v, "Output routine for A"));
2763   addrOutA = generateOutputSubroutine(pParse,
2764                  p, &destA, pDest, regOutA,
2765                  regPrev, pKeyDup, labelEnd);
2766 
2767   /* Generate a subroutine that outputs the current row of the B
2768   ** select as the next output row of the compound select.
2769   */
2770   if( op==TK_ALL || op==TK_UNION ){
2771     VdbeNoopComment((v, "Output routine for B"));
2772     addrOutB = generateOutputSubroutine(pParse,
2773                  p, &destB, pDest, regOutB,
2774                  regPrev, pKeyDup, labelEnd);
2775   }
2776   sqlite3KeyInfoUnref(pKeyDup);
2777 
2778   /* Generate a subroutine to run when the results from select A
2779   ** are exhausted and only data in select B remains.
2780   */
2781   if( op==TK_EXCEPT || op==TK_INTERSECT ){
2782     addrEofA_noB = addrEofA = labelEnd;
2783   }else{
2784     VdbeNoopComment((v, "eof-A subroutine"));
2785     addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
2786     addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
2787     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
2788     p->nSelectRow += pPrior->nSelectRow;
2789   }
2790 
2791   /* Generate a subroutine to run when the results from select B
2792   ** are exhausted and only data in select A remains.
2793   */
2794   if( op==TK_INTERSECT ){
2795     addrEofB = addrEofA;
2796     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
2797   }else{
2798     VdbeNoopComment((v, "eof-B subroutine"));
2799     addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
2800     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd);
2801     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
2802   }
2803 
2804   /* Generate code to handle the case of A<B
2805   */
2806   VdbeNoopComment((v, "A-lt-B subroutine"));
2807   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
2808   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA);
2809   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2810 
2811   /* Generate code to handle the case of A==B
2812   */
2813   if( op==TK_ALL ){
2814     addrAeqB = addrAltB;
2815   }else if( op==TK_INTERSECT ){
2816     addrAeqB = addrAltB;
2817     addrAltB++;
2818   }else{
2819     VdbeNoopComment((v, "A-eq-B subroutine"));
2820     addrAeqB =
2821     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA);
2822     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2823   }
2824 
2825   /* Generate code to handle the case of A>B
2826   */
2827   VdbeNoopComment((v, "A-gt-B subroutine"));
2828   addrAgtB = sqlite3VdbeCurrentAddr(v);
2829   if( op==TK_ALL || op==TK_UNION ){
2830     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
2831   }
2832   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB);
2833   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2834 
2835   /* This code runs once to initialize everything.
2836   */
2837   sqlite3VdbeJumpHere(v, j1);
2838   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB);
2839   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB);
2840 
2841   /* Implement the main merge loop
2842   */
2843   sqlite3VdbeResolveLabel(v, labelCmpr);
2844   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
2845   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
2846                          (char*)pKeyMerge, P4_KEYINFO);
2847   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
2848   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
2849 
2850   /* Jump to the this point in order to terminate the query.
2851   */
2852   sqlite3VdbeResolveLabel(v, labelEnd);
2853 
2854   /* Set the number of output columns
2855   */
2856   if( pDest->eDest==SRT_Output ){
2857     Select *pFirst = pPrior;
2858     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
2859     generateColumnNames(pParse, 0, pFirst->pEList);
2860   }
2861 
2862   /* Reassembly the compound query so that it will be freed correctly
2863   ** by the calling function */
2864   if( p->pPrior ){
2865     sqlite3SelectDelete(db, p->pPrior);
2866   }
2867   p->pPrior = pPrior;
2868   pPrior->pNext = p;
2869 
2870   /*** TBD:  Insert subroutine calls to close cursors on incomplete
2871   **** subqueries ****/
2872   explainComposite(pParse, p->op, iSub1, iSub2, 0);
2873   return SQLITE_OK;
2874 }
2875 #endif
2876 
2877 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
2878 /* Forward Declarations */
2879 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
2880 static void substSelect(sqlite3*, Select *, int, ExprList *);
2881 
2882 /*
2883 ** Scan through the expression pExpr.  Replace every reference to
2884 ** a column in table number iTable with a copy of the iColumn-th
2885 ** entry in pEList.  (But leave references to the ROWID column
2886 ** unchanged.)
2887 **
2888 ** This routine is part of the flattening procedure.  A subquery
2889 ** whose result set is defined by pEList appears as entry in the
2890 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
2891 ** FORM clause entry is iTable.  This routine make the necessary
2892 ** changes to pExpr so that it refers directly to the source table
2893 ** of the subquery rather the result set of the subquery.
2894 */
2895 static Expr *substExpr(
2896   sqlite3 *db,        /* Report malloc errors to this connection */
2897   Expr *pExpr,        /* Expr in which substitution occurs */
2898   int iTable,         /* Table to be substituted */
2899   ExprList *pEList    /* Substitute expressions */
2900 ){
2901   if( pExpr==0 ) return 0;
2902   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
2903     if( pExpr->iColumn<0 ){
2904       pExpr->op = TK_NULL;
2905     }else{
2906       Expr *pNew;
2907       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
2908       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
2909       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
2910       sqlite3ExprDelete(db, pExpr);
2911       pExpr = pNew;
2912     }
2913   }else{
2914     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
2915     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
2916     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2917       substSelect(db, pExpr->x.pSelect, iTable, pEList);
2918     }else{
2919       substExprList(db, pExpr->x.pList, iTable, pEList);
2920     }
2921   }
2922   return pExpr;
2923 }
2924 static void substExprList(
2925   sqlite3 *db,         /* Report malloc errors here */
2926   ExprList *pList,     /* List to scan and in which to make substitutes */
2927   int iTable,          /* Table to be substituted */
2928   ExprList *pEList     /* Substitute values */
2929 ){
2930   int i;
2931   if( pList==0 ) return;
2932   for(i=0; i<pList->nExpr; i++){
2933     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
2934   }
2935 }
2936 static void substSelect(
2937   sqlite3 *db,         /* Report malloc errors here */
2938   Select *p,           /* SELECT statement in which to make substitutions */
2939   int iTable,          /* Table to be replaced */
2940   ExprList *pEList     /* Substitute values */
2941 ){
2942   SrcList *pSrc;
2943   struct SrcList_item *pItem;
2944   int i;
2945   if( !p ) return;
2946   substExprList(db, p->pEList, iTable, pEList);
2947   substExprList(db, p->pGroupBy, iTable, pEList);
2948   substExprList(db, p->pOrderBy, iTable, pEList);
2949   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
2950   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
2951   substSelect(db, p->pPrior, iTable, pEList);
2952   pSrc = p->pSrc;
2953   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
2954   if( ALWAYS(pSrc) ){
2955     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
2956       substSelect(db, pItem->pSelect, iTable, pEList);
2957     }
2958   }
2959 }
2960 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
2961 
2962 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
2963 /*
2964 ** This routine attempts to flatten subqueries as a performance optimization.
2965 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
2966 **
2967 ** To understand the concept of flattening, consider the following
2968 ** query:
2969 **
2970 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
2971 **
2972 ** The default way of implementing this query is to execute the
2973 ** subquery first and store the results in a temporary table, then
2974 ** run the outer query on that temporary table.  This requires two
2975 ** passes over the data.  Furthermore, because the temporary table
2976 ** has no indices, the WHERE clause on the outer query cannot be
2977 ** optimized.
2978 **
2979 ** This routine attempts to rewrite queries such as the above into
2980 ** a single flat select, like this:
2981 **
2982 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
2983 **
2984 ** The code generated for this simpification gives the same result
2985 ** but only has to scan the data once.  And because indices might
2986 ** exist on the table t1, a complete scan of the data might be
2987 ** avoided.
2988 **
2989 ** Flattening is only attempted if all of the following are true:
2990 **
2991 **   (1)  The subquery and the outer query do not both use aggregates.
2992 **
2993 **   (2)  The subquery is not an aggregate or the outer query is not a join.
2994 **
2995 **   (3)  The subquery is not the right operand of a left outer join
2996 **        (Originally ticket #306.  Strengthened by ticket #3300)
2997 **
2998 **   (4)  The subquery is not DISTINCT.
2999 **
3000 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
3001 **        sub-queries that were excluded from this optimization. Restriction
3002 **        (4) has since been expanded to exclude all DISTINCT subqueries.
3003 **
3004 **   (6)  The subquery does not use aggregates or the outer query is not
3005 **        DISTINCT.
3006 **
3007 **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
3008 **        A FROM clause, consider adding a FROM close with the special
3009 **        table sqlite_once that consists of a single row containing a
3010 **        single NULL.
3011 **
3012 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
3013 **
3014 **   (9)  The subquery does not use LIMIT or the outer query does not use
3015 **        aggregates.
3016 **
3017 **  (10)  The subquery does not use aggregates or the outer query does not
3018 **        use LIMIT.
3019 **
3020 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
3021 **
3022 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
3023 **        a separate restriction deriving from ticket #350.
3024 **
3025 **  (13)  The subquery and outer query do not both use LIMIT.
3026 **
3027 **  (14)  The subquery does not use OFFSET.
3028 **
3029 **  (15)  The outer query is not part of a compound select or the
3030 **        subquery does not have a LIMIT clause.
3031 **        (See ticket #2339 and ticket [02a8e81d44]).
3032 **
3033 **  (16)  The outer query is not an aggregate or the subquery does
3034 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
3035 **        until we introduced the group_concat() function.
3036 **
3037 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
3038 **        compound clause made up entirely of non-aggregate queries, and
3039 **        the parent query:
3040 **
3041 **          * is not itself part of a compound select,
3042 **          * is not an aggregate or DISTINCT query, and
3043 **          * is not a join
3044 **
3045 **        The parent and sub-query may contain WHERE clauses. Subject to
3046 **        rules (11), (13) and (14), they may also contain ORDER BY,
3047 **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
3048 **        operator other than UNION ALL because all the other compound
3049 **        operators have an implied DISTINCT which is disallowed by
3050 **        restriction (4).
3051 **
3052 **        Also, each component of the sub-query must return the same number
3053 **        of result columns. This is actually a requirement for any compound
3054 **        SELECT statement, but all the code here does is make sure that no
3055 **        such (illegal) sub-query is flattened. The caller will detect the
3056 **        syntax error and return a detailed message.
3057 **
3058 **  (18)  If the sub-query is a compound select, then all terms of the
3059 **        ORDER by clause of the parent must be simple references to
3060 **        columns of the sub-query.
3061 **
3062 **  (19)  The subquery does not use LIMIT or the outer query does not
3063 **        have a WHERE clause.
3064 **
3065 **  (20)  If the sub-query is a compound select, then it must not use
3066 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
3067 **        somewhat by saying that the terms of the ORDER BY clause must
3068 **        appear as unmodified result columns in the outer query.  But we
3069 **        have other optimizations in mind to deal with that case.
3070 **
3071 **  (21)  The subquery does not use LIMIT or the outer query is not
3072 **        DISTINCT.  (See ticket [752e1646fc]).
3073 **
3074 **  (22)  The subquery is not a recursive CTE.
3075 **
3076 **  (23)  The parent is not a recursive CTE, or the sub-query is not a
3077 **        compound query. This restriction is because transforming the
3078 **        parent to a compound query confuses the code that handles
3079 **        recursive queries in multiSelect().
3080 **
3081 **
3082 ** In this routine, the "p" parameter is a pointer to the outer query.
3083 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
3084 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
3085 **
3086 ** If flattening is not attempted, this routine is a no-op and returns 0.
3087 ** If flattening is attempted this routine returns 1.
3088 **
3089 ** All of the expression analysis must occur on both the outer query and
3090 ** the subquery before this routine runs.
3091 */
3092 static int flattenSubquery(
3093   Parse *pParse,       /* Parsing context */
3094   Select *p,           /* The parent or outer SELECT statement */
3095   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
3096   int isAgg,           /* True if outer SELECT uses aggregate functions */
3097   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
3098 ){
3099   const char *zSavedAuthContext = pParse->zAuthContext;
3100   Select *pParent;
3101   Select *pSub;       /* The inner query or "subquery" */
3102   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
3103   SrcList *pSrc;      /* The FROM clause of the outer query */
3104   SrcList *pSubSrc;   /* The FROM clause of the subquery */
3105   ExprList *pList;    /* The result set of the outer query */
3106   int iParent;        /* VDBE cursor number of the pSub result set temp table */
3107   int i;              /* Loop counter */
3108   Expr *pWhere;                    /* The WHERE clause */
3109   struct SrcList_item *pSubitem;   /* The subquery */
3110   sqlite3 *db = pParse->db;
3111 
3112   /* Check to see if flattening is permitted.  Return 0 if not.
3113   */
3114   assert( p!=0 );
3115   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
3116   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
3117   pSrc = p->pSrc;
3118   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
3119   pSubitem = &pSrc->a[iFrom];
3120   iParent = pSubitem->iCursor;
3121   pSub = pSubitem->pSelect;
3122   assert( pSub!=0 );
3123   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
3124   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
3125   pSubSrc = pSub->pSrc;
3126   assert( pSubSrc );
3127   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
3128   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
3129   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
3130   ** became arbitrary expressions, we were forced to add restrictions (13)
3131   ** and (14). */
3132   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
3133   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
3134   if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
3135     return 0;                                            /* Restriction (15) */
3136   }
3137   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
3138   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
3139   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
3140      return 0;         /* Restrictions (8)(9) */
3141   }
3142   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
3143      return 0;         /* Restriction (6)  */
3144   }
3145   if( p->pOrderBy && pSub->pOrderBy ){
3146      return 0;                                           /* Restriction (11) */
3147   }
3148   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
3149   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
3150   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
3151      return 0;         /* Restriction (21) */
3152   }
3153   if( pSub->selFlags & SF_Recursive ) return 0;          /* Restriction (22)  */
3154   if( (p->selFlags & SF_Recursive) && pSub->pPrior ) return 0;       /* (23)  */
3155 
3156   /* OBSOLETE COMMENT 1:
3157   ** Restriction 3:  If the subquery is a join, make sure the subquery is
3158   ** not used as the right operand of an outer join.  Examples of why this
3159   ** is not allowed:
3160   **
3161   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
3162   **
3163   ** If we flatten the above, we would get
3164   **
3165   **         (t1 LEFT OUTER JOIN t2) JOIN t3
3166   **
3167   ** which is not at all the same thing.
3168   **
3169   ** OBSOLETE COMMENT 2:
3170   ** Restriction 12:  If the subquery is the right operand of a left outer
3171   ** join, make sure the subquery has no WHERE clause.
3172   ** An examples of why this is not allowed:
3173   **
3174   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
3175   **
3176   ** If we flatten the above, we would get
3177   **
3178   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
3179   **
3180   ** But the t2.x>0 test will always fail on a NULL row of t2, which
3181   ** effectively converts the OUTER JOIN into an INNER JOIN.
3182   **
3183   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
3184   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
3185   ** is fraught with danger.  Best to avoid the whole thing.  If the
3186   ** subquery is the right term of a LEFT JOIN, then do not flatten.
3187   */
3188   if( (pSubitem->jointype & JT_OUTER)!=0 ){
3189     return 0;
3190   }
3191 
3192   /* Restriction 17: If the sub-query is a compound SELECT, then it must
3193   ** use only the UNION ALL operator. And none of the simple select queries
3194   ** that make up the compound SELECT are allowed to be aggregate or distinct
3195   ** queries.
3196   */
3197   if( pSub->pPrior ){
3198     if( pSub->pOrderBy ){
3199       return 0;  /* Restriction 20 */
3200     }
3201     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
3202       return 0;
3203     }
3204     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
3205       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
3206       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
3207       assert( pSub->pSrc!=0 );
3208       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
3209        || (pSub1->pPrior && pSub1->op!=TK_ALL)
3210        || pSub1->pSrc->nSrc<1
3211        || pSub->pEList->nExpr!=pSub1->pEList->nExpr
3212       ){
3213         return 0;
3214       }
3215       testcase( pSub1->pSrc->nSrc>1 );
3216     }
3217 
3218     /* Restriction 18. */
3219     if( p->pOrderBy ){
3220       int ii;
3221       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
3222         if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
3223       }
3224     }
3225   }
3226 
3227   /***** If we reach this point, flattening is permitted. *****/
3228 
3229   /* Authorize the subquery */
3230   pParse->zAuthContext = pSubitem->zName;
3231   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
3232   testcase( i==SQLITE_DENY );
3233   pParse->zAuthContext = zSavedAuthContext;
3234 
3235   /* If the sub-query is a compound SELECT statement, then (by restrictions
3236   ** 17 and 18 above) it must be a UNION ALL and the parent query must
3237   ** be of the form:
3238   **
3239   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
3240   **
3241   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
3242   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
3243   ** OFFSET clauses and joins them to the left-hand-side of the original
3244   ** using UNION ALL operators. In this case N is the number of simple
3245   ** select statements in the compound sub-query.
3246   **
3247   ** Example:
3248   **
3249   **     SELECT a+1 FROM (
3250   **        SELECT x FROM tab
3251   **        UNION ALL
3252   **        SELECT y FROM tab
3253   **        UNION ALL
3254   **        SELECT abs(z*2) FROM tab2
3255   **     ) WHERE a!=5 ORDER BY 1
3256   **
3257   ** Transformed into:
3258   **
3259   **     SELECT x+1 FROM tab WHERE x+1!=5
3260   **     UNION ALL
3261   **     SELECT y+1 FROM tab WHERE y+1!=5
3262   **     UNION ALL
3263   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
3264   **     ORDER BY 1
3265   **
3266   ** We call this the "compound-subquery flattening".
3267   */
3268   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
3269     Select *pNew;
3270     ExprList *pOrderBy = p->pOrderBy;
3271     Expr *pLimit = p->pLimit;
3272     Expr *pOffset = p->pOffset;
3273     Select *pPrior = p->pPrior;
3274     p->pOrderBy = 0;
3275     p->pSrc = 0;
3276     p->pPrior = 0;
3277     p->pLimit = 0;
3278     p->pOffset = 0;
3279     pNew = sqlite3SelectDup(db, p, 0);
3280     p->pOffset = pOffset;
3281     p->pLimit = pLimit;
3282     p->pOrderBy = pOrderBy;
3283     p->pSrc = pSrc;
3284     p->op = TK_ALL;
3285     if( pNew==0 ){
3286       p->pPrior = pPrior;
3287     }else{
3288       pNew->pPrior = pPrior;
3289       if( pPrior ) pPrior->pNext = pNew;
3290       pNew->pNext = p;
3291       p->pPrior = pNew;
3292     }
3293     if( db->mallocFailed ) return 1;
3294   }
3295 
3296   /* Begin flattening the iFrom-th entry of the FROM clause
3297   ** in the outer query.
3298   */
3299   pSub = pSub1 = pSubitem->pSelect;
3300 
3301   /* Delete the transient table structure associated with the
3302   ** subquery
3303   */
3304   sqlite3DbFree(db, pSubitem->zDatabase);
3305   sqlite3DbFree(db, pSubitem->zName);
3306   sqlite3DbFree(db, pSubitem->zAlias);
3307   pSubitem->zDatabase = 0;
3308   pSubitem->zName = 0;
3309   pSubitem->zAlias = 0;
3310   pSubitem->pSelect = 0;
3311 
3312   /* Defer deleting the Table object associated with the
3313   ** subquery until code generation is
3314   ** complete, since there may still exist Expr.pTab entries that
3315   ** refer to the subquery even after flattening.  Ticket #3346.
3316   **
3317   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
3318   */
3319   if( ALWAYS(pSubitem->pTab!=0) ){
3320     Table *pTabToDel = pSubitem->pTab;
3321     if( pTabToDel->nRef==1 ){
3322       Parse *pToplevel = sqlite3ParseToplevel(pParse);
3323       pTabToDel->pNextZombie = pToplevel->pZombieTab;
3324       pToplevel->pZombieTab = pTabToDel;
3325     }else{
3326       pTabToDel->nRef--;
3327     }
3328     pSubitem->pTab = 0;
3329   }
3330 
3331   /* The following loop runs once for each term in a compound-subquery
3332   ** flattening (as described above).  If we are doing a different kind
3333   ** of flattening - a flattening other than a compound-subquery flattening -
3334   ** then this loop only runs once.
3335   **
3336   ** This loop moves all of the FROM elements of the subquery into the
3337   ** the FROM clause of the outer query.  Before doing this, remember
3338   ** the cursor number for the original outer query FROM element in
3339   ** iParent.  The iParent cursor will never be used.  Subsequent code
3340   ** will scan expressions looking for iParent references and replace
3341   ** those references with expressions that resolve to the subquery FROM
3342   ** elements we are now copying in.
3343   */
3344   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
3345     int nSubSrc;
3346     u8 jointype = 0;
3347     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
3348     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
3349     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
3350 
3351     if( pSrc ){
3352       assert( pParent==p );  /* First time through the loop */
3353       jointype = pSubitem->jointype;
3354     }else{
3355       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
3356       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
3357       if( pSrc==0 ){
3358         assert( db->mallocFailed );
3359         break;
3360       }
3361     }
3362 
3363     /* The subquery uses a single slot of the FROM clause of the outer
3364     ** query.  If the subquery has more than one element in its FROM clause,
3365     ** then expand the outer query to make space for it to hold all elements
3366     ** of the subquery.
3367     **
3368     ** Example:
3369     **
3370     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
3371     **
3372     ** The outer query has 3 slots in its FROM clause.  One slot of the
3373     ** outer query (the middle slot) is used by the subquery.  The next
3374     ** block of code will expand the out query to 4 slots.  The middle
3375     ** slot is expanded to two slots in order to make space for the
3376     ** two elements in the FROM clause of the subquery.
3377     */
3378     if( nSubSrc>1 ){
3379       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
3380       if( db->mallocFailed ){
3381         break;
3382       }
3383     }
3384 
3385     /* Transfer the FROM clause terms from the subquery into the
3386     ** outer query.
3387     */
3388     for(i=0; i<nSubSrc; i++){
3389       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
3390       pSrc->a[i+iFrom] = pSubSrc->a[i];
3391       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
3392     }
3393     pSrc->a[iFrom].jointype = jointype;
3394 
3395     /* Now begin substituting subquery result set expressions for
3396     ** references to the iParent in the outer query.
3397     **
3398     ** Example:
3399     **
3400     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
3401     **   \                     \_____________ subquery __________/          /
3402     **    \_____________________ outer query ______________________________/
3403     **
3404     ** We look at every expression in the outer query and every place we see
3405     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
3406     */
3407     pList = pParent->pEList;
3408     for(i=0; i<pList->nExpr; i++){
3409       if( pList->a[i].zName==0 ){
3410         char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
3411         sqlite3Dequote(zName);
3412         pList->a[i].zName = zName;
3413       }
3414     }
3415     substExprList(db, pParent->pEList, iParent, pSub->pEList);
3416     if( isAgg ){
3417       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
3418       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
3419     }
3420     if( pSub->pOrderBy ){
3421       assert( pParent->pOrderBy==0 );
3422       pParent->pOrderBy = pSub->pOrderBy;
3423       pSub->pOrderBy = 0;
3424     }else if( pParent->pOrderBy ){
3425       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
3426     }
3427     if( pSub->pWhere ){
3428       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
3429     }else{
3430       pWhere = 0;
3431     }
3432     if( subqueryIsAgg ){
3433       assert( pParent->pHaving==0 );
3434       pParent->pHaving = pParent->pWhere;
3435       pParent->pWhere = pWhere;
3436       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
3437       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
3438                                   sqlite3ExprDup(db, pSub->pHaving, 0));
3439       assert( pParent->pGroupBy==0 );
3440       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
3441     }else{
3442       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
3443       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
3444     }
3445 
3446     /* The flattened query is distinct if either the inner or the
3447     ** outer query is distinct.
3448     */
3449     pParent->selFlags |= pSub->selFlags & SF_Distinct;
3450 
3451     /*
3452     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
3453     **
3454     ** One is tempted to try to add a and b to combine the limits.  But this
3455     ** does not work if either limit is negative.
3456     */
3457     if( pSub->pLimit ){
3458       pParent->pLimit = pSub->pLimit;
3459       pSub->pLimit = 0;
3460     }
3461   }
3462 
3463   /* Finially, delete what is left of the subquery and return
3464   ** success.
3465   */
3466   sqlite3SelectDelete(db, pSub1);
3467 
3468   return 1;
3469 }
3470 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
3471 
3472 /*
3473 ** Based on the contents of the AggInfo structure indicated by the first
3474 ** argument, this function checks if the following are true:
3475 **
3476 **    * the query contains just a single aggregate function,
3477 **    * the aggregate function is either min() or max(), and
3478 **    * the argument to the aggregate function is a column value.
3479 **
3480 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
3481 ** is returned as appropriate. Also, *ppMinMax is set to point to the
3482 ** list of arguments passed to the aggregate before returning.
3483 **
3484 ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
3485 ** WHERE_ORDERBY_NORMAL is returned.
3486 */
3487 static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
3488   int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
3489 
3490   *ppMinMax = 0;
3491   if( pAggInfo->nFunc==1 ){
3492     Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
3493     ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
3494 
3495     assert( pExpr->op==TK_AGG_FUNCTION );
3496     if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
3497       const char *zFunc = pExpr->u.zToken;
3498       if( sqlite3StrICmp(zFunc, "min")==0 ){
3499         eRet = WHERE_ORDERBY_MIN;
3500         *ppMinMax = pEList;
3501       }else if( sqlite3StrICmp(zFunc, "max")==0 ){
3502         eRet = WHERE_ORDERBY_MAX;
3503         *ppMinMax = pEList;
3504       }
3505     }
3506   }
3507 
3508   assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
3509   return eRet;
3510 }
3511 
3512 /*
3513 ** The select statement passed as the first argument is an aggregate query.
3514 ** The second argment is the associated aggregate-info object. This
3515 ** function tests if the SELECT is of the form:
3516 **
3517 **   SELECT count(*) FROM <tbl>
3518 **
3519 ** where table is a database table, not a sub-select or view. If the query
3520 ** does match this pattern, then a pointer to the Table object representing
3521 ** <tbl> is returned. Otherwise, 0 is returned.
3522 */
3523 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
3524   Table *pTab;
3525   Expr *pExpr;
3526 
3527   assert( !p->pGroupBy );
3528 
3529   if( p->pWhere || p->pEList->nExpr!=1
3530    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
3531   ){
3532     return 0;
3533   }
3534   pTab = p->pSrc->a[0].pTab;
3535   pExpr = p->pEList->a[0].pExpr;
3536   assert( pTab && !pTab->pSelect && pExpr );
3537 
3538   if( IsVirtual(pTab) ) return 0;
3539   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
3540   if( NEVER(pAggInfo->nFunc==0) ) return 0;
3541   if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
3542   if( pExpr->flags&EP_Distinct ) return 0;
3543 
3544   return pTab;
3545 }
3546 
3547 /*
3548 ** If the source-list item passed as an argument was augmented with an
3549 ** INDEXED BY clause, then try to locate the specified index. If there
3550 ** was such a clause and the named index cannot be found, return
3551 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
3552 ** pFrom->pIndex and return SQLITE_OK.
3553 */
3554 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
3555   if( pFrom->pTab && pFrom->zIndex ){
3556     Table *pTab = pFrom->pTab;
3557     char *zIndex = pFrom->zIndex;
3558     Index *pIdx;
3559     for(pIdx=pTab->pIndex;
3560         pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
3561         pIdx=pIdx->pNext
3562     );
3563     if( !pIdx ){
3564       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
3565       pParse->checkSchema = 1;
3566       return SQLITE_ERROR;
3567     }
3568     pFrom->pIndex = pIdx;
3569   }
3570   return SQLITE_OK;
3571 }
3572 /*
3573 ** Detect compound SELECT statements that use an ORDER BY clause with
3574 ** an alternative collating sequence.
3575 **
3576 **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
3577 **
3578 ** These are rewritten as a subquery:
3579 **
3580 **    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
3581 **     ORDER BY ... COLLATE ...
3582 **
3583 ** This transformation is necessary because the multiSelectOrderBy() routine
3584 ** above that generates the code for a compound SELECT with an ORDER BY clause
3585 ** uses a merge algorithm that requires the same collating sequence on the
3586 ** result columns as on the ORDER BY clause.  See ticket
3587 ** http://www.sqlite.org/src/info/6709574d2a
3588 **
3589 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
3590 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
3591 ** there are COLLATE terms in the ORDER BY.
3592 */
3593 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
3594   int i;
3595   Select *pNew;
3596   Select *pX;
3597   sqlite3 *db;
3598   struct ExprList_item *a;
3599   SrcList *pNewSrc;
3600   Parse *pParse;
3601   Token dummy;
3602 
3603   if( p->pPrior==0 ) return WRC_Continue;
3604   if( p->pOrderBy==0 ) return WRC_Continue;
3605   for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
3606   if( pX==0 ) return WRC_Continue;
3607   a = p->pOrderBy->a;
3608   for(i=p->pOrderBy->nExpr-1; i>=0; i--){
3609     if( a[i].pExpr->flags & EP_Collate ) break;
3610   }
3611   if( i<0 ) return WRC_Continue;
3612 
3613   /* If we reach this point, that means the transformation is required. */
3614 
3615   pParse = pWalker->pParse;
3616   db = pParse->db;
3617   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
3618   if( pNew==0 ) return WRC_Abort;
3619   memset(&dummy, 0, sizeof(dummy));
3620   pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
3621   if( pNewSrc==0 ) return WRC_Abort;
3622   *pNew = *p;
3623   p->pSrc = pNewSrc;
3624   p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
3625   p->op = TK_SELECT;
3626   p->pWhere = 0;
3627   pNew->pGroupBy = 0;
3628   pNew->pHaving = 0;
3629   pNew->pOrderBy = 0;
3630   p->pPrior = 0;
3631   p->pNext = 0;
3632   p->selFlags &= ~SF_Compound;
3633   assert( pNew->pPrior!=0 );
3634   pNew->pPrior->pNext = pNew;
3635   pNew->pLimit = 0;
3636   pNew->pOffset = 0;
3637   return WRC_Continue;
3638 }
3639 
3640 #ifndef SQLITE_OMIT_CTE
3641 /*
3642 ** Argument pWith (which may be NULL) points to a linked list of nested
3643 ** WITH contexts, from inner to outermost. If the table identified by
3644 ** FROM clause element pItem is really a common-table-expression (CTE)
3645 ** then return a pointer to the CTE definition for that table. Otherwise
3646 ** return NULL.
3647 **
3648 ** If a non-NULL value is returned, set *ppContext to point to the With
3649 ** object that the returned CTE belongs to.
3650 */
3651 static struct Cte *searchWith(
3652   With *pWith,                    /* Current outermost WITH clause */
3653   struct SrcList_item *pItem,     /* FROM clause element to resolve */
3654   With **ppContext                /* OUT: WITH clause return value belongs to */
3655 ){
3656   const char *zName;
3657   if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
3658     With *p;
3659     for(p=pWith; p; p=p->pOuter){
3660       int i;
3661       for(i=0; i<p->nCte; i++){
3662         if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
3663           *ppContext = p;
3664           return &p->a[i];
3665         }
3666       }
3667     }
3668   }
3669   return 0;
3670 }
3671 
3672 /* The code generator maintains a stack of active WITH clauses
3673 ** with the inner-most WITH clause being at the top of the stack.
3674 **
3675 ** This routine pushes the WITH clause passed as the second argument
3676 ** onto the top of the stack. If argument bFree is true, then this
3677 ** WITH clause will never be popped from the stack. In this case it
3678 ** should be freed along with the Parse object. In other cases, when
3679 ** bFree==0, the With object will be freed along with the SELECT
3680 ** statement with which it is associated.
3681 */
3682 void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
3683   assert( bFree==0 || pParse->pWith==0 );
3684   if( pWith ){
3685     pWith->pOuter = pParse->pWith;
3686     pParse->pWith = pWith;
3687     pParse->bFreeWith = bFree;
3688   }
3689 }
3690 
3691 /*
3692 ** This function checks if argument pFrom refers to a CTE declared by
3693 ** a WITH clause on the stack currently maintained by the parser. And,
3694 ** if currently processing a CTE expression, if it is a recursive
3695 ** reference to the current CTE.
3696 **
3697 ** If pFrom falls into either of the two categories above, pFrom->pTab
3698 ** and other fields are populated accordingly. The caller should check
3699 ** (pFrom->pTab!=0) to determine whether or not a successful match
3700 ** was found.
3701 **
3702 ** Whether or not a match is found, SQLITE_OK is returned if no error
3703 ** occurs. If an error does occur, an error message is stored in the
3704 ** parser and some error code other than SQLITE_OK returned.
3705 */
3706 static int withExpand(
3707   Walker *pWalker,
3708   struct SrcList_item *pFrom
3709 ){
3710   Parse *pParse = pWalker->pParse;
3711   sqlite3 *db = pParse->db;
3712   struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
3713   With *pWith;                    /* WITH clause that pCte belongs to */
3714 
3715   assert( pFrom->pTab==0 );
3716 
3717   pCte = searchWith(pParse->pWith, pFrom, &pWith);
3718   if( pCte ){
3719     Table *pTab;
3720     ExprList *pEList;
3721     Select *pSel;
3722     Select *pLeft;                /* Left-most SELECT statement */
3723     int bMayRecursive;            /* True if compound joined by UNION [ALL] */
3724     With *pSavedWith;             /* Initial value of pParse->pWith */
3725 
3726     /* If pCte->zErr is non-NULL at this point, then this is an illegal
3727     ** recursive reference to CTE pCte. Leave an error in pParse and return
3728     ** early. If pCte->zErr is NULL, then this is not a recursive reference.
3729     ** In this case, proceed.  */
3730     if( pCte->zErr ){
3731       sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName);
3732       return SQLITE_ERROR;
3733     }
3734 
3735     assert( pFrom->pTab==0 );
3736     pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
3737     if( pTab==0 ) return WRC_Abort;
3738     pTab->nRef = 1;
3739     pTab->zName = sqlite3DbStrDup(db, pCte->zName);
3740     pTab->iPKey = -1;
3741     pTab->nRowEst = 1048576;
3742     pTab->tabFlags |= TF_Ephemeral;
3743     pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
3744     if( db->mallocFailed ) return SQLITE_NOMEM;
3745     assert( pFrom->pSelect );
3746 
3747     /* Check if this is a recursive CTE. */
3748     pSel = pFrom->pSelect;
3749     bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
3750     if( bMayRecursive ){
3751       int i;
3752       SrcList *pSrc = pFrom->pSelect->pSrc;
3753       for(i=0; i<pSrc->nSrc; i++){
3754         struct SrcList_item *pItem = &pSrc->a[i];
3755         if( pItem->zDatabase==0
3756          && pItem->zName!=0
3757          && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
3758           ){
3759           pItem->pTab = pTab;
3760           pItem->isRecursive = 1;
3761           pTab->nRef++;
3762           pSel->selFlags |= SF_Recursive;
3763         }
3764       }
3765     }
3766 
3767     /* Only one recursive reference is permitted. */
3768     if( pTab->nRef>2 ){
3769       sqlite3ErrorMsg(
3770           pParse, "multiple references to recursive table: %s", pCte->zName
3771       );
3772       return SQLITE_ERROR;
3773     }
3774     assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
3775 
3776     pCte->zErr = "circular reference: %s";
3777     pSavedWith = pParse->pWith;
3778     pParse->pWith = pWith;
3779     sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
3780 
3781     for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
3782     pEList = pLeft->pEList;
3783     if( pCte->pCols ){
3784       if( pEList->nExpr!=pCte->pCols->nExpr ){
3785         sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
3786             pCte->zName, pEList->nExpr, pCte->pCols->nExpr
3787         );
3788         pParse->pWith = pSavedWith;
3789         return SQLITE_ERROR;
3790       }
3791       pEList = pCte->pCols;
3792     }
3793 
3794     selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
3795     if( bMayRecursive ){
3796       if( pSel->selFlags & SF_Recursive ){
3797         pCte->zErr = "multiple recursive references: %s";
3798       }else{
3799         pCte->zErr = "recursive reference in a subquery: %s";
3800       }
3801       sqlite3WalkSelect(pWalker, pSel);
3802     }
3803     pCte->zErr = 0;
3804     pParse->pWith = pSavedWith;
3805   }
3806 
3807   return SQLITE_OK;
3808 }
3809 #endif
3810 
3811 #ifndef SQLITE_OMIT_CTE
3812 /*
3813 ** If the SELECT passed as the second argument has an associated WITH
3814 ** clause, pop it from the stack stored as part of the Parse object.
3815 **
3816 ** This function is used as the xSelectCallback2() callback by
3817 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
3818 ** names and other FROM clause elements.
3819 */
3820 static void selectPopWith(Walker *pWalker, Select *p){
3821   Parse *pParse = pWalker->pParse;
3822   With *pWith = findRightmost(p)->pWith;
3823   if( pWith!=0 ){
3824     assert( pParse->pWith==pWith );
3825     pParse->pWith = pWith->pOuter;
3826   }
3827 }
3828 #else
3829 #define selectPopWith 0
3830 #endif
3831 
3832 /*
3833 ** This routine is a Walker callback for "expanding" a SELECT statement.
3834 ** "Expanding" means to do the following:
3835 **
3836 **    (1)  Make sure VDBE cursor numbers have been assigned to every
3837 **         element of the FROM clause.
3838 **
3839 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
3840 **         defines FROM clause.  When views appear in the FROM clause,
3841 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
3842 **         that implements the view.  A copy is made of the view's SELECT
3843 **         statement so that we can freely modify or delete that statement
3844 **         without worrying about messing up the presistent representation
3845 **         of the view.
3846 **
3847 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
3848 **         on joins and the ON and USING clause of joins.
3849 **
3850 **    (4)  Scan the list of columns in the result set (pEList) looking
3851 **         for instances of the "*" operator or the TABLE.* operator.
3852 **         If found, expand each "*" to be every column in every table
3853 **         and TABLE.* to be every column in TABLE.
3854 **
3855 */
3856 static int selectExpander(Walker *pWalker, Select *p){
3857   Parse *pParse = pWalker->pParse;
3858   int i, j, k;
3859   SrcList *pTabList;
3860   ExprList *pEList;
3861   struct SrcList_item *pFrom;
3862   sqlite3 *db = pParse->db;
3863   Expr *pE, *pRight, *pExpr;
3864   u16 selFlags = p->selFlags;
3865 
3866   p->selFlags |= SF_Expanded;
3867   if( db->mallocFailed  ){
3868     return WRC_Abort;
3869   }
3870   if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
3871     return WRC_Prune;
3872   }
3873   pTabList = p->pSrc;
3874   pEList = p->pEList;
3875   sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
3876 
3877   /* Make sure cursor numbers have been assigned to all entries in
3878   ** the FROM clause of the SELECT statement.
3879   */
3880   sqlite3SrcListAssignCursors(pParse, pTabList);
3881 
3882   /* Look up every table named in the FROM clause of the select.  If
3883   ** an entry of the FROM clause is a subquery instead of a table or view,
3884   ** then create a transient table structure to describe the subquery.
3885   */
3886   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
3887     Table *pTab;
3888     assert( pFrom->isRecursive==0 || pFrom->pTab );
3889     if( pFrom->isRecursive ) continue;
3890     if( pFrom->pTab!=0 ){
3891       /* This statement has already been prepared.  There is no need
3892       ** to go further. */
3893       assert( i==0 );
3894 #ifndef SQLITE_OMIT_CTE
3895       selectPopWith(pWalker, p);
3896 #endif
3897       return WRC_Prune;
3898     }
3899 #ifndef SQLITE_OMIT_CTE
3900     if( withExpand(pWalker, pFrom) ) return WRC_Abort;
3901     if( pFrom->pTab ) {} else
3902 #endif
3903     if( pFrom->zName==0 ){
3904 #ifndef SQLITE_OMIT_SUBQUERY
3905       Select *pSel = pFrom->pSelect;
3906       /* A sub-query in the FROM clause of a SELECT */
3907       assert( pSel!=0 );
3908       assert( pFrom->pTab==0 );
3909       sqlite3WalkSelect(pWalker, pSel);
3910       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
3911       if( pTab==0 ) return WRC_Abort;
3912       pTab->nRef = 1;
3913       pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
3914       while( pSel->pPrior ){ pSel = pSel->pPrior; }
3915       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
3916       pTab->iPKey = -1;
3917       pTab->nRowEst = 1048576;
3918       pTab->tabFlags |= TF_Ephemeral;
3919 #endif
3920     }else{
3921       /* An ordinary table or view name in the FROM clause */
3922       assert( pFrom->pTab==0 );
3923       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
3924       if( pTab==0 ) return WRC_Abort;
3925       if( pTab->nRef==0xffff ){
3926         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
3927            pTab->zName);
3928         pFrom->pTab = 0;
3929         return WRC_Abort;
3930       }
3931       pTab->nRef++;
3932 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
3933       if( pTab->pSelect || IsVirtual(pTab) ){
3934         /* We reach here if the named table is a really a view */
3935         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
3936         assert( pFrom->pSelect==0 );
3937         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
3938         sqlite3WalkSelect(pWalker, pFrom->pSelect);
3939       }
3940 #endif
3941     }
3942 
3943     /* Locate the index named by the INDEXED BY clause, if any. */
3944     if( sqlite3IndexedByLookup(pParse, pFrom) ){
3945       return WRC_Abort;
3946     }
3947   }
3948 
3949   /* Process NATURAL keywords, and ON and USING clauses of joins.
3950   */
3951   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
3952     return WRC_Abort;
3953   }
3954 
3955   /* For every "*" that occurs in the column list, insert the names of
3956   ** all columns in all tables.  And for every TABLE.* insert the names
3957   ** of all columns in TABLE.  The parser inserted a special expression
3958   ** with the TK_ALL operator for each "*" that it found in the column list.
3959   ** The following code just has to locate the TK_ALL expressions and expand
3960   ** each one to the list of all columns in all tables.
3961   **
3962   ** The first loop just checks to see if there are any "*" operators
3963   ** that need expanding.
3964   */
3965   for(k=0; k<pEList->nExpr; k++){
3966     pE = pEList->a[k].pExpr;
3967     if( pE->op==TK_ALL ) break;
3968     assert( pE->op!=TK_DOT || pE->pRight!=0 );
3969     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
3970     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
3971   }
3972   if( k<pEList->nExpr ){
3973     /*
3974     ** If we get here it means the result set contains one or more "*"
3975     ** operators that need to be expanded.  Loop through each expression
3976     ** in the result set and expand them one by one.
3977     */
3978     struct ExprList_item *a = pEList->a;
3979     ExprList *pNew = 0;
3980     int flags = pParse->db->flags;
3981     int longNames = (flags & SQLITE_FullColNames)!=0
3982                       && (flags & SQLITE_ShortColNames)==0;
3983 
3984     /* When processing FROM-clause subqueries, it is always the case
3985     ** that full_column_names=OFF and short_column_names=ON.  The
3986     ** sqlite3ResultSetOfSelect() routine makes it so. */
3987     assert( (p->selFlags & SF_NestedFrom)==0
3988           || ((flags & SQLITE_FullColNames)==0 &&
3989               (flags & SQLITE_ShortColNames)!=0) );
3990 
3991     for(k=0; k<pEList->nExpr; k++){
3992       pE = a[k].pExpr;
3993       pRight = pE->pRight;
3994       assert( pE->op!=TK_DOT || pRight!=0 );
3995       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
3996         /* This particular expression does not need to be expanded.
3997         */
3998         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
3999         if( pNew ){
4000           pNew->a[pNew->nExpr-1].zName = a[k].zName;
4001           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
4002           a[k].zName = 0;
4003           a[k].zSpan = 0;
4004         }
4005         a[k].pExpr = 0;
4006       }else{
4007         /* This expression is a "*" or a "TABLE.*" and needs to be
4008         ** expanded. */
4009         int tableSeen = 0;      /* Set to 1 when TABLE matches */
4010         char *zTName = 0;       /* text of name of TABLE */
4011         if( pE->op==TK_DOT ){
4012           assert( pE->pLeft!=0 );
4013           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
4014           zTName = pE->pLeft->u.zToken;
4015         }
4016         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
4017           Table *pTab = pFrom->pTab;
4018           Select *pSub = pFrom->pSelect;
4019           char *zTabName = pFrom->zAlias;
4020           const char *zSchemaName = 0;
4021           int iDb;
4022           if( zTabName==0 ){
4023             zTabName = pTab->zName;
4024           }
4025           if( db->mallocFailed ) break;
4026           if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
4027             pSub = 0;
4028             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
4029               continue;
4030             }
4031             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
4032             zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
4033           }
4034           for(j=0; j<pTab->nCol; j++){
4035             char *zName = pTab->aCol[j].zName;
4036             char *zColname;  /* The computed column name */
4037             char *zToFree;   /* Malloced string that needs to be freed */
4038             Token sColname;  /* Computed column name as a token */
4039 
4040             assert( zName );
4041             if( zTName && pSub
4042              && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
4043             ){
4044               continue;
4045             }
4046 
4047             /* If a column is marked as 'hidden' (currently only possible
4048             ** for virtual tables), do not include it in the expanded
4049             ** result-set list.
4050             */
4051             if( IsHiddenColumn(&pTab->aCol[j]) ){
4052               assert(IsVirtual(pTab));
4053               continue;
4054             }
4055             tableSeen = 1;
4056 
4057             if( i>0 && zTName==0 ){
4058               if( (pFrom->jointype & JT_NATURAL)!=0
4059                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
4060               ){
4061                 /* In a NATURAL join, omit the join columns from the
4062                 ** table to the right of the join */
4063                 continue;
4064               }
4065               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
4066                 /* In a join with a USING clause, omit columns in the
4067                 ** using clause from the table on the right. */
4068                 continue;
4069               }
4070             }
4071             pRight = sqlite3Expr(db, TK_ID, zName);
4072             zColname = zName;
4073             zToFree = 0;
4074             if( longNames || pTabList->nSrc>1 ){
4075               Expr *pLeft;
4076               pLeft = sqlite3Expr(db, TK_ID, zTabName);
4077               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
4078               if( zSchemaName ){
4079                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
4080                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
4081               }
4082               if( longNames ){
4083                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
4084                 zToFree = zColname;
4085               }
4086             }else{
4087               pExpr = pRight;
4088             }
4089             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
4090             sColname.z = zColname;
4091             sColname.n = sqlite3Strlen30(zColname);
4092             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
4093             if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
4094               struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
4095               if( pSub ){
4096                 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
4097                 testcase( pX->zSpan==0 );
4098               }else{
4099                 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
4100                                            zSchemaName, zTabName, zColname);
4101                 testcase( pX->zSpan==0 );
4102               }
4103               pX->bSpanIsTab = 1;
4104             }
4105             sqlite3DbFree(db, zToFree);
4106           }
4107         }
4108         if( !tableSeen ){
4109           if( zTName ){
4110             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
4111           }else{
4112             sqlite3ErrorMsg(pParse, "no tables specified");
4113           }
4114         }
4115       }
4116     }
4117     sqlite3ExprListDelete(db, pEList);
4118     p->pEList = pNew;
4119   }
4120 #if SQLITE_MAX_COLUMN
4121   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
4122     sqlite3ErrorMsg(pParse, "too many columns in result set");
4123   }
4124 #endif
4125   return WRC_Continue;
4126 }
4127 
4128 /*
4129 ** No-op routine for the parse-tree walker.
4130 **
4131 ** When this routine is the Walker.xExprCallback then expression trees
4132 ** are walked without any actions being taken at each node.  Presumably,
4133 ** when this routine is used for Walker.xExprCallback then
4134 ** Walker.xSelectCallback is set to do something useful for every
4135 ** subquery in the parser tree.
4136 */
4137 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
4138   UNUSED_PARAMETER2(NotUsed, NotUsed2);
4139   return WRC_Continue;
4140 }
4141 
4142 /*
4143 ** This routine "expands" a SELECT statement and all of its subqueries.
4144 ** For additional information on what it means to "expand" a SELECT
4145 ** statement, see the comment on the selectExpand worker callback above.
4146 **
4147 ** Expanding a SELECT statement is the first step in processing a
4148 ** SELECT statement.  The SELECT statement must be expanded before
4149 ** name resolution is performed.
4150 **
4151 ** If anything goes wrong, an error message is written into pParse.
4152 ** The calling function can detect the problem by looking at pParse->nErr
4153 ** and/or pParse->db->mallocFailed.
4154 */
4155 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
4156   Walker w;
4157   memset(&w, 0, sizeof(w));
4158   w.xExprCallback = exprWalkNoop;
4159   w.pParse = pParse;
4160   if( pParse->hasCompound ){
4161     w.xSelectCallback = convertCompoundSelectToSubquery;
4162     sqlite3WalkSelect(&w, pSelect);
4163   }
4164   w.xSelectCallback = selectExpander;
4165   w.xSelectCallback2 = selectPopWith;
4166   sqlite3WalkSelect(&w, pSelect);
4167 }
4168 
4169 
4170 #ifndef SQLITE_OMIT_SUBQUERY
4171 /*
4172 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
4173 ** interface.
4174 **
4175 ** For each FROM-clause subquery, add Column.zType and Column.zColl
4176 ** information to the Table structure that represents the result set
4177 ** of that subquery.
4178 **
4179 ** The Table structure that represents the result set was constructed
4180 ** by selectExpander() but the type and collation information was omitted
4181 ** at that point because identifiers had not yet been resolved.  This
4182 ** routine is called after identifier resolution.
4183 */
4184 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
4185   Parse *pParse;
4186   int i;
4187   SrcList *pTabList;
4188   struct SrcList_item *pFrom;
4189 
4190   assert( p->selFlags & SF_Resolved );
4191   if( (p->selFlags & SF_HasTypeInfo)==0 ){
4192     p->selFlags |= SF_HasTypeInfo;
4193     pParse = pWalker->pParse;
4194     pTabList = p->pSrc;
4195     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
4196       Table *pTab = pFrom->pTab;
4197       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
4198         /* A sub-query in the FROM clause of a SELECT */
4199         Select *pSel = pFrom->pSelect;
4200         if( pSel ){
4201           while( pSel->pPrior ) pSel = pSel->pPrior;
4202           selectAddColumnTypeAndCollation(pParse, pTab, pSel);
4203         }
4204       }
4205     }
4206   }
4207 }
4208 #endif
4209 
4210 
4211 /*
4212 ** This routine adds datatype and collating sequence information to
4213 ** the Table structures of all FROM-clause subqueries in a
4214 ** SELECT statement.
4215 **
4216 ** Use this routine after name resolution.
4217 */
4218 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
4219 #ifndef SQLITE_OMIT_SUBQUERY
4220   Walker w;
4221   memset(&w, 0, sizeof(w));
4222   w.xSelectCallback2 = selectAddSubqueryTypeInfo;
4223   w.xExprCallback = exprWalkNoop;
4224   w.pParse = pParse;
4225   sqlite3WalkSelect(&w, pSelect);
4226 #endif
4227 }
4228 
4229 
4230 /*
4231 ** This routine sets up a SELECT statement for processing.  The
4232 ** following is accomplished:
4233 **
4234 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
4235 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
4236 **     *  ON and USING clauses are shifted into WHERE statements
4237 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
4238 **     *  Identifiers in expression are matched to tables.
4239 **
4240 ** This routine acts recursively on all subqueries within the SELECT.
4241 */
4242 void sqlite3SelectPrep(
4243   Parse *pParse,         /* The parser context */
4244   Select *p,             /* The SELECT statement being coded. */
4245   NameContext *pOuterNC  /* Name context for container */
4246 ){
4247   sqlite3 *db;
4248   if( NEVER(p==0) ) return;
4249   db = pParse->db;
4250   if( db->mallocFailed ) return;
4251   if( p->selFlags & SF_HasTypeInfo ) return;
4252   sqlite3SelectExpand(pParse, p);
4253   if( pParse->nErr || db->mallocFailed ) return;
4254   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
4255   if( pParse->nErr || db->mallocFailed ) return;
4256   sqlite3SelectAddTypeInfo(pParse, p);
4257 }
4258 
4259 /*
4260 ** Reset the aggregate accumulator.
4261 **
4262 ** The aggregate accumulator is a set of memory cells that hold
4263 ** intermediate results while calculating an aggregate.  This
4264 ** routine generates code that stores NULLs in all of those memory
4265 ** cells.
4266 */
4267 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
4268   Vdbe *v = pParse->pVdbe;
4269   int i;
4270   struct AggInfo_func *pFunc;
4271   int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
4272   if( nReg==0 ) return;
4273 #ifdef SQLITE_DEBUG
4274   /* Verify that all AggInfo registers are within the range specified by
4275   ** AggInfo.mnReg..AggInfo.mxReg */
4276   assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
4277   for(i=0; i<pAggInfo->nColumn; i++){
4278     assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
4279          && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
4280   }
4281   for(i=0; i<pAggInfo->nFunc; i++){
4282     assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
4283          && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
4284   }
4285 #endif
4286   sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
4287   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
4288     if( pFunc->iDistinct>=0 ){
4289       Expr *pE = pFunc->pExpr;
4290       assert( !ExprHasProperty(pE, EP_xIsSelect) );
4291       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
4292         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
4293            "argument");
4294         pFunc->iDistinct = -1;
4295       }else{
4296         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0);
4297         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
4298                           (char*)pKeyInfo, P4_KEYINFO);
4299       }
4300     }
4301   }
4302 }
4303 
4304 /*
4305 ** Invoke the OP_AggFinalize opcode for every aggregate function
4306 ** in the AggInfo structure.
4307 */
4308 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
4309   Vdbe *v = pParse->pVdbe;
4310   int i;
4311   struct AggInfo_func *pF;
4312   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
4313     ExprList *pList = pF->pExpr->x.pList;
4314     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
4315     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
4316                       (void*)pF->pFunc, P4_FUNCDEF);
4317   }
4318 }
4319 
4320 /*
4321 ** Update the accumulator memory cells for an aggregate based on
4322 ** the current cursor position.
4323 */
4324 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
4325   Vdbe *v = pParse->pVdbe;
4326   int i;
4327   int regHit = 0;
4328   int addrHitTest = 0;
4329   struct AggInfo_func *pF;
4330   struct AggInfo_col *pC;
4331 
4332   pAggInfo->directMode = 1;
4333   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
4334     int nArg;
4335     int addrNext = 0;
4336     int regAgg;
4337     ExprList *pList = pF->pExpr->x.pList;
4338     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
4339     if( pList ){
4340       nArg = pList->nExpr;
4341       regAgg = sqlite3GetTempRange(pParse, nArg);
4342       sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP);
4343     }else{
4344       nArg = 0;
4345       regAgg = 0;
4346     }
4347     if( pF->iDistinct>=0 ){
4348       addrNext = sqlite3VdbeMakeLabel(v);
4349       assert( nArg==1 );
4350       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
4351     }
4352     if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
4353       CollSeq *pColl = 0;
4354       struct ExprList_item *pItem;
4355       int j;
4356       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
4357       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
4358         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
4359       }
4360       if( !pColl ){
4361         pColl = pParse->db->pDfltColl;
4362       }
4363       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
4364       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
4365     }
4366     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
4367                       (void*)pF->pFunc, P4_FUNCDEF);
4368     sqlite3VdbeChangeP5(v, (u8)nArg);
4369     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
4370     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
4371     if( addrNext ){
4372       sqlite3VdbeResolveLabel(v, addrNext);
4373       sqlite3ExprCacheClear(pParse);
4374     }
4375   }
4376 
4377   /* Before populating the accumulator registers, clear the column cache.
4378   ** Otherwise, if any of the required column values are already present
4379   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
4380   ** to pC->iMem. But by the time the value is used, the original register
4381   ** may have been used, invalidating the underlying buffer holding the
4382   ** text or blob value. See ticket [883034dcb5].
4383   **
4384   ** Another solution would be to change the OP_SCopy used to copy cached
4385   ** values to an OP_Copy.
4386   */
4387   if( regHit ){
4388     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
4389   }
4390   sqlite3ExprCacheClear(pParse);
4391   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
4392     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
4393   }
4394   pAggInfo->directMode = 0;
4395   sqlite3ExprCacheClear(pParse);
4396   if( addrHitTest ){
4397     sqlite3VdbeJumpHere(v, addrHitTest);
4398   }
4399 }
4400 
4401 /*
4402 ** Add a single OP_Explain instruction to the VDBE to explain a simple
4403 ** count(*) query ("SELECT count(*) FROM pTab").
4404 */
4405 #ifndef SQLITE_OMIT_EXPLAIN
4406 static void explainSimpleCount(
4407   Parse *pParse,                  /* Parse context */
4408   Table *pTab,                    /* Table being queried */
4409   Index *pIdx                     /* Index used to optimize scan, or NULL */
4410 ){
4411   if( pParse->explain==2 ){
4412     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
4413         pTab->zName,
4414         pIdx ? " USING COVERING INDEX " : "",
4415         pIdx ? pIdx->zName : ""
4416     );
4417     sqlite3VdbeAddOp4(
4418         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
4419     );
4420   }
4421 }
4422 #else
4423 # define explainSimpleCount(a,b,c)
4424 #endif
4425 
4426 /*
4427 ** Generate code for the SELECT statement given in the p argument.
4428 **
4429 ** The results are returned according to the SelectDest structure.
4430 ** See comments in sqliteInt.h for further information.
4431 **
4432 ** This routine returns the number of errors.  If any errors are
4433 ** encountered, then an appropriate error message is left in
4434 ** pParse->zErrMsg.
4435 **
4436 ** This routine does NOT free the Select structure passed in.  The
4437 ** calling function needs to do that.
4438 */
4439 int sqlite3Select(
4440   Parse *pParse,         /* The parser context */
4441   Select *p,             /* The SELECT statement being coded. */
4442   SelectDest *pDest      /* What to do with the query results */
4443 ){
4444   int i, j;              /* Loop counters */
4445   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
4446   Vdbe *v;               /* The virtual machine under construction */
4447   int isAgg;             /* True for select lists like "count(*)" */
4448   ExprList *pEList;      /* List of columns to extract. */
4449   SrcList *pTabList;     /* List of tables to select from */
4450   Expr *pWhere;          /* The WHERE clause.  May be NULL */
4451   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
4452   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
4453   Expr *pHaving;         /* The HAVING clause.  May be NULL */
4454   int rc = 1;            /* Value to return from this function */
4455   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
4456   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
4457   AggInfo sAggInfo;      /* Information used by aggregate queries */
4458   int iEnd;              /* Address of the end of the query */
4459   sqlite3 *db;           /* The database connection */
4460 
4461 #ifndef SQLITE_OMIT_EXPLAIN
4462   int iRestoreSelectId = pParse->iSelectId;
4463   pParse->iSelectId = pParse->iNextSelectId++;
4464 #endif
4465 
4466   db = pParse->db;
4467   if( p==0 || db->mallocFailed || pParse->nErr ){
4468     return 1;
4469   }
4470   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
4471   memset(&sAggInfo, 0, sizeof(sAggInfo));
4472 
4473   if( IgnorableOrderby(pDest) ){
4474     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
4475            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
4476     /* If ORDER BY makes no difference in the output then neither does
4477     ** DISTINCT so it can be removed too. */
4478     sqlite3ExprListDelete(db, p->pOrderBy);
4479     p->pOrderBy = 0;
4480     p->selFlags &= ~SF_Distinct;
4481   }
4482   sqlite3SelectPrep(pParse, p, 0);
4483   pOrderBy = p->pOrderBy;
4484   pTabList = p->pSrc;
4485   pEList = p->pEList;
4486   if( pParse->nErr || db->mallocFailed ){
4487     goto select_end;
4488   }
4489   isAgg = (p->selFlags & SF_Aggregate)!=0;
4490   assert( pEList!=0 );
4491 
4492   /* Begin generating code.
4493   */
4494   v = sqlite3GetVdbe(pParse);
4495   if( v==0 ) goto select_end;
4496 
4497   /* If writing to memory or generating a set
4498   ** only a single column may be output.
4499   */
4500 #ifndef SQLITE_OMIT_SUBQUERY
4501   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
4502     goto select_end;
4503   }
4504 #endif
4505 
4506   /* Generate code for all sub-queries in the FROM clause
4507   */
4508 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4509   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
4510     struct SrcList_item *pItem = &pTabList->a[i];
4511     SelectDest dest;
4512     Select *pSub = pItem->pSelect;
4513     int isAggSub;
4514 
4515     if( pSub==0 ) continue;
4516 
4517     /* Sometimes the code for a subquery will be generated more than
4518     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
4519     ** for example.  In that case, do not regenerate the code to manifest
4520     ** a view or the co-routine to implement a view.  The first instance
4521     ** is sufficient, though the subroutine to manifest the view does need
4522     ** to be invoked again. */
4523     if( pItem->addrFillSub ){
4524       if( pItem->viaCoroutine==0 ){
4525         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
4526       }
4527       continue;
4528     }
4529 
4530     /* Increment Parse.nHeight by the height of the largest expression
4531     ** tree referred to by this, the parent select. The child select
4532     ** may contain expression trees of at most
4533     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
4534     ** more conservative than necessary, but much easier than enforcing
4535     ** an exact limit.
4536     */
4537     pParse->nHeight += sqlite3SelectExprHeight(p);
4538 
4539     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
4540     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
4541       /* This subquery can be absorbed into its parent. */
4542       if( isAggSub ){
4543         isAgg = 1;
4544         p->selFlags |= SF_Aggregate;
4545       }
4546       i = -1;
4547     }else if( pTabList->nSrc==1
4548            && OptimizationEnabled(db, SQLITE_SubqCoroutine)
4549     ){
4550       /* Implement a co-routine that will return a single row of the result
4551       ** set on each invocation.
4552       */
4553       int addrTop = sqlite3VdbeCurrentAddr(v)+1;
4554       pItem->regReturn = ++pParse->nMem;
4555       sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
4556       VdbeComment((v, "%s", pItem->pTab->zName));
4557       pItem->addrFillSub = addrTop;
4558       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
4559       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
4560       sqlite3Select(pParse, pSub, &dest);
4561       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
4562       pItem->viaCoroutine = 1;
4563       pItem->regResult = dest.iSdst;
4564       sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
4565       sqlite3VdbeJumpHere(v, addrTop-1);
4566       sqlite3ClearTempRegCache(pParse);
4567     }else{
4568       /* Generate a subroutine that will fill an ephemeral table with
4569       ** the content of this subquery.  pItem->addrFillSub will point
4570       ** to the address of the generated subroutine.  pItem->regReturn
4571       ** is a register allocated to hold the subroutine return address
4572       */
4573       int topAddr;
4574       int onceAddr = 0;
4575       int retAddr;
4576       assert( pItem->addrFillSub==0 );
4577       pItem->regReturn = ++pParse->nMem;
4578       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
4579       pItem->addrFillSub = topAddr+1;
4580       if( pItem->isCorrelated==0 ){
4581         /* If the subquery is not correlated and if we are not inside of
4582         ** a trigger, then we only need to compute the value of the subquery
4583         ** once. */
4584         onceAddr = sqlite3CodeOnce(pParse);
4585         VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
4586       }else{
4587         VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
4588       }
4589       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
4590       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
4591       sqlite3Select(pParse, pSub, &dest);
4592       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
4593       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
4594       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
4595       VdbeComment((v, "end %s", pItem->pTab->zName));
4596       sqlite3VdbeChangeP1(v, topAddr, retAddr);
4597       sqlite3ClearTempRegCache(pParse);
4598     }
4599     if( /*pParse->nErr ||*/ db->mallocFailed ){
4600       goto select_end;
4601     }
4602     pParse->nHeight -= sqlite3SelectExprHeight(p);
4603     pTabList = p->pSrc;
4604     if( !IgnorableOrderby(pDest) ){
4605       pOrderBy = p->pOrderBy;
4606     }
4607   }
4608   pEList = p->pEList;
4609 #endif
4610   pWhere = p->pWhere;
4611   pGroupBy = p->pGroupBy;
4612   pHaving = p->pHaving;
4613   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
4614 
4615 #ifndef SQLITE_OMIT_COMPOUND_SELECT
4616   /* If there is are a sequence of queries, do the earlier ones first.
4617   */
4618   if( p->pPrior ){
4619     rc = multiSelect(pParse, p, pDest);
4620     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
4621     return rc;
4622   }
4623 #endif
4624 
4625   /* If there is both a GROUP BY and an ORDER BY clause and they are
4626   ** identical, then disable the ORDER BY clause since the GROUP BY
4627   ** will cause elements to come out in the correct order.  This is
4628   ** an optimization - the correct answer should result regardless.
4629   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
4630   ** to disable this optimization for testing purposes.
4631   */
4632   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy, -1)==0
4633          && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
4634     pOrderBy = 0;
4635   }
4636 
4637   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
4638   ** if the select-list is the same as the ORDER BY list, then this query
4639   ** can be rewritten as a GROUP BY. In other words, this:
4640   **
4641   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
4642   **
4643   ** is transformed to:
4644   **
4645   **     SELECT xyz FROM ... GROUP BY xyz
4646   **
4647   ** The second form is preferred as a single index (or temp-table) may be
4648   ** used for both the ORDER BY and DISTINCT processing. As originally
4649   ** written the query must use a temp-table for at least one of the ORDER
4650   ** BY and DISTINCT, and an index or separate temp-table for the other.
4651   */
4652   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
4653    && sqlite3ExprListCompare(pOrderBy, p->pEList, -1)==0
4654   ){
4655     p->selFlags &= ~SF_Distinct;
4656     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
4657     pGroupBy = p->pGroupBy;
4658     pOrderBy = 0;
4659     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
4660     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
4661     ** original setting of the SF_Distinct flag, not the current setting */
4662     assert( sDistinct.isTnct );
4663   }
4664 
4665   /* If there is an ORDER BY clause, then this sorting
4666   ** index might end up being unused if the data can be
4667   ** extracted in pre-sorted order.  If that is the case, then the
4668   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
4669   ** we figure out that the sorting index is not needed.  The addrSortIndex
4670   ** variable is used to facilitate that change.
4671   */
4672   if( pOrderBy ){
4673     KeyInfo *pKeyInfo;
4674     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy, 0);
4675     pOrderBy->iECursor = pParse->nTab++;
4676     p->addrOpenEphm[2] = addrSortIndex =
4677       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
4678                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
4679                            (char*)pKeyInfo, P4_KEYINFO);
4680   }else{
4681     addrSortIndex = -1;
4682   }
4683 
4684   /* If the output is destined for a temporary table, open that table.
4685   */
4686   if( pDest->eDest==SRT_EphemTab ){
4687     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
4688   }
4689 
4690   /* Set the limiter.
4691   */
4692   iEnd = sqlite3VdbeMakeLabel(v);
4693   p->nSelectRow = LARGEST_INT64;
4694   computeLimitRegisters(pParse, p, iEnd);
4695   if( p->iLimit==0 && addrSortIndex>=0 ){
4696     sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
4697     p->selFlags |= SF_UseSorter;
4698   }
4699 
4700   /* Open a virtual index to use for the distinct set.
4701   */
4702   if( p->selFlags & SF_Distinct ){
4703     sDistinct.tabTnct = pParse->nTab++;
4704     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
4705                                 sDistinct.tabTnct, 0, 0,
4706                                 (char*)keyInfoFromExprList(pParse, p->pEList, 0),
4707                                 P4_KEYINFO);
4708     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
4709     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
4710   }else{
4711     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
4712   }
4713 
4714   if( !isAgg && pGroupBy==0 ){
4715     /* No aggregate functions and no GROUP BY clause */
4716     u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
4717 
4718     /* Begin the database scan. */
4719     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, p->pEList,
4720                                wctrlFlags, 0);
4721     if( pWInfo==0 ) goto select_end;
4722     if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
4723       p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
4724     }
4725     if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
4726       sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
4727     }
4728     if( pOrderBy && sqlite3WhereIsOrdered(pWInfo) ) pOrderBy = 0;
4729 
4730     /* If sorting index that was created by a prior OP_OpenEphemeral
4731     ** instruction ended up not being needed, then change the OP_OpenEphemeral
4732     ** into an OP_Noop.
4733     */
4734     if( addrSortIndex>=0 && pOrderBy==0 ){
4735       sqlite3VdbeChangeToNoop(v, addrSortIndex);
4736       p->addrOpenEphm[2] = -1;
4737     }
4738 
4739     /* Use the standard inner loop. */
4740     selectInnerLoop(pParse, p, pEList, -1, pOrderBy, &sDistinct, pDest,
4741                     sqlite3WhereContinueLabel(pWInfo),
4742                     sqlite3WhereBreakLabel(pWInfo));
4743 
4744     /* End the database scan loop.
4745     */
4746     sqlite3WhereEnd(pWInfo);
4747   }else{
4748     /* This case when there exist aggregate functions or a GROUP BY clause
4749     ** or both */
4750     NameContext sNC;    /* Name context for processing aggregate information */
4751     int iAMem;          /* First Mem address for storing current GROUP BY */
4752     int iBMem;          /* First Mem address for previous GROUP BY */
4753     int iUseFlag;       /* Mem address holding flag indicating that at least
4754                         ** one row of the input to the aggregator has been
4755                         ** processed */
4756     int iAbortFlag;     /* Mem address which causes query abort if positive */
4757     int groupBySort;    /* Rows come from source in GROUP BY order */
4758     int addrEnd;        /* End of processing for this SELECT */
4759     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
4760     int sortOut = 0;    /* Output register from the sorter */
4761 
4762     /* Remove any and all aliases between the result set and the
4763     ** GROUP BY clause.
4764     */
4765     if( pGroupBy ){
4766       int k;                        /* Loop counter */
4767       struct ExprList_item *pItem;  /* For looping over expression in a list */
4768 
4769       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
4770         pItem->u.x.iAlias = 0;
4771       }
4772       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
4773         pItem->u.x.iAlias = 0;
4774       }
4775       if( p->nSelectRow>100 ) p->nSelectRow = 100;
4776     }else{
4777       p->nSelectRow = 1;
4778     }
4779 
4780 
4781     /* Create a label to jump to when we want to abort the query */
4782     addrEnd = sqlite3VdbeMakeLabel(v);
4783 
4784     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
4785     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
4786     ** SELECT statement.
4787     */
4788     memset(&sNC, 0, sizeof(sNC));
4789     sNC.pParse = pParse;
4790     sNC.pSrcList = pTabList;
4791     sNC.pAggInfo = &sAggInfo;
4792     sAggInfo.mnReg = pParse->nMem+1;
4793     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
4794     sAggInfo.pGroupBy = pGroupBy;
4795     sqlite3ExprAnalyzeAggList(&sNC, pEList);
4796     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
4797     if( pHaving ){
4798       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
4799     }
4800     sAggInfo.nAccumulator = sAggInfo.nColumn;
4801     for(i=0; i<sAggInfo.nFunc; i++){
4802       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
4803       sNC.ncFlags |= NC_InAggFunc;
4804       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
4805       sNC.ncFlags &= ~NC_InAggFunc;
4806     }
4807     sAggInfo.mxReg = pParse->nMem;
4808     if( db->mallocFailed ) goto select_end;
4809 
4810     /* Processing for aggregates with GROUP BY is very different and
4811     ** much more complex than aggregates without a GROUP BY.
4812     */
4813     if( pGroupBy ){
4814       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
4815       int j1;             /* A-vs-B comparision jump */
4816       int addrOutputRow;  /* Start of subroutine that outputs a result row */
4817       int regOutputRow;   /* Return address register for output subroutine */
4818       int addrSetAbort;   /* Set the abort flag and return */
4819       int addrTopOfLoop;  /* Top of the input loop */
4820       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
4821       int addrReset;      /* Subroutine for resetting the accumulator */
4822       int regReset;       /* Return address register for reset subroutine */
4823 
4824       /* If there is a GROUP BY clause we might need a sorting index to
4825       ** implement it.  Allocate that sorting index now.  If it turns out
4826       ** that we do not need it after all, the OP_SorterOpen instruction
4827       ** will be converted into a Noop.
4828       */
4829       sAggInfo.sortingIdx = pParse->nTab++;
4830       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0);
4831       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
4832           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
4833           0, (char*)pKeyInfo, P4_KEYINFO);
4834 
4835       /* Initialize memory locations used by GROUP BY aggregate processing
4836       */
4837       iUseFlag = ++pParse->nMem;
4838       iAbortFlag = ++pParse->nMem;
4839       regOutputRow = ++pParse->nMem;
4840       addrOutputRow = sqlite3VdbeMakeLabel(v);
4841       regReset = ++pParse->nMem;
4842       addrReset = sqlite3VdbeMakeLabel(v);
4843       iAMem = pParse->nMem + 1;
4844       pParse->nMem += pGroupBy->nExpr;
4845       iBMem = pParse->nMem + 1;
4846       pParse->nMem += pGroupBy->nExpr;
4847       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
4848       VdbeComment((v, "clear abort flag"));
4849       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
4850       VdbeComment((v, "indicate accumulator empty"));
4851       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
4852 
4853       /* Begin a loop that will extract all source rows in GROUP BY order.
4854       ** This might involve two separate loops with an OP_Sort in between, or
4855       ** it might be a single loop that uses an index to extract information
4856       ** in the right order to begin with.
4857       */
4858       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
4859       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
4860                                  WHERE_GROUPBY, 0);
4861       if( pWInfo==0 ) goto select_end;
4862       if( sqlite3WhereIsOrdered(pWInfo) ){
4863         /* The optimizer is able to deliver rows in group by order so
4864         ** we do not have to sort.  The OP_OpenEphemeral table will be
4865         ** cancelled later because we still need to use the pKeyInfo
4866         */
4867         groupBySort = 0;
4868       }else{
4869         /* Rows are coming out in undetermined order.  We have to push
4870         ** each row into a sorting index, terminate the first loop,
4871         ** then loop over the sorting index in order to get the output
4872         ** in sorted order
4873         */
4874         int regBase;
4875         int regRecord;
4876         int nCol;
4877         int nGroupBy;
4878 
4879         explainTempTable(pParse,
4880             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
4881                     "DISTINCT" : "GROUP BY");
4882 
4883         groupBySort = 1;
4884         nGroupBy = pGroupBy->nExpr;
4885         nCol = nGroupBy + 1;
4886         j = nGroupBy+1;
4887         for(i=0; i<sAggInfo.nColumn; i++){
4888           if( sAggInfo.aCol[i].iSorterColumn>=j ){
4889             nCol++;
4890             j++;
4891           }
4892         }
4893         regBase = sqlite3GetTempRange(pParse, nCol);
4894         sqlite3ExprCacheClear(pParse);
4895         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
4896         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
4897         j = nGroupBy+1;
4898         for(i=0; i<sAggInfo.nColumn; i++){
4899           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
4900           if( pCol->iSorterColumn>=j ){
4901             int r1 = j + regBase;
4902             int r2;
4903 
4904             r2 = sqlite3ExprCodeGetColumn(pParse,
4905                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
4906             if( r1!=r2 ){
4907               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
4908             }
4909             j++;
4910           }
4911         }
4912         regRecord = sqlite3GetTempReg(pParse);
4913         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
4914         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
4915         sqlite3ReleaseTempReg(pParse, regRecord);
4916         sqlite3ReleaseTempRange(pParse, regBase, nCol);
4917         sqlite3WhereEnd(pWInfo);
4918         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
4919         sortOut = sqlite3GetTempReg(pParse);
4920         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
4921         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
4922         VdbeComment((v, "GROUP BY sort"));
4923         sAggInfo.useSortingIdx = 1;
4924         sqlite3ExprCacheClear(pParse);
4925       }
4926 
4927       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
4928       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
4929       ** Then compare the current GROUP BY terms against the GROUP BY terms
4930       ** from the previous row currently stored in a0, a1, a2...
4931       */
4932       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
4933       sqlite3ExprCacheClear(pParse);
4934       if( groupBySort ){
4935         sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
4936       }
4937       for(j=0; j<pGroupBy->nExpr; j++){
4938         if( groupBySort ){
4939           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
4940           if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
4941         }else{
4942           sAggInfo.directMode = 1;
4943           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
4944         }
4945       }
4946       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
4947                           (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
4948       j1 = sqlite3VdbeCurrentAddr(v);
4949       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
4950 
4951       /* Generate code that runs whenever the GROUP BY changes.
4952       ** Changes in the GROUP BY are detected by the previous code
4953       ** block.  If there were no changes, this block is skipped.
4954       **
4955       ** This code copies current group by terms in b0,b1,b2,...
4956       ** over to a0,a1,a2.  It then calls the output subroutine
4957       ** and resets the aggregate accumulator registers in preparation
4958       ** for the next GROUP BY batch.
4959       */
4960       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
4961       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
4962       VdbeComment((v, "output one row"));
4963       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
4964       VdbeComment((v, "check abort flag"));
4965       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
4966       VdbeComment((v, "reset accumulator"));
4967 
4968       /* Update the aggregate accumulators based on the content of
4969       ** the current row
4970       */
4971       sqlite3VdbeJumpHere(v, j1);
4972       updateAccumulator(pParse, &sAggInfo);
4973       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
4974       VdbeComment((v, "indicate data in accumulator"));
4975 
4976       /* End of the loop
4977       */
4978       if( groupBySort ){
4979         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
4980       }else{
4981         sqlite3WhereEnd(pWInfo);
4982         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
4983       }
4984 
4985       /* Output the final row of result
4986       */
4987       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
4988       VdbeComment((v, "output final row"));
4989 
4990       /* Jump over the subroutines
4991       */
4992       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
4993 
4994       /* Generate a subroutine that outputs a single row of the result
4995       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
4996       ** is less than or equal to zero, the subroutine is a no-op.  If
4997       ** the processing calls for the query to abort, this subroutine
4998       ** increments the iAbortFlag memory location before returning in
4999       ** order to signal the caller to abort.
5000       */
5001       addrSetAbort = sqlite3VdbeCurrentAddr(v);
5002       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
5003       VdbeComment((v, "set abort flag"));
5004       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5005       sqlite3VdbeResolveLabel(v, addrOutputRow);
5006       addrOutputRow = sqlite3VdbeCurrentAddr(v);
5007       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
5008       VdbeComment((v, "Groupby result generator entry point"));
5009       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5010       finalizeAggFunctions(pParse, &sAggInfo);
5011       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
5012       selectInnerLoop(pParse, p, p->pEList, -1, pOrderBy,
5013                       &sDistinct, pDest,
5014                       addrOutputRow+1, addrSetAbort);
5015       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5016       VdbeComment((v, "end groupby result generator"));
5017 
5018       /* Generate a subroutine that will reset the group-by accumulator
5019       */
5020       sqlite3VdbeResolveLabel(v, addrReset);
5021       resetAccumulator(pParse, &sAggInfo);
5022       sqlite3VdbeAddOp1(v, OP_Return, regReset);
5023 
5024     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
5025     else {
5026       ExprList *pDel = 0;
5027 #ifndef SQLITE_OMIT_BTREECOUNT
5028       Table *pTab;
5029       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
5030         /* If isSimpleCount() returns a pointer to a Table structure, then
5031         ** the SQL statement is of the form:
5032         **
5033         **   SELECT count(*) FROM <tbl>
5034         **
5035         ** where the Table structure returned represents table <tbl>.
5036         **
5037         ** This statement is so common that it is optimized specially. The
5038         ** OP_Count instruction is executed either on the intkey table that
5039         ** contains the data for table <tbl> or on one of its indexes. It
5040         ** is better to execute the op on an index, as indexes are almost
5041         ** always spread across less pages than their corresponding tables.
5042         */
5043         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
5044         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
5045         Index *pIdx;                         /* Iterator variable */
5046         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
5047         Index *pBest = 0;                    /* Best index found so far */
5048         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
5049 
5050         sqlite3CodeVerifySchema(pParse, iDb);
5051         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
5052 
5053         /* Search for the index that has the lowest scan cost.
5054         **
5055         ** (2011-04-15) Do not do a full scan of an unordered index.
5056         **
5057         ** (2013-10-03) Do not count the entries in a partial index.
5058         **
5059         ** In practice the KeyInfo structure will not be used. It is only
5060         ** passed to keep OP_OpenRead happy.
5061         */
5062         if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
5063         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
5064           if( pIdx->bUnordered==0
5065            && pIdx->szIdxRow<pTab->szTabRow
5066            && pIdx->pPartIdxWhere==0
5067            && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
5068           ){
5069             pBest = pIdx;
5070           }
5071         }
5072         if( pBest ){
5073           iRoot = pBest->tnum;
5074           pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
5075         }
5076 
5077         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
5078         sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
5079         if( pKeyInfo ){
5080           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
5081         }
5082         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
5083         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
5084         explainSimpleCount(pParse, pTab, pBest);
5085       }else
5086 #endif /* SQLITE_OMIT_BTREECOUNT */
5087       {
5088         /* Check if the query is of one of the following forms:
5089         **
5090         **   SELECT min(x) FROM ...
5091         **   SELECT max(x) FROM ...
5092         **
5093         ** If it is, then ask the code in where.c to attempt to sort results
5094         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
5095         ** If where.c is able to produce results sorted in this order, then
5096         ** add vdbe code to break out of the processing loop after the
5097         ** first iteration (since the first iteration of the loop is
5098         ** guaranteed to operate on the row with the minimum or maximum
5099         ** value of x, the only row required).
5100         **
5101         ** A special flag must be passed to sqlite3WhereBegin() to slightly
5102         ** modify behavior as follows:
5103         **
5104         **   + If the query is a "SELECT min(x)", then the loop coded by
5105         **     where.c should not iterate over any values with a NULL value
5106         **     for x.
5107         **
5108         **   + The optimizer code in where.c (the thing that decides which
5109         **     index or indices to use) should place a different priority on
5110         **     satisfying the 'ORDER BY' clause than it does in other cases.
5111         **     Refer to code and comments in where.c for details.
5112         */
5113         ExprList *pMinMax = 0;
5114         u8 flag = WHERE_ORDERBY_NORMAL;
5115 
5116         assert( p->pGroupBy==0 );
5117         assert( flag==0 );
5118         if( p->pHaving==0 ){
5119           flag = minMaxQuery(&sAggInfo, &pMinMax);
5120         }
5121         assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
5122 
5123         if( flag ){
5124           pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
5125           pDel = pMinMax;
5126           if( pMinMax && !db->mallocFailed ){
5127             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
5128             pMinMax->a[0].pExpr->op = TK_COLUMN;
5129           }
5130         }
5131 
5132         /* This case runs if the aggregate has no GROUP BY clause.  The
5133         ** processing is much simpler since there is only a single row
5134         ** of output.
5135         */
5136         resetAccumulator(pParse, &sAggInfo);
5137         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
5138         if( pWInfo==0 ){
5139           sqlite3ExprListDelete(db, pDel);
5140           goto select_end;
5141         }
5142         updateAccumulator(pParse, &sAggInfo);
5143         assert( pMinMax==0 || pMinMax->nExpr==1 );
5144         if( sqlite3WhereIsOrdered(pWInfo) ){
5145           sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
5146           VdbeComment((v, "%s() by index",
5147                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
5148         }
5149         sqlite3WhereEnd(pWInfo);
5150         finalizeAggFunctions(pParse, &sAggInfo);
5151       }
5152 
5153       pOrderBy = 0;
5154       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
5155       selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
5156                       pDest, addrEnd, addrEnd);
5157       sqlite3ExprListDelete(db, pDel);
5158     }
5159     sqlite3VdbeResolveLabel(v, addrEnd);
5160 
5161   } /* endif aggregate query */
5162 
5163   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
5164     explainTempTable(pParse, "DISTINCT");
5165   }
5166 
5167   /* If there is an ORDER BY clause, then we need to sort the results
5168   ** and send them to the callback one by one.
5169   */
5170   if( pOrderBy ){
5171     explainTempTable(pParse, "ORDER BY");
5172     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
5173   }
5174 
5175   /* Jump here to skip this query
5176   */
5177   sqlite3VdbeResolveLabel(v, iEnd);
5178 
5179   /* The SELECT was successfully coded.   Set the return code to 0
5180   ** to indicate no errors.
5181   */
5182   rc = 0;
5183 
5184   /* Control jumps to here if an error is encountered above, or upon
5185   ** successful coding of the SELECT.
5186   */
5187 select_end:
5188   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
5189 
5190   /* Identify column names if results of the SELECT are to be output.
5191   */
5192   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
5193     generateColumnNames(pParse, pTabList, pEList);
5194   }
5195 
5196   sqlite3DbFree(db, sAggInfo.aCol);
5197   sqlite3DbFree(db, sAggInfo.aFunc);
5198   return rc;
5199 }
5200 
5201 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
5202 /*
5203 ** Generate a human-readable description of a the Select object.
5204 */
5205 static void explainOneSelect(Vdbe *pVdbe, Select *p){
5206   sqlite3ExplainPrintf(pVdbe, "SELECT ");
5207   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
5208     if( p->selFlags & SF_Distinct ){
5209       sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
5210     }
5211     if( p->selFlags & SF_Aggregate ){
5212       sqlite3ExplainPrintf(pVdbe, "agg_flag ");
5213     }
5214     sqlite3ExplainNL(pVdbe);
5215     sqlite3ExplainPrintf(pVdbe, "   ");
5216   }
5217   sqlite3ExplainExprList(pVdbe, p->pEList);
5218   sqlite3ExplainNL(pVdbe);
5219   if( p->pSrc && p->pSrc->nSrc ){
5220     int i;
5221     sqlite3ExplainPrintf(pVdbe, "FROM ");
5222     sqlite3ExplainPush(pVdbe);
5223     for(i=0; i<p->pSrc->nSrc; i++){
5224       struct SrcList_item *pItem = &p->pSrc->a[i];
5225       sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
5226       if( pItem->pSelect ){
5227         sqlite3ExplainSelect(pVdbe, pItem->pSelect);
5228         if( pItem->pTab ){
5229           sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
5230         }
5231       }else if( pItem->zName ){
5232         sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
5233       }
5234       if( pItem->zAlias ){
5235         sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
5236       }
5237       if( pItem->jointype & JT_LEFT ){
5238         sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
5239       }
5240       sqlite3ExplainNL(pVdbe);
5241     }
5242     sqlite3ExplainPop(pVdbe);
5243   }
5244   if( p->pWhere ){
5245     sqlite3ExplainPrintf(pVdbe, "WHERE ");
5246     sqlite3ExplainExpr(pVdbe, p->pWhere);
5247     sqlite3ExplainNL(pVdbe);
5248   }
5249   if( p->pGroupBy ){
5250     sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
5251     sqlite3ExplainExprList(pVdbe, p->pGroupBy);
5252     sqlite3ExplainNL(pVdbe);
5253   }
5254   if( p->pHaving ){
5255     sqlite3ExplainPrintf(pVdbe, "HAVING ");
5256     sqlite3ExplainExpr(pVdbe, p->pHaving);
5257     sqlite3ExplainNL(pVdbe);
5258   }
5259   if( p->pOrderBy ){
5260     sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
5261     sqlite3ExplainExprList(pVdbe, p->pOrderBy);
5262     sqlite3ExplainNL(pVdbe);
5263   }
5264   if( p->pLimit ){
5265     sqlite3ExplainPrintf(pVdbe, "LIMIT ");
5266     sqlite3ExplainExpr(pVdbe, p->pLimit);
5267     sqlite3ExplainNL(pVdbe);
5268   }
5269   if( p->pOffset ){
5270     sqlite3ExplainPrintf(pVdbe, "OFFSET ");
5271     sqlite3ExplainExpr(pVdbe, p->pOffset);
5272     sqlite3ExplainNL(pVdbe);
5273   }
5274 }
5275 void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
5276   if( p==0 ){
5277     sqlite3ExplainPrintf(pVdbe, "(null-select)");
5278     return;
5279   }
5280   sqlite3ExplainPush(pVdbe);
5281   while( p ){
5282     explainOneSelect(pVdbe, p);
5283     p = p->pNext;
5284     if( p==0 ) break;
5285     sqlite3ExplainNL(pVdbe);
5286     sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
5287   }
5288   sqlite3ExplainPrintf(pVdbe, "END");
5289   sqlite3ExplainPop(pVdbe);
5290 }
5291 
5292 /* End of the structure debug printing code
5293 *****************************************************************************/
5294 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
5295