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