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