xref: /sqlite-3.40.0/src/select.c (revision de7a820f)
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 **  (28)  The subquery is not a MATERIALIZED CTE.
4157 **
4158 **
4159 ** In this routine, the "p" parameter is a pointer to the outer query.
4160 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
4161 ** uses aggregates.
4162 **
4163 ** If flattening is not attempted, this routine is a no-op and returns 0.
4164 ** If flattening is attempted this routine returns 1.
4165 **
4166 ** All of the expression analysis must occur on both the outer query and
4167 ** the subquery before this routine runs.
4168 */
4169 static int flattenSubquery(
4170   Parse *pParse,       /* Parsing context */
4171   Select *p,           /* The parent or outer SELECT statement */
4172   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
4173   int isAgg            /* True if outer SELECT uses aggregate functions */
4174 ){
4175   const char *zSavedAuthContext = pParse->zAuthContext;
4176   Select *pParent;    /* Current UNION ALL term of the other query */
4177   Select *pSub;       /* The inner query or "subquery" */
4178   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
4179   SrcList *pSrc;      /* The FROM clause of the outer query */
4180   SrcList *pSubSrc;   /* The FROM clause of the subquery */
4181   int iParent;        /* VDBE cursor number of the pSub result set temp table */
4182   int iNewParent = -1;/* Replacement table for iParent */
4183   int isOuterJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
4184   int i;              /* Loop counter */
4185   Expr *pWhere;                    /* The WHERE clause */
4186   SrcItem *pSubitem;               /* The subquery */
4187   sqlite3 *db = pParse->db;
4188   Walker w;                        /* Walker to persist agginfo data */
4189   int *aCsrMap = 0;
4190 
4191   /* Check to see if flattening is permitted.  Return 0 if not.
4192   */
4193   assert( p!=0 );
4194   assert( p->pPrior==0 );
4195   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
4196   pSrc = p->pSrc;
4197   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
4198   pSubitem = &pSrc->a[iFrom];
4199   iParent = pSubitem->iCursor;
4200   pSub = pSubitem->pSelect;
4201   assert( pSub!=0 );
4202 
4203 #ifndef SQLITE_OMIT_WINDOWFUNC
4204   if( p->pWin || pSub->pWin ) return 0;                  /* Restriction (25) */
4205 #endif
4206 
4207   pSubSrc = pSub->pSrc;
4208   assert( pSubSrc );
4209   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
4210   ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
4211   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
4212   ** became arbitrary expressions, we were forced to add restrictions (13)
4213   ** and (14). */
4214   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
4215   if( pSub->pLimit && pSub->pLimit->pRight ) return 0;   /* Restriction (14) */
4216   if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
4217     return 0;                                            /* Restriction (15) */
4218   }
4219   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
4220   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (4)  */
4221   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
4222      return 0;         /* Restrictions (8)(9) */
4223   }
4224   if( p->pOrderBy && pSub->pOrderBy ){
4225      return 0;                                           /* Restriction (11) */
4226   }
4227   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
4228   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
4229   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
4230      return 0;         /* Restriction (21) */
4231   }
4232   if( pSub->selFlags & (SF_Recursive) ){
4233     return 0; /* Restrictions (22) */
4234   }
4235 
4236   /*
4237   ** If the subquery is the right operand of a LEFT JOIN, then the
4238   ** subquery may not be a join itself (3a). Example of why this is not
4239   ** allowed:
4240   **
4241   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
4242   **
4243   ** If we flatten the above, we would get
4244   **
4245   **         (t1 LEFT OUTER JOIN t2) JOIN t3
4246   **
4247   ** which is not at all the same thing.
4248   **
4249   ** If the subquery is the right operand of a LEFT JOIN, then the outer
4250   ** query cannot be an aggregate. (3c)  This is an artifact of the way
4251   ** aggregates are processed - there is no mechanism to determine if
4252   ** the LEFT JOIN table should be all-NULL.
4253   **
4254   ** See also tickets #306, #350, and #3300.
4255   */
4256   if( (pSubitem->fg.jointype & (JT_OUTER|JT_LTORJ))!=0 ){
4257     if( pSubSrc->nSrc>1                        /* (3a) */
4258      || isAgg                                  /* (3b) */
4259      || IsVirtual(pSubSrc->a[0].pTab)          /* (3c) */
4260      || (p->selFlags & SF_Distinct)!=0         /* (3d) */
4261      || (pSubitem->fg.jointype & JT_RIGHT)!=0  /* (26) */
4262     ){
4263       return 0;
4264     }
4265     isOuterJoin = 1;
4266   }
4267 #ifdef SQLITE_EXTRA_IFNULLROW
4268   else if( iFrom>0 && !isAgg ){
4269     /* Setting isOuterJoin to -1 causes OP_IfNullRow opcodes to be generated for
4270     ** every reference to any result column from subquery in a join, even
4271     ** though they are not necessary.  This will stress-test the OP_IfNullRow
4272     ** opcode. */
4273     isOuterJoin = -1;
4274   }
4275 #endif
4276 
4277   assert( pSubSrc->nSrc>0 );  /* True by restriction (7) */
4278   if( iFrom>0 && (pSubSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
4279     return 0;   /* Restriction (27) */
4280   }
4281   if( pSubitem->fg.isCte && pSubitem->u2.pCteUse->eM10d==M10d_Yes ){
4282     return 0;       /* (28) */
4283   }
4284 
4285   /* Restriction (17): If the sub-query is a compound SELECT, then it must
4286   ** use only the UNION ALL operator. And none of the simple select queries
4287   ** that make up the compound SELECT are allowed to be aggregate or distinct
4288   ** queries.
4289   */
4290   if( pSub->pPrior ){
4291     if( pSub->pOrderBy ){
4292       return 0;  /* Restriction (20) */
4293     }
4294     if( isAgg || (p->selFlags & SF_Distinct)!=0 || isOuterJoin>0 ){
4295       return 0; /* (17d1), (17d2), or (17f) */
4296     }
4297     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
4298       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
4299       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
4300       assert( pSub->pSrc!=0 );
4301       assert( (pSub->selFlags & SF_Recursive)==0 );
4302       assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
4303       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0    /* (17b) */
4304        || (pSub1->pPrior && pSub1->op!=TK_ALL)                 /* (17a) */
4305        || pSub1->pSrc->nSrc<1                                  /* (17c) */
4306 #ifndef SQLITE_OMIT_WINDOWFUNC
4307        || pSub1->pWin                                          /* (17e) */
4308 #endif
4309       ){
4310         return 0;
4311       }
4312       testcase( pSub1->pSrc->nSrc>1 );
4313     }
4314 
4315     /* Restriction (18). */
4316     if( p->pOrderBy ){
4317       int ii;
4318       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
4319         if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
4320       }
4321     }
4322 
4323     /* Restriction (23) */
4324     if( (p->selFlags & SF_Recursive) ) return 0;
4325 
4326     if( pSrc->nSrc>1 ){
4327       if( pParse->nSelect>500 ) return 0;
4328       if( OptimizationDisabled(db, SQLITE_FlttnUnionAll) ) return 0;
4329       aCsrMap = sqlite3DbMallocZero(db, ((i64)pParse->nTab+1)*sizeof(int));
4330       if( aCsrMap ) aCsrMap[0] = pParse->nTab;
4331     }
4332   }
4333 
4334   /***** If we reach this point, flattening is permitted. *****/
4335   SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n",
4336                    pSub->selId, pSub, iFrom));
4337 
4338   /* Authorize the subquery */
4339   pParse->zAuthContext = pSubitem->zName;
4340   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
4341   testcase( i==SQLITE_DENY );
4342   pParse->zAuthContext = zSavedAuthContext;
4343 
4344   /* Delete the transient structures associated with thesubquery */
4345   pSub1 = pSubitem->pSelect;
4346   sqlite3DbFree(db, pSubitem->zDatabase);
4347   sqlite3DbFree(db, pSubitem->zName);
4348   sqlite3DbFree(db, pSubitem->zAlias);
4349   pSubitem->zDatabase = 0;
4350   pSubitem->zName = 0;
4351   pSubitem->zAlias = 0;
4352   pSubitem->pSelect = 0;
4353   assert( pSubitem->fg.isUsing!=0 || pSubitem->u3.pOn==0 );
4354 
4355   /* If the sub-query is a compound SELECT statement, then (by restrictions
4356   ** 17 and 18 above) it must be a UNION ALL and the parent query must
4357   ** be of the form:
4358   **
4359   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
4360   **
4361   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
4362   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
4363   ** OFFSET clauses and joins them to the left-hand-side of the original
4364   ** using UNION ALL operators. In this case N is the number of simple
4365   ** select statements in the compound sub-query.
4366   **
4367   ** Example:
4368   **
4369   **     SELECT a+1 FROM (
4370   **        SELECT x FROM tab
4371   **        UNION ALL
4372   **        SELECT y FROM tab
4373   **        UNION ALL
4374   **        SELECT abs(z*2) FROM tab2
4375   **     ) WHERE a!=5 ORDER BY 1
4376   **
4377   ** Transformed into:
4378   **
4379   **     SELECT x+1 FROM tab WHERE x+1!=5
4380   **     UNION ALL
4381   **     SELECT y+1 FROM tab WHERE y+1!=5
4382   **     UNION ALL
4383   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
4384   **     ORDER BY 1
4385   **
4386   ** We call this the "compound-subquery flattening".
4387   */
4388   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
4389     Select *pNew;
4390     ExprList *pOrderBy = p->pOrderBy;
4391     Expr *pLimit = p->pLimit;
4392     Select *pPrior = p->pPrior;
4393     Table *pItemTab = pSubitem->pTab;
4394     pSubitem->pTab = 0;
4395     p->pOrderBy = 0;
4396     p->pPrior = 0;
4397     p->pLimit = 0;
4398     pNew = sqlite3SelectDup(db, p, 0);
4399     p->pLimit = pLimit;
4400     p->pOrderBy = pOrderBy;
4401     p->op = TK_ALL;
4402     pSubitem->pTab = pItemTab;
4403     if( pNew==0 ){
4404       p->pPrior = pPrior;
4405     }else{
4406       pNew->selId = ++pParse->nSelect;
4407       if( aCsrMap && ALWAYS(db->mallocFailed==0) ){
4408         renumberCursors(pParse, pNew, iFrom, aCsrMap);
4409       }
4410       pNew->pPrior = pPrior;
4411       if( pPrior ) pPrior->pNext = pNew;
4412       pNew->pNext = p;
4413       p->pPrior = pNew;
4414       SELECTTRACE(2,pParse,p,("compound-subquery flattener"
4415                               " creates %u as peer\n",pNew->selId));
4416     }
4417     assert( pSubitem->pSelect==0 );
4418   }
4419   sqlite3DbFree(db, aCsrMap);
4420   if( db->mallocFailed ){
4421     pSubitem->pSelect = pSub1;
4422     return 1;
4423   }
4424 
4425   /* Defer deleting the Table object associated with the
4426   ** subquery until code generation is
4427   ** complete, since there may still exist Expr.pTab entries that
4428   ** refer to the subquery even after flattening.  Ticket #3346.
4429   **
4430   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
4431   */
4432   if( ALWAYS(pSubitem->pTab!=0) ){
4433     Table *pTabToDel = pSubitem->pTab;
4434     if( pTabToDel->nTabRef==1 ){
4435       Parse *pToplevel = sqlite3ParseToplevel(pParse);
4436       sqlite3ParserAddCleanup(pToplevel,
4437          (void(*)(sqlite3*,void*))sqlite3DeleteTable,
4438          pTabToDel);
4439       testcase( pToplevel->earlyCleanup );
4440     }else{
4441       pTabToDel->nTabRef--;
4442     }
4443     pSubitem->pTab = 0;
4444   }
4445 
4446   /* The following loop runs once for each term in a compound-subquery
4447   ** flattening (as described above).  If we are doing a different kind
4448   ** of flattening - a flattening other than a compound-subquery flattening -
4449   ** then this loop only runs once.
4450   **
4451   ** This loop moves all of the FROM elements of the subquery into the
4452   ** the FROM clause of the outer query.  Before doing this, remember
4453   ** the cursor number for the original outer query FROM element in
4454   ** iParent.  The iParent cursor will never be used.  Subsequent code
4455   ** will scan expressions looking for iParent references and replace
4456   ** those references with expressions that resolve to the subquery FROM
4457   ** elements we are now copying in.
4458   */
4459   pSub = pSub1;
4460   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
4461     int nSubSrc;
4462     u8 jointype = 0;
4463     u8 ltorj = pSrc->a[iFrom].fg.jointype & JT_LTORJ;
4464     assert( pSub!=0 );
4465     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
4466     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
4467     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
4468 
4469     if( pParent==p ){
4470       jointype = pSubitem->fg.jointype;     /* First time through the loop */
4471     }
4472 
4473     /* The subquery uses a single slot of the FROM clause of the outer
4474     ** query.  If the subquery has more than one element in its FROM clause,
4475     ** then expand the outer query to make space for it to hold all elements
4476     ** of the subquery.
4477     **
4478     ** Example:
4479     **
4480     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
4481     **
4482     ** The outer query has 3 slots in its FROM clause.  One slot of the
4483     ** outer query (the middle slot) is used by the subquery.  The next
4484     ** block of code will expand the outer query FROM clause to 4 slots.
4485     ** The middle slot is expanded to two slots in order to make space
4486     ** for the two elements in the FROM clause of the subquery.
4487     */
4488     if( nSubSrc>1 ){
4489       pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
4490       if( pSrc==0 ) break;
4491       pParent->pSrc = pSrc;
4492     }
4493 
4494     /* Transfer the FROM clause terms from the subquery into the
4495     ** outer query.
4496     */
4497     for(i=0; i<nSubSrc; i++){
4498       SrcItem *pItem = &pSrc->a[i+iFrom];
4499       if( pItem->fg.isUsing ) sqlite3IdListDelete(db, pItem->u3.pUsing);
4500       assert( pItem->fg.isTabFunc==0 );
4501       *pItem = pSubSrc->a[i];
4502       pItem->fg.jointype |= ltorj;
4503       iNewParent = pSubSrc->a[i].iCursor;
4504       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
4505     }
4506     pSrc->a[iFrom].fg.jointype &= JT_LTORJ;
4507     pSrc->a[iFrom].fg.jointype |= jointype | ltorj;
4508 
4509     /* Now begin substituting subquery result set expressions for
4510     ** references to the iParent in the outer query.
4511     **
4512     ** Example:
4513     **
4514     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
4515     **   \                     \_____________ subquery __________/          /
4516     **    \_____________________ outer query ______________________________/
4517     **
4518     ** We look at every expression in the outer query and every place we see
4519     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
4520     */
4521     if( pSub->pOrderBy && (pParent->selFlags & SF_NoopOrderBy)==0 ){
4522       /* At this point, any non-zero iOrderByCol values indicate that the
4523       ** ORDER BY column expression is identical to the iOrderByCol'th
4524       ** expression returned by SELECT statement pSub. Since these values
4525       ** do not necessarily correspond to columns in SELECT statement pParent,
4526       ** zero them before transfering the ORDER BY clause.
4527       **
4528       ** Not doing this may cause an error if a subsequent call to this
4529       ** function attempts to flatten a compound sub-query into pParent
4530       ** (the only way this can happen is if the compound sub-query is
4531       ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
4532       ExprList *pOrderBy = pSub->pOrderBy;
4533       for(i=0; i<pOrderBy->nExpr; i++){
4534         pOrderBy->a[i].u.x.iOrderByCol = 0;
4535       }
4536       assert( pParent->pOrderBy==0 );
4537       pParent->pOrderBy = pOrderBy;
4538       pSub->pOrderBy = 0;
4539     }
4540     pWhere = pSub->pWhere;
4541     pSub->pWhere = 0;
4542     if( isOuterJoin>0 ){
4543       sqlite3SetJoinExpr(pWhere, iNewParent, EP_FromJoin);
4544     }
4545     if( pWhere ){
4546       if( pParent->pWhere ){
4547         pParent->pWhere = sqlite3PExpr(pParse, TK_AND, pWhere, pParent->pWhere);
4548       }else{
4549         pParent->pWhere = pWhere;
4550       }
4551     }
4552     if( db->mallocFailed==0 ){
4553       SubstContext x;
4554       x.pParse = pParse;
4555       x.iTable = iParent;
4556       x.iNewTable = iNewParent;
4557       x.isOuterJoin = isOuterJoin;
4558       x.pEList = pSub->pEList;
4559       substSelect(&x, pParent, 0);
4560     }
4561 
4562     /* The flattened query is a compound if either the inner or the
4563     ** outer query is a compound. */
4564     pParent->selFlags |= pSub->selFlags & SF_Compound;
4565     assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
4566 
4567     /*
4568     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
4569     **
4570     ** One is tempted to try to add a and b to combine the limits.  But this
4571     ** does not work if either limit is negative.
4572     */
4573     if( pSub->pLimit ){
4574       pParent->pLimit = pSub->pLimit;
4575       pSub->pLimit = 0;
4576     }
4577 
4578     /* Recompute the SrcList_item.colUsed masks for the flattened
4579     ** tables. */
4580     for(i=0; i<nSubSrc; i++){
4581       recomputeColumnsUsed(pParent, &pSrc->a[i+iFrom]);
4582     }
4583   }
4584 
4585   /* Finially, delete what is left of the subquery and return
4586   ** success.
4587   */
4588   sqlite3AggInfoPersistWalkerInit(&w, pParse);
4589   sqlite3WalkSelect(&w,pSub1);
4590   sqlite3SelectDelete(db, pSub1);
4591 
4592 #if TREETRACE_ENABLED
4593   if( sqlite3TreeTrace & 0x100 ){
4594     SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
4595     sqlite3TreeViewSelect(0, p, 0);
4596   }
4597 #endif
4598 
4599   return 1;
4600 }
4601 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
4602 
4603 /*
4604 ** A structure to keep track of all of the column values that are fixed to
4605 ** a known value due to WHERE clause constraints of the form COLUMN=VALUE.
4606 */
4607 typedef struct WhereConst WhereConst;
4608 struct WhereConst {
4609   Parse *pParse;   /* Parsing context */
4610   u8 *pOomFault;   /* Pointer to pParse->db->mallocFailed */
4611   int nConst;      /* Number for COLUMN=CONSTANT terms */
4612   int nChng;       /* Number of times a constant is propagated */
4613   int bHasAffBlob; /* At least one column in apExpr[] as affinity BLOB */
4614   Expr **apExpr;   /* [i*2] is COLUMN and [i*2+1] is VALUE */
4615 };
4616 
4617 /*
4618 ** Add a new entry to the pConst object.  Except, do not add duplicate
4619 ** pColumn entires.  Also, do not add if doing so would not be appropriate.
4620 **
4621 ** The caller guarantees the pColumn is a column and pValue is a constant.
4622 ** This routine has to do some additional checks before completing the
4623 ** insert.
4624 */
4625 static void constInsert(
4626   WhereConst *pConst,  /* The WhereConst into which we are inserting */
4627   Expr *pColumn,       /* The COLUMN part of the constraint */
4628   Expr *pValue,        /* The VALUE part of the constraint */
4629   Expr *pExpr          /* Overall expression: COLUMN=VALUE or VALUE=COLUMN */
4630 ){
4631   int i;
4632   assert( pColumn->op==TK_COLUMN );
4633   assert( sqlite3ExprIsConstant(pValue) );
4634 
4635   if( ExprHasProperty(pColumn, EP_FixedCol) ) return;
4636   if( sqlite3ExprAffinity(pValue)!=0 ) return;
4637   if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){
4638     return;
4639   }
4640 
4641   /* 2018-10-25 ticket [cf5ed20f]
4642   ** Make sure the same pColumn is not inserted more than once */
4643   for(i=0; i<pConst->nConst; i++){
4644     const Expr *pE2 = pConst->apExpr[i*2];
4645     assert( pE2->op==TK_COLUMN );
4646     if( pE2->iTable==pColumn->iTable
4647      && pE2->iColumn==pColumn->iColumn
4648     ){
4649       return;  /* Already present.  Return without doing anything. */
4650     }
4651   }
4652   if( sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){
4653     pConst->bHasAffBlob = 1;
4654   }
4655 
4656   pConst->nConst++;
4657   pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
4658                          pConst->nConst*2*sizeof(Expr*));
4659   if( pConst->apExpr==0 ){
4660     pConst->nConst = 0;
4661   }else{
4662     pConst->apExpr[pConst->nConst*2-2] = pColumn;
4663     pConst->apExpr[pConst->nConst*2-1] = pValue;
4664   }
4665 }
4666 
4667 /*
4668 ** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE
4669 ** is a constant expression and where the term must be true because it
4670 ** is part of the AND-connected terms of the expression.  For each term
4671 ** found, add it to the pConst structure.
4672 */
4673 static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
4674   Expr *pRight, *pLeft;
4675   if( NEVER(pExpr==0) ) return;
4676   if( ExprHasProperty(pExpr, EP_FromJoin) ) return;
4677   if( pExpr->op==TK_AND ){
4678     findConstInWhere(pConst, pExpr->pRight);
4679     findConstInWhere(pConst, pExpr->pLeft);
4680     return;
4681   }
4682   if( pExpr->op!=TK_EQ ) return;
4683   pRight = pExpr->pRight;
4684   pLeft = pExpr->pLeft;
4685   assert( pRight!=0 );
4686   assert( pLeft!=0 );
4687   if( pRight->op==TK_COLUMN && sqlite3ExprIsConstant(pLeft) ){
4688     constInsert(pConst,pRight,pLeft,pExpr);
4689   }
4690   if( pLeft->op==TK_COLUMN && sqlite3ExprIsConstant(pRight) ){
4691     constInsert(pConst,pLeft,pRight,pExpr);
4692   }
4693 }
4694 
4695 /*
4696 ** This is a helper function for Walker callback propagateConstantExprRewrite().
4697 **
4698 ** Argument pExpr is a candidate expression to be replaced by a value. If
4699 ** pExpr is equivalent to one of the columns named in pWalker->u.pConst,
4700 ** then overwrite it with the corresponding value. Except, do not do so
4701 ** if argument bIgnoreAffBlob is non-zero and the affinity of pExpr
4702 ** is SQLITE_AFF_BLOB.
4703 */
4704 static int propagateConstantExprRewriteOne(
4705   WhereConst *pConst,
4706   Expr *pExpr,
4707   int bIgnoreAffBlob
4708 ){
4709   int i;
4710   if( pConst->pOomFault[0] ) return WRC_Prune;
4711   if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
4712   if( ExprHasProperty(pExpr, EP_FixedCol|EP_FromJoin) ){
4713     testcase( ExprHasProperty(pExpr, EP_FixedCol) );
4714     testcase( ExprHasProperty(pExpr, EP_FromJoin) );
4715     return WRC_Continue;
4716   }
4717   for(i=0; i<pConst->nConst; i++){
4718     Expr *pColumn = pConst->apExpr[i*2];
4719     if( pColumn==pExpr ) continue;
4720     if( pColumn->iTable!=pExpr->iTable ) continue;
4721     if( pColumn->iColumn!=pExpr->iColumn ) continue;
4722     if( bIgnoreAffBlob && sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){
4723       break;
4724     }
4725     /* A match is found.  Add the EP_FixedCol property */
4726     pConst->nChng++;
4727     ExprClearProperty(pExpr, EP_Leaf);
4728     ExprSetProperty(pExpr, EP_FixedCol);
4729     assert( pExpr->pLeft==0 );
4730     pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
4731     if( pConst->pParse->db->mallocFailed ) return WRC_Prune;
4732     break;
4733   }
4734   return WRC_Prune;
4735 }
4736 
4737 /*
4738 ** This is a Walker expression callback. pExpr is a node from the WHERE
4739 ** clause of a SELECT statement. This function examines pExpr to see if
4740 ** any substitutions based on the contents of pWalker->u.pConst should
4741 ** be made to pExpr or its immediate children.
4742 **
4743 ** A substitution is made if:
4744 **
4745 **   + pExpr is a column with an affinity other than BLOB that matches
4746 **     one of the columns in pWalker->u.pConst, or
4747 **
4748 **   + pExpr is a binary comparison operator (=, <=, >=, <, >) that
4749 **     uses an affinity other than TEXT and one of its immediate
4750 **     children is a column that matches one of the columns in
4751 **     pWalker->u.pConst.
4752 */
4753 static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
4754   WhereConst *pConst = pWalker->u.pConst;
4755   assert( TK_GT==TK_EQ+1 );
4756   assert( TK_LE==TK_EQ+2 );
4757   assert( TK_LT==TK_EQ+3 );
4758   assert( TK_GE==TK_EQ+4 );
4759   if( pConst->bHasAffBlob ){
4760     if( (pExpr->op>=TK_EQ && pExpr->op<=TK_GE)
4761      || pExpr->op==TK_IS
4762     ){
4763       propagateConstantExprRewriteOne(pConst, pExpr->pLeft, 0);
4764       if( pConst->pOomFault[0] ) return WRC_Prune;
4765       if( sqlite3ExprAffinity(pExpr->pLeft)!=SQLITE_AFF_TEXT ){
4766         propagateConstantExprRewriteOne(pConst, pExpr->pRight, 0);
4767       }
4768     }
4769   }
4770   return propagateConstantExprRewriteOne(pConst, pExpr, pConst->bHasAffBlob);
4771 }
4772 
4773 /*
4774 ** The WHERE-clause constant propagation optimization.
4775 **
4776 ** If the WHERE clause contains terms of the form COLUMN=CONSTANT or
4777 ** CONSTANT=COLUMN that are top-level AND-connected terms that are not
4778 ** part of a ON clause from a LEFT JOIN, then throughout the query
4779 ** replace all other occurrences of COLUMN with CONSTANT.
4780 **
4781 ** For example, the query:
4782 **
4783 **      SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b
4784 **
4785 ** Is transformed into
4786 **
4787 **      SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39
4788 **
4789 ** Return true if any transformations where made and false if not.
4790 **
4791 ** Implementation note:  Constant propagation is tricky due to affinity
4792 ** and collating sequence interactions.  Consider this example:
4793 **
4794 **    CREATE TABLE t1(a INT,b TEXT);
4795 **    INSERT INTO t1 VALUES(123,'0123');
4796 **    SELECT * FROM t1 WHERE a=123 AND b=a;
4797 **    SELECT * FROM t1 WHERE a=123 AND b=123;
4798 **
4799 ** The two SELECT statements above should return different answers.  b=a
4800 ** is alway true because the comparison uses numeric affinity, but b=123
4801 ** is false because it uses text affinity and '0123' is not the same as '123'.
4802 ** To work around this, the expression tree is not actually changed from
4803 ** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol
4804 ** and the "123" value is hung off of the pLeft pointer.  Code generator
4805 ** routines know to generate the constant "123" instead of looking up the
4806 ** column value.  Also, to avoid collation problems, this optimization is
4807 ** only attempted if the "a=123" term uses the default BINARY collation.
4808 **
4809 ** 2021-05-25 forum post 6a06202608: Another troublesome case is...
4810 **
4811 **    CREATE TABLE t1(x);
4812 **    INSERT INTO t1 VALUES(10.0);
4813 **    SELECT 1 FROM t1 WHERE x=10 AND x LIKE 10;
4814 **
4815 ** The query should return no rows, because the t1.x value is '10.0' not '10'
4816 ** and '10.0' is not LIKE '10'.  But if we are not careful, the first WHERE
4817 ** term "x=10" will cause the second WHERE term to become "10 LIKE 10",
4818 ** resulting in a false positive.  To avoid this, constant propagation for
4819 ** columns with BLOB affinity is only allowed if the constant is used with
4820 ** operators ==, <=, <, >=, >, or IS in a way that will cause the correct
4821 ** type conversions to occur.  See logic associated with the bHasAffBlob flag
4822 ** for details.
4823 */
4824 static int propagateConstants(
4825   Parse *pParse,   /* The parsing context */
4826   Select *p        /* The query in which to propagate constants */
4827 ){
4828   WhereConst x;
4829   Walker w;
4830   int nChng = 0;
4831   x.pParse = pParse;
4832   x.pOomFault = &pParse->db->mallocFailed;
4833   do{
4834     x.nConst = 0;
4835     x.nChng = 0;
4836     x.apExpr = 0;
4837     x.bHasAffBlob = 0;
4838     findConstInWhere(&x, p->pWhere);
4839     if( x.nConst ){
4840       memset(&w, 0, sizeof(w));
4841       w.pParse = pParse;
4842       w.xExprCallback = propagateConstantExprRewrite;
4843       w.xSelectCallback = sqlite3SelectWalkNoop;
4844       w.xSelectCallback2 = 0;
4845       w.walkerDepth = 0;
4846       w.u.pConst = &x;
4847       sqlite3WalkExpr(&w, p->pWhere);
4848       sqlite3DbFree(x.pParse->db, x.apExpr);
4849       nChng += x.nChng;
4850     }
4851   }while( x.nChng );
4852   return nChng;
4853 }
4854 
4855 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4856 # if !defined(SQLITE_OMIT_WINDOWFUNC)
4857 /*
4858 ** This function is called to determine whether or not it is safe to
4859 ** push WHERE clause expression pExpr down to FROM clause sub-query
4860 ** pSubq, which contains at least one window function. Return 1
4861 ** if it is safe and the expression should be pushed down, or 0
4862 ** otherwise.
4863 **
4864 ** It is only safe to push the expression down if it consists only
4865 ** of constants and copies of expressions that appear in the PARTITION
4866 ** BY clause of all window function used by the sub-query. It is safe
4867 ** to filter out entire partitions, but not rows within partitions, as
4868 ** this may change the results of the window functions.
4869 **
4870 ** At the time this function is called it is guaranteed that
4871 **
4872 **   * the sub-query uses only one distinct window frame, and
4873 **   * that the window frame has a PARTITION BY clase.
4874 */
4875 static int pushDownWindowCheck(Parse *pParse, Select *pSubq, Expr *pExpr){
4876   assert( pSubq->pWin->pPartition );
4877   assert( (pSubq->selFlags & SF_MultiPart)==0 );
4878   assert( pSubq->pPrior==0 );
4879   return sqlite3ExprIsConstantOrGroupBy(pParse, pExpr, pSubq->pWin->pPartition);
4880 }
4881 # endif /* SQLITE_OMIT_WINDOWFUNC */
4882 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
4883 
4884 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4885 /*
4886 ** Make copies of relevant WHERE clause terms of the outer query into
4887 ** the WHERE clause of subquery.  Example:
4888 **
4889 **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
4890 **
4891 ** Transformed into:
4892 **
4893 **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
4894 **     WHERE x=5 AND y=10;
4895 **
4896 ** The hope is that the terms added to the inner query will make it more
4897 ** efficient.
4898 **
4899 ** Do not attempt this optimization if:
4900 **
4901 **   (1) (** This restriction was removed on 2017-09-29.  We used to
4902 **           disallow this optimization for aggregate subqueries, but now
4903 **           it is allowed by putting the extra terms on the HAVING clause.
4904 **           The added HAVING clause is pointless if the subquery lacks
4905 **           a GROUP BY clause.  But such a HAVING clause is also harmless
4906 **           so there does not appear to be any reason to add extra logic
4907 **           to suppress it. **)
4908 **
4909 **   (2) The inner query is the recursive part of a common table expression.
4910 **
4911 **   (3) The inner query has a LIMIT clause (since the changes to the WHERE
4912 **       clause would change the meaning of the LIMIT).
4913 **
4914 **   (4) The inner query is the right operand of a LEFT JOIN and the
4915 **       expression to be pushed down does not come from the ON clause
4916 **       on that LEFT JOIN.
4917 **
4918 **   (5) The WHERE clause expression originates in the ON or USING clause
4919 **       of a LEFT JOIN where iCursor is not the right-hand table of that
4920 **       left join.  An example:
4921 **
4922 **           SELECT *
4923 **           FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
4924 **           JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
4925 **           LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
4926 **
4927 **       The correct answer is three rows:  (1,1,NULL),(2,2,8),(2,2,9).
4928 **       But if the (b2=2) term were to be pushed down into the bb subquery,
4929 **       then the (1,1,NULL) row would be suppressed.
4930 **
4931 **   (6) Window functions make things tricky as changes to the WHERE clause
4932 **       of the inner query could change the window over which window
4933 **       functions are calculated. Therefore, do not attempt the optimization
4934 **       if:
4935 **
4936 **     (6a) The inner query uses multiple incompatible window partitions.
4937 **
4938 **     (6b) The inner query is a compound and uses window-functions.
4939 **
4940 **     (6c) The WHERE clause does not consist entirely of constants and
4941 **          copies of expressions found in the PARTITION BY clause of
4942 **          all window-functions used by the sub-query. It is safe to
4943 **          filter out entire partitions, as this does not change the
4944 **          window over which any window-function is calculated.
4945 **
4946 **   (7) The inner query is a Common Table Expression (CTE) that should
4947 **       be materialized.  (This restriction is implemented in the calling
4948 **       routine.)
4949 **
4950 ** Return 0 if no changes are made and non-zero if one or more WHERE clause
4951 ** terms are duplicated into the subquery.
4952 */
4953 static int pushDownWhereTerms(
4954   Parse *pParse,        /* Parse context (for malloc() and error reporting) */
4955   Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
4956   Expr *pWhere,         /* The WHERE clause of the outer query */
4957   SrcItem *pSrc         /* The subquery term of the outer FROM clause */
4958 ){
4959   Expr *pNew;
4960   int nChng = 0;
4961   if( pWhere==0 ) return 0;
4962   if( pSubq->selFlags & (SF_Recursive|SF_MultiPart) ) return 0;
4963   if( pSrc->fg.jointype & (JT_LTORJ|JT_RIGHT) ) return 0;
4964 
4965 #ifndef SQLITE_OMIT_WINDOWFUNC
4966   if( pSubq->pPrior ){
4967     Select *pSel;
4968     for(pSel=pSubq; pSel; pSel=pSel->pPrior){
4969       if( pSel->pWin ) return 0;    /* restriction (6b) */
4970     }
4971   }else{
4972     if( pSubq->pWin && pSubq->pWin->pPartition==0 ) return 0;
4973   }
4974 #endif
4975 
4976 #ifdef SQLITE_DEBUG
4977   /* Only the first term of a compound can have a WITH clause.  But make
4978   ** sure no other terms are marked SF_Recursive in case something changes
4979   ** in the future.
4980   */
4981   {
4982     Select *pX;
4983     for(pX=pSubq; pX; pX=pX->pPrior){
4984       assert( (pX->selFlags & (SF_Recursive))==0 );
4985     }
4986   }
4987 #endif
4988 
4989   if( pSubq->pLimit!=0 ){
4990     return 0; /* restriction (3) */
4991   }
4992   while( pWhere->op==TK_AND ){
4993     nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, pSrc);
4994     pWhere = pWhere->pLeft;
4995   }
4996 
4997 #if 0  /* Legacy code. Checks now done by sqlite3ExprIsTableConstraint() */
4998   if( isLeftJoin
4999    && (ExprHasProperty(pWhere,EP_FromJoin)==0
5000          || pWhere->w.iJoin!=iCursor)
5001   ){
5002     return 0; /* restriction (4) */
5003   }
5004   if( ExprHasProperty(pWhere,EP_FromJoin)
5005    && pWhere->w.iJoin!=iCursor
5006   ){
5007     return 0; /* restriction (5) */
5008   }
5009 #endif
5010 
5011   if( sqlite3ExprIsTableConstraint(pWhere, pSrc) ){
5012     nChng++;
5013     pSubq->selFlags |= SF_PushDown;
5014     while( pSubq ){
5015       SubstContext x;
5016       pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
5017       unsetJoinExpr(pNew, -1);
5018       x.pParse = pParse;
5019       x.iTable = pSrc->iCursor;
5020       x.iNewTable = pSrc->iCursor;
5021       x.isOuterJoin = 0;
5022       x.pEList = pSubq->pEList;
5023       pNew = substExpr(&x, pNew);
5024 #ifndef SQLITE_OMIT_WINDOWFUNC
5025       if( pSubq->pWin && 0==pushDownWindowCheck(pParse, pSubq, pNew) ){
5026         /* Restriction 6c has prevented push-down in this case */
5027         sqlite3ExprDelete(pParse->db, pNew);
5028         nChng--;
5029         break;
5030       }
5031 #endif
5032       if( pSubq->selFlags & SF_Aggregate ){
5033         pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew);
5034       }else{
5035         pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew);
5036       }
5037       pSubq = pSubq->pPrior;
5038     }
5039   }
5040   return nChng;
5041 }
5042 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
5043 
5044 /*
5045 ** The pFunc is the only aggregate function in the query.  Check to see
5046 ** if the query is a candidate for the min/max optimization.
5047 **
5048 ** If the query is a candidate for the min/max optimization, then set
5049 ** *ppMinMax to be an ORDER BY clause to be used for the optimization
5050 ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
5051 ** whether pFunc is a min() or max() function.
5052 **
5053 ** If the query is not a candidate for the min/max optimization, return
5054 ** WHERE_ORDERBY_NORMAL (which must be zero).
5055 **
5056 ** This routine must be called after aggregate functions have been
5057 ** located but before their arguments have been subjected to aggregate
5058 ** analysis.
5059 */
5060 static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
5061   int eRet = WHERE_ORDERBY_NORMAL;      /* Return value */
5062   ExprList *pEList;                     /* Arguments to agg function */
5063   const char *zFunc;                    /* Name of aggregate function pFunc */
5064   ExprList *pOrderBy;
5065   u8 sortFlags = 0;
5066 
5067   assert( *ppMinMax==0 );
5068   assert( pFunc->op==TK_AGG_FUNCTION );
5069   assert( !IsWindowFunc(pFunc) );
5070   assert( ExprUseXList(pFunc) );
5071   pEList = pFunc->x.pList;
5072   if( pEList==0
5073    || pEList->nExpr!=1
5074    || ExprHasProperty(pFunc, EP_WinFunc)
5075    || OptimizationDisabled(db, SQLITE_MinMaxOpt)
5076   ){
5077     return eRet;
5078   }
5079   assert( !ExprHasProperty(pFunc, EP_IntValue) );
5080   zFunc = pFunc->u.zToken;
5081   if( sqlite3StrICmp(zFunc, "min")==0 ){
5082     eRet = WHERE_ORDERBY_MIN;
5083     if( sqlite3ExprCanBeNull(pEList->a[0].pExpr) ){
5084       sortFlags = KEYINFO_ORDER_BIGNULL;
5085     }
5086   }else if( sqlite3StrICmp(zFunc, "max")==0 ){
5087     eRet = WHERE_ORDERBY_MAX;
5088     sortFlags = KEYINFO_ORDER_DESC;
5089   }else{
5090     return eRet;
5091   }
5092   *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
5093   assert( pOrderBy!=0 || db->mallocFailed );
5094   if( pOrderBy ) pOrderBy->a[0].sortFlags = sortFlags;
5095   return eRet;
5096 }
5097 
5098 /*
5099 ** The select statement passed as the first argument is an aggregate query.
5100 ** The second argument is the associated aggregate-info object. This
5101 ** function tests if the SELECT is of the form:
5102 **
5103 **   SELECT count(*) FROM <tbl>
5104 **
5105 ** where table is a database table, not a sub-select or view. If the query
5106 ** does match this pattern, then a pointer to the Table object representing
5107 ** <tbl> is returned. Otherwise, NULL is returned.
5108 **
5109 ** This routine checks to see if it is safe to use the count optimization.
5110 ** A correct answer is still obtained (though perhaps more slowly) if
5111 ** this routine returns NULL when it could have returned a table pointer.
5112 ** But returning the pointer when NULL should have been returned can
5113 ** result in incorrect answers and/or crashes.  So, when in doubt, return NULL.
5114 */
5115 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
5116   Table *pTab;
5117   Expr *pExpr;
5118 
5119   assert( !p->pGroupBy );
5120 
5121   if( p->pWhere
5122    || p->pEList->nExpr!=1
5123    || p->pSrc->nSrc!=1
5124    || p->pSrc->a[0].pSelect
5125    || pAggInfo->nFunc!=1
5126   ){
5127     return 0;
5128   }
5129   pTab = p->pSrc->a[0].pTab;
5130   assert( pTab!=0 );
5131   assert( !IsView(pTab) );
5132   if( !IsOrdinaryTable(pTab) ) return 0;
5133   pExpr = p->pEList->a[0].pExpr;
5134   assert( pExpr!=0 );
5135   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
5136   if( pExpr->pAggInfo!=pAggInfo ) return 0;
5137   if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
5138   assert( pAggInfo->aFunc[0].pFExpr==pExpr );
5139   testcase( ExprHasProperty(pExpr, EP_Distinct) );
5140   testcase( ExprHasProperty(pExpr, EP_WinFunc) );
5141   if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0;
5142 
5143   return pTab;
5144 }
5145 
5146 /*
5147 ** If the source-list item passed as an argument was augmented with an
5148 ** INDEXED BY clause, then try to locate the specified index. If there
5149 ** was such a clause and the named index cannot be found, return
5150 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
5151 ** pFrom->pIndex and return SQLITE_OK.
5152 */
5153 int sqlite3IndexedByLookup(Parse *pParse, SrcItem *pFrom){
5154   Table *pTab = pFrom->pTab;
5155   char *zIndexedBy = pFrom->u1.zIndexedBy;
5156   Index *pIdx;
5157   assert( pTab!=0 );
5158   assert( pFrom->fg.isIndexedBy!=0 );
5159 
5160   for(pIdx=pTab->pIndex;
5161       pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
5162       pIdx=pIdx->pNext
5163   );
5164   if( !pIdx ){
5165     sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
5166     pParse->checkSchema = 1;
5167     return SQLITE_ERROR;
5168   }
5169   assert( pFrom->fg.isCte==0 );
5170   pFrom->u2.pIBIndex = pIdx;
5171   return SQLITE_OK;
5172 }
5173 
5174 /*
5175 ** Detect compound SELECT statements that use an ORDER BY clause with
5176 ** an alternative collating sequence.
5177 **
5178 **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
5179 **
5180 ** These are rewritten as a subquery:
5181 **
5182 **    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
5183 **     ORDER BY ... COLLATE ...
5184 **
5185 ** This transformation is necessary because the multiSelectOrderBy() routine
5186 ** above that generates the code for a compound SELECT with an ORDER BY clause
5187 ** uses a merge algorithm that requires the same collating sequence on the
5188 ** result columns as on the ORDER BY clause.  See ticket
5189 ** http://www.sqlite.org/src/info/6709574d2a
5190 **
5191 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
5192 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
5193 ** there are COLLATE terms in the ORDER BY.
5194 */
5195 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
5196   int i;
5197   Select *pNew;
5198   Select *pX;
5199   sqlite3 *db;
5200   struct ExprList_item *a;
5201   SrcList *pNewSrc;
5202   Parse *pParse;
5203   Token dummy;
5204 
5205   if( p->pPrior==0 ) return WRC_Continue;
5206   if( p->pOrderBy==0 ) return WRC_Continue;
5207   for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
5208   if( pX==0 ) return WRC_Continue;
5209   a = p->pOrderBy->a;
5210 #ifndef SQLITE_OMIT_WINDOWFUNC
5211   /* If iOrderByCol is already non-zero, then it has already been matched
5212   ** to a result column of the SELECT statement. This occurs when the
5213   ** SELECT is rewritten for window-functions processing and then passed
5214   ** to sqlite3SelectPrep() and similar a second time. The rewriting done
5215   ** by this function is not required in this case. */
5216   if( a[0].u.x.iOrderByCol ) return WRC_Continue;
5217 #endif
5218   for(i=p->pOrderBy->nExpr-1; i>=0; i--){
5219     if( a[i].pExpr->flags & EP_Collate ) break;
5220   }
5221   if( i<0 ) return WRC_Continue;
5222 
5223   /* If we reach this point, that means the transformation is required. */
5224 
5225   pParse = pWalker->pParse;
5226   db = pParse->db;
5227   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
5228   if( pNew==0 ) return WRC_Abort;
5229   memset(&dummy, 0, sizeof(dummy));
5230   pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0);
5231   if( pNewSrc==0 ) return WRC_Abort;
5232   *pNew = *p;
5233   p->pSrc = pNewSrc;
5234   p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
5235   p->op = TK_SELECT;
5236   p->pWhere = 0;
5237   pNew->pGroupBy = 0;
5238   pNew->pHaving = 0;
5239   pNew->pOrderBy = 0;
5240   p->pPrior = 0;
5241   p->pNext = 0;
5242   p->pWith = 0;
5243 #ifndef SQLITE_OMIT_WINDOWFUNC
5244   p->pWinDefn = 0;
5245 #endif
5246   p->selFlags &= ~SF_Compound;
5247   assert( (p->selFlags & SF_Converted)==0 );
5248   p->selFlags |= SF_Converted;
5249   assert( pNew->pPrior!=0 );
5250   pNew->pPrior->pNext = pNew;
5251   pNew->pLimit = 0;
5252   return WRC_Continue;
5253 }
5254 
5255 /*
5256 ** Check to see if the FROM clause term pFrom has table-valued function
5257 ** arguments.  If it does, leave an error message in pParse and return
5258 ** non-zero, since pFrom is not allowed to be a table-valued function.
5259 */
5260 static int cannotBeFunction(Parse *pParse, SrcItem *pFrom){
5261   if( pFrom->fg.isTabFunc ){
5262     sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
5263     return 1;
5264   }
5265   return 0;
5266 }
5267 
5268 #ifndef SQLITE_OMIT_CTE
5269 /*
5270 ** Argument pWith (which may be NULL) points to a linked list of nested
5271 ** WITH contexts, from inner to outermost. If the table identified by
5272 ** FROM clause element pItem is really a common-table-expression (CTE)
5273 ** then return a pointer to the CTE definition for that table. Otherwise
5274 ** return NULL.
5275 **
5276 ** If a non-NULL value is returned, set *ppContext to point to the With
5277 ** object that the returned CTE belongs to.
5278 */
5279 static struct Cte *searchWith(
5280   With *pWith,                    /* Current innermost WITH clause */
5281   SrcItem *pItem,                 /* FROM clause element to resolve */
5282   With **ppContext                /* OUT: WITH clause return value belongs to */
5283 ){
5284   const char *zName = pItem->zName;
5285   With *p;
5286   assert( pItem->zDatabase==0 );
5287   assert( zName!=0 );
5288   for(p=pWith; p; p=p->pOuter){
5289     int i;
5290     for(i=0; i<p->nCte; i++){
5291       if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
5292         *ppContext = p;
5293         return &p->a[i];
5294       }
5295     }
5296     if( p->bView ) break;
5297   }
5298   return 0;
5299 }
5300 
5301 /* The code generator maintains a stack of active WITH clauses
5302 ** with the inner-most WITH clause being at the top of the stack.
5303 **
5304 ** This routine pushes the WITH clause passed as the second argument
5305 ** onto the top of the stack. If argument bFree is true, then this
5306 ** WITH clause will never be popped from the stack but should instead
5307 ** be freed along with the Parse object. In other cases, when
5308 ** bFree==0, the With object will be freed along with the SELECT
5309 ** statement with which it is associated.
5310 **
5311 ** This routine returns a copy of pWith.  Or, if bFree is true and
5312 ** the pWith object is destroyed immediately due to an OOM condition,
5313 ** then this routine return NULL.
5314 **
5315 ** If bFree is true, do not continue to use the pWith pointer after
5316 ** calling this routine,  Instead, use only the return value.
5317 */
5318 With *sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
5319   if( pWith ){
5320     if( bFree ){
5321       pWith = (With*)sqlite3ParserAddCleanup(pParse,
5322                       (void(*)(sqlite3*,void*))sqlite3WithDelete,
5323                       pWith);
5324       if( pWith==0 ) return 0;
5325     }
5326     if( pParse->nErr==0 ){
5327       assert( pParse->pWith!=pWith );
5328       pWith->pOuter = pParse->pWith;
5329       pParse->pWith = pWith;
5330     }
5331   }
5332   return pWith;
5333 }
5334 
5335 /*
5336 ** This function checks if argument pFrom refers to a CTE declared by
5337 ** a WITH clause on the stack currently maintained by the parser (on the
5338 ** pParse->pWith linked list).  And if currently processing a CTE
5339 ** CTE expression, through routine checks to see if the reference is
5340 ** a recursive reference to the CTE.
5341 **
5342 ** If pFrom matches a CTE according to either of these two above, pFrom->pTab
5343 ** and other fields are populated accordingly.
5344 **
5345 ** Return 0 if no match is found.
5346 ** Return 1 if a match is found.
5347 ** Return 2 if an error condition is detected.
5348 */
5349 static int resolveFromTermToCte(
5350   Parse *pParse,                  /* The parsing context */
5351   Walker *pWalker,                /* Current tree walker */
5352   SrcItem *pFrom                  /* The FROM clause term to check */
5353 ){
5354   Cte *pCte;               /* Matched CTE (or NULL if no match) */
5355   With *pWith;             /* The matching WITH */
5356 
5357   assert( pFrom->pTab==0 );
5358   if( pParse->pWith==0 ){
5359     /* There are no WITH clauses in the stack.  No match is possible */
5360     return 0;
5361   }
5362   if( pParse->nErr ){
5363     /* Prior errors might have left pParse->pWith in a goofy state, so
5364     ** go no further. */
5365     return 0;
5366   }
5367   if( pFrom->zDatabase!=0 ){
5368     /* The FROM term contains a schema qualifier (ex: main.t1) and so
5369     ** it cannot possibly be a CTE reference. */
5370     return 0;
5371   }
5372   if( pFrom->fg.notCte ){
5373     /* The FROM term is specifically excluded from matching a CTE.
5374     **   (1)  It is part of a trigger that used to have zDatabase but had
5375     **        zDatabase removed by sqlite3FixTriggerStep().
5376     **   (2)  This is the first term in the FROM clause of an UPDATE.
5377     */
5378     return 0;
5379   }
5380   pCte = searchWith(pParse->pWith, pFrom, &pWith);
5381   if( pCte ){
5382     sqlite3 *db = pParse->db;
5383     Table *pTab;
5384     ExprList *pEList;
5385     Select *pSel;
5386     Select *pLeft;                /* Left-most SELECT statement */
5387     Select *pRecTerm;             /* Left-most recursive term */
5388     int bMayRecursive;            /* True if compound joined by UNION [ALL] */
5389     With *pSavedWith;             /* Initial value of pParse->pWith */
5390     int iRecTab = -1;             /* Cursor for recursive table */
5391     CteUse *pCteUse;
5392 
5393     /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
5394     ** recursive reference to CTE pCte. Leave an error in pParse and return
5395     ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
5396     ** In this case, proceed.  */
5397     if( pCte->zCteErr ){
5398       sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
5399       return 2;
5400     }
5401     if( cannotBeFunction(pParse, pFrom) ) return 2;
5402 
5403     assert( pFrom->pTab==0 );
5404     pTab = sqlite3DbMallocZero(db, sizeof(Table));
5405     if( pTab==0 ) return 2;
5406     pCteUse = pCte->pUse;
5407     if( pCteUse==0 ){
5408       pCte->pUse = pCteUse = sqlite3DbMallocZero(db, sizeof(pCteUse[0]));
5409       if( pCteUse==0
5410        || sqlite3ParserAddCleanup(pParse,sqlite3DbFree,pCteUse)==0
5411       ){
5412         sqlite3DbFree(db, pTab);
5413         return 2;
5414       }
5415       pCteUse->eM10d = pCte->eM10d;
5416     }
5417     pFrom->pTab = pTab;
5418     pTab->nTabRef = 1;
5419     pTab->zName = sqlite3DbStrDup(db, pCte->zName);
5420     pTab->iPKey = -1;
5421     pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
5422     pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
5423     pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
5424     if( db->mallocFailed ) return 2;
5425     pFrom->pSelect->selFlags |= SF_CopyCte;
5426     assert( pFrom->pSelect );
5427     if( pFrom->fg.isIndexedBy ){
5428       sqlite3ErrorMsg(pParse, "no such index: \"%s\"", pFrom->u1.zIndexedBy);
5429       return 2;
5430     }
5431     pFrom->fg.isCte = 1;
5432     pFrom->u2.pCteUse = pCteUse;
5433     pCteUse->nUse++;
5434     if( pCteUse->nUse>=2 && pCteUse->eM10d==M10d_Any ){
5435       pCteUse->eM10d = M10d_Yes;
5436     }
5437 
5438     /* Check if this is a recursive CTE. */
5439     pRecTerm = pSel = pFrom->pSelect;
5440     bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
5441     while( bMayRecursive && pRecTerm->op==pSel->op ){
5442       int i;
5443       SrcList *pSrc = pRecTerm->pSrc;
5444       assert( pRecTerm->pPrior!=0 );
5445       for(i=0; i<pSrc->nSrc; i++){
5446         SrcItem *pItem = &pSrc->a[i];
5447         if( pItem->zDatabase==0
5448          && pItem->zName!=0
5449          && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
5450         ){
5451           pItem->pTab = pTab;
5452           pTab->nTabRef++;
5453           pItem->fg.isRecursive = 1;
5454           if( pRecTerm->selFlags & SF_Recursive ){
5455             sqlite3ErrorMsg(pParse,
5456                "multiple references to recursive table: %s", pCte->zName
5457             );
5458             return 2;
5459           }
5460           pRecTerm->selFlags |= SF_Recursive;
5461           if( iRecTab<0 ) iRecTab = pParse->nTab++;
5462           pItem->iCursor = iRecTab;
5463         }
5464       }
5465       if( (pRecTerm->selFlags & SF_Recursive)==0 ) break;
5466       pRecTerm = pRecTerm->pPrior;
5467     }
5468 
5469     pCte->zCteErr = "circular reference: %s";
5470     pSavedWith = pParse->pWith;
5471     pParse->pWith = pWith;
5472     if( pSel->selFlags & SF_Recursive ){
5473       int rc;
5474       assert( pRecTerm!=0 );
5475       assert( (pRecTerm->selFlags & SF_Recursive)==0 );
5476       assert( pRecTerm->pNext!=0 );
5477       assert( (pRecTerm->pNext->selFlags & SF_Recursive)!=0 );
5478       assert( pRecTerm->pWith==0 );
5479       pRecTerm->pWith = pSel->pWith;
5480       rc = sqlite3WalkSelect(pWalker, pRecTerm);
5481       pRecTerm->pWith = 0;
5482       if( rc ){
5483         pParse->pWith = pSavedWith;
5484         return 2;
5485       }
5486     }else{
5487       if( sqlite3WalkSelect(pWalker, pSel) ){
5488         pParse->pWith = pSavedWith;
5489         return 2;
5490       }
5491     }
5492     pParse->pWith = pWith;
5493 
5494     for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
5495     pEList = pLeft->pEList;
5496     if( pCte->pCols ){
5497       if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
5498         sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
5499             pCte->zName, pEList->nExpr, pCte->pCols->nExpr
5500         );
5501         pParse->pWith = pSavedWith;
5502         return 2;
5503       }
5504       pEList = pCte->pCols;
5505     }
5506 
5507     sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
5508     if( bMayRecursive ){
5509       if( pSel->selFlags & SF_Recursive ){
5510         pCte->zCteErr = "multiple recursive references: %s";
5511       }else{
5512         pCte->zCteErr = "recursive reference in a subquery: %s";
5513       }
5514       sqlite3WalkSelect(pWalker, pSel);
5515     }
5516     pCte->zCteErr = 0;
5517     pParse->pWith = pSavedWith;
5518     return 1;  /* Success */
5519   }
5520   return 0;  /* No match */
5521 }
5522 #endif
5523 
5524 #ifndef SQLITE_OMIT_CTE
5525 /*
5526 ** If the SELECT passed as the second argument has an associated WITH
5527 ** clause, pop it from the stack stored as part of the Parse object.
5528 **
5529 ** This function is used as the xSelectCallback2() callback by
5530 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
5531 ** names and other FROM clause elements.
5532 */
5533 void sqlite3SelectPopWith(Walker *pWalker, Select *p){
5534   Parse *pParse = pWalker->pParse;
5535   if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
5536     With *pWith = findRightmost(p)->pWith;
5537     if( pWith!=0 ){
5538       assert( pParse->pWith==pWith || pParse->nErr );
5539       pParse->pWith = pWith->pOuter;
5540     }
5541   }
5542 }
5543 #endif
5544 
5545 /*
5546 ** The SrcList_item structure passed as the second argument represents a
5547 ** sub-query in the FROM clause of a SELECT statement. This function
5548 ** allocates and populates the SrcList_item.pTab object. If successful,
5549 ** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
5550 ** SQLITE_NOMEM.
5551 */
5552 int sqlite3ExpandSubquery(Parse *pParse, SrcItem *pFrom){
5553   Select *pSel = pFrom->pSelect;
5554   Table *pTab;
5555 
5556   assert( pSel );
5557   pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
5558   if( pTab==0 ) return SQLITE_NOMEM;
5559   pTab->nTabRef = 1;
5560   if( pFrom->zAlias ){
5561     pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
5562   }else{
5563     pTab->zName = sqlite3MPrintf(pParse->db, "%!S", pFrom);
5564   }
5565   while( pSel->pPrior ){ pSel = pSel->pPrior; }
5566   sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
5567   pTab->iPKey = -1;
5568   pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
5569 #ifndef SQLITE_ALLOW_ROWID_IN_VIEW
5570   /* The usual case - do not allow ROWID on a subquery */
5571   pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
5572 #else
5573   pTab->tabFlags |= TF_Ephemeral;  /* Legacy compatibility mode */
5574 #endif
5575   return pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
5576 }
5577 
5578 
5579 /*
5580 ** Check the N SrcItem objects to the right of pBase.  (N might be zero!)
5581 ** If any of those SrcItem objects have a USING clause containing zName
5582 ** then return true.
5583 **
5584 ** If N is zero, or none of the N SrcItem objects to the right of pBase
5585 ** contains a USING clause, or if none of the USING clauses contain zName,
5586 ** then return false.
5587 */
5588 static int inAnyUsingClause(
5589   const char *zName, /* Name we are looking for */
5590   SrcItem *pBase,    /* The base SrcItem.  Looking at pBase[1] and following */
5591   int N              /* How many SrcItems to check */
5592 ){
5593   while( N>0 ){
5594     N--;
5595     pBase++;
5596     if( pBase->fg.isUsing==0 ) continue;
5597     if( NEVER(pBase->u3.pUsing==0) ) continue;
5598     if( sqlite3IdListIndex(pBase->u3.pUsing, zName)>=0 ) return 1;
5599   }
5600   return 0;
5601 }
5602 
5603 
5604 /*
5605 ** This routine is a Walker callback for "expanding" a SELECT statement.
5606 ** "Expanding" means to do the following:
5607 **
5608 **    (1)  Make sure VDBE cursor numbers have been assigned to every
5609 **         element of the FROM clause.
5610 **
5611 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
5612 **         defines FROM clause.  When views appear in the FROM clause,
5613 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
5614 **         that implements the view.  A copy is made of the view's SELECT
5615 **         statement so that we can freely modify or delete that statement
5616 **         without worrying about messing up the persistent representation
5617 **         of the view.
5618 **
5619 **    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
5620 **         on joins and the ON and USING clause of joins.
5621 **
5622 **    (4)  Scan the list of columns in the result set (pEList) looking
5623 **         for instances of the "*" operator or the TABLE.* operator.
5624 **         If found, expand each "*" to be every column in every table
5625 **         and TABLE.* to be every column in TABLE.
5626 **
5627 */
5628 static int selectExpander(Walker *pWalker, Select *p){
5629   Parse *pParse = pWalker->pParse;
5630   int i, j, k, rc;
5631   SrcList *pTabList;
5632   ExprList *pEList;
5633   SrcItem *pFrom;
5634   sqlite3 *db = pParse->db;
5635   Expr *pE, *pRight, *pExpr;
5636   u16 selFlags = p->selFlags;
5637   u32 elistFlags = 0;
5638 
5639   p->selFlags |= SF_Expanded;
5640   if( db->mallocFailed  ){
5641     return WRC_Abort;
5642   }
5643   assert( p->pSrc!=0 );
5644   if( (selFlags & SF_Expanded)!=0 ){
5645     return WRC_Prune;
5646   }
5647   if( pWalker->eCode ){
5648     /* Renumber selId because it has been copied from a view */
5649     p->selId = ++pParse->nSelect;
5650   }
5651   pTabList = p->pSrc;
5652   pEList = p->pEList;
5653   if( pParse->pWith && (p->selFlags & SF_View) ){
5654     if( p->pWith==0 ){
5655       p->pWith = (With*)sqlite3DbMallocZero(db, sizeof(With));
5656       if( p->pWith==0 ){
5657         return WRC_Abort;
5658       }
5659     }
5660     p->pWith->bView = 1;
5661   }
5662   sqlite3WithPush(pParse, p->pWith, 0);
5663 
5664   /* Make sure cursor numbers have been assigned to all entries in
5665   ** the FROM clause of the SELECT statement.
5666   */
5667   sqlite3SrcListAssignCursors(pParse, pTabList);
5668 
5669   /* Look up every table named in the FROM clause of the select.  If
5670   ** an entry of the FROM clause is a subquery instead of a table or view,
5671   ** then create a transient table structure to describe the subquery.
5672   */
5673   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
5674     Table *pTab;
5675     assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
5676     if( pFrom->pTab ) continue;
5677     assert( pFrom->fg.isRecursive==0 );
5678     if( pFrom->zName==0 ){
5679 #ifndef SQLITE_OMIT_SUBQUERY
5680       Select *pSel = pFrom->pSelect;
5681       /* A sub-query in the FROM clause of a SELECT */
5682       assert( pSel!=0 );
5683       assert( pFrom->pTab==0 );
5684       if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
5685       if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;
5686 #endif
5687 #ifndef SQLITE_OMIT_CTE
5688     }else if( (rc = resolveFromTermToCte(pParse, pWalker, pFrom))!=0 ){
5689       if( rc>1 ) return WRC_Abort;
5690       pTab = pFrom->pTab;
5691       assert( pTab!=0 );
5692 #endif
5693     }else{
5694       /* An ordinary table or view name in the FROM clause */
5695       assert( pFrom->pTab==0 );
5696       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
5697       if( pTab==0 ) return WRC_Abort;
5698       if( pTab->nTabRef>=0xffff ){
5699         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
5700            pTab->zName);
5701         pFrom->pTab = 0;
5702         return WRC_Abort;
5703       }
5704       pTab->nTabRef++;
5705       if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
5706         return WRC_Abort;
5707       }
5708 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
5709       if( !IsOrdinaryTable(pTab) ){
5710         i16 nCol;
5711         u8 eCodeOrig = pWalker->eCode;
5712         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
5713         assert( pFrom->pSelect==0 );
5714         if( IsView(pTab) ){
5715           if( (db->flags & SQLITE_EnableView)==0
5716            && pTab->pSchema!=db->aDb[1].pSchema
5717           ){
5718             sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited",
5719               pTab->zName);
5720           }
5721           pFrom->pSelect = sqlite3SelectDup(db, pTab->u.view.pSelect, 0);
5722         }
5723 #ifndef SQLITE_OMIT_VIRTUALTABLE
5724         else if( ALWAYS(IsVirtual(pTab))
5725          && pFrom->fg.fromDDL
5726          && ALWAYS(pTab->u.vtab.p!=0)
5727          && pTab->u.vtab.p->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0)
5728         ){
5729           sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"",
5730                                   pTab->zName);
5731         }
5732         assert( SQLITE_VTABRISK_Normal==1 && SQLITE_VTABRISK_High==2 );
5733 #endif
5734         nCol = pTab->nCol;
5735         pTab->nCol = -1;
5736         pWalker->eCode = 1;  /* Turn on Select.selId renumbering */
5737         sqlite3WalkSelect(pWalker, pFrom->pSelect);
5738         pWalker->eCode = eCodeOrig;
5739         pTab->nCol = nCol;
5740       }
5741 #endif
5742     }
5743 
5744     /* Locate the index named by the INDEXED BY clause, if any. */
5745     if( pFrom->fg.isIndexedBy && sqlite3IndexedByLookup(pParse, pFrom) ){
5746       return WRC_Abort;
5747     }
5748   }
5749 
5750   /* Process NATURAL keywords, and ON and USING clauses of joins.
5751   */
5752   assert( db->mallocFailed==0 || pParse->nErr!=0 );
5753   if( pParse->nErr || sqlite3ProcessJoin(pParse, p) ){
5754     return WRC_Abort;
5755   }
5756 
5757   /* For every "*" that occurs in the column list, insert the names of
5758   ** all columns in all tables.  And for every TABLE.* insert the names
5759   ** of all columns in TABLE.  The parser inserted a special expression
5760   ** with the TK_ASTERISK operator for each "*" that it found in the column
5761   ** list.  The following code just has to locate the TK_ASTERISK
5762   ** expressions and expand each one to the list of all columns in
5763   ** all tables.
5764   **
5765   ** The first loop just checks to see if there are any "*" operators
5766   ** that need expanding.
5767   */
5768   for(k=0; k<pEList->nExpr; k++){
5769     pE = pEList->a[k].pExpr;
5770     if( pE->op==TK_ASTERISK ) break;
5771     assert( pE->op!=TK_DOT || pE->pRight!=0 );
5772     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
5773     if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
5774     elistFlags |= pE->flags;
5775   }
5776   if( k<pEList->nExpr ){
5777     /*
5778     ** If we get here it means the result set contains one or more "*"
5779     ** operators that need to be expanded.  Loop through each expression
5780     ** in the result set and expand them one by one.
5781     */
5782     struct ExprList_item *a = pEList->a;
5783     ExprList *pNew = 0;
5784     int flags = pParse->db->flags;
5785     int longNames = (flags & SQLITE_FullColNames)!=0
5786                       && (flags & SQLITE_ShortColNames)==0;
5787 
5788     for(k=0; k<pEList->nExpr; k++){
5789       pE = a[k].pExpr;
5790       elistFlags |= pE->flags;
5791       pRight = pE->pRight;
5792       assert( pE->op!=TK_DOT || pRight!=0 );
5793       if( pE->op!=TK_ASTERISK
5794        && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
5795       ){
5796         /* This particular expression does not need to be expanded.
5797         */
5798         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
5799         if( pNew ){
5800           pNew->a[pNew->nExpr-1].zEName = a[k].zEName;
5801           pNew->a[pNew->nExpr-1].eEName = a[k].eEName;
5802           a[k].zEName = 0;
5803         }
5804         a[k].pExpr = 0;
5805       }else{
5806         /* This expression is a "*" or a "TABLE.*" and needs to be
5807         ** expanded. */
5808         int tableSeen = 0;      /* Set to 1 when TABLE matches */
5809         char *zTName = 0;       /* text of name of TABLE */
5810         if( pE->op==TK_DOT ){
5811           assert( pE->pLeft!=0 );
5812           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
5813           zTName = pE->pLeft->u.zToken;
5814         }
5815         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
5816           Table *pTab = pFrom->pTab;   /* Table for this data source */
5817           ExprList *pNestedFrom;       /* Result-set of a nested FROM clause */
5818           char *zTabName;              /* AS name for this data source */
5819           const char *zSchemaName = 0; /* Schema name for this data source */
5820           int iDb;                     /* Schema index for this data src */
5821 
5822           if( (zTabName = pFrom->zAlias)==0 ){
5823             zTabName = pTab->zName;
5824           }
5825           if( db->mallocFailed ) break;
5826           assert( pFrom->fg.isNestedFrom == IsNestedFrom(pFrom->pSelect) );
5827           if( pFrom->fg.isNestedFrom ){
5828             assert( pFrom->pSelect!=0 );
5829             pNestedFrom = pFrom->pSelect->pEList;
5830             assert( pNestedFrom!=0 );
5831             assert( pNestedFrom->nExpr==pTab->nCol );
5832           }else{
5833             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
5834               continue;
5835             }
5836             pNestedFrom = 0;
5837             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
5838             zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
5839           }
5840           for(j=0; j<pTab->nCol; j++){
5841             char *zName = pTab->aCol[j].zCnName;
5842             struct ExprList_item *pX; /* Newly added ExprList term */
5843 
5844             assert( zName );
5845             if( zTName
5846              && pNestedFrom
5847              && sqlite3MatchEName(&pNestedFrom->a[j], 0, zTName, 0)==0
5848             ){
5849               continue;
5850             }
5851 
5852             /* If a column is marked as 'hidden', omit it from the expanded
5853             ** result-set list unless the SELECT has the SF_IncludeHidden
5854             ** bit set.
5855             */
5856             if( (p->selFlags & SF_IncludeHidden)==0
5857              && IsHiddenColumn(&pTab->aCol[j])
5858             ){
5859               continue;
5860             }
5861             tableSeen = 1;
5862 
5863             if( i>0 && zTName==0 ){
5864               if( pFrom->fg.isUsing
5865                && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0
5866               ){
5867                 /* In a join with a USING clause, omit columns in the
5868                 ** using clause from the table on the right. */
5869                 continue;
5870               }
5871             }
5872             pRight = sqlite3Expr(db, TK_ID, zName);
5873             if( (pTabList->nSrc>1
5874                  && (  (pFrom->fg.jointype & JT_LTORJ)==0
5875                      || !inAnyUsingClause(zName,pFrom,pTabList->nSrc-i-1)
5876                     )
5877                 )
5878              || IN_RENAME_OBJECT
5879             ){
5880               Expr *pLeft;
5881               pLeft = sqlite3Expr(db, TK_ID, zTabName);
5882               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
5883               if( IN_RENAME_OBJECT && pE->pLeft ){
5884                 sqlite3RenameTokenRemap(pParse, pLeft, pE->pLeft);
5885               }
5886               if( zSchemaName ){
5887                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
5888                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
5889               }
5890             }else{
5891               pExpr = pRight;
5892             }
5893             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
5894             if( pNew==0 ){
5895               break;  /* OOM */
5896             }
5897             pX = &pNew->a[pNew->nExpr-1];
5898             assert( pX->zEName==0 );
5899             if( (selFlags & SF_NestedFrom)!=0 && !IN_RENAME_OBJECT ){
5900               if( pNestedFrom ){
5901                 pX->zEName = sqlite3DbStrDup(db, pNestedFrom->a[j].zEName);
5902                 testcase( pX->zEName==0 );
5903               }else{
5904                 pX->zEName = sqlite3MPrintf(db, "%s.%s.%s",
5905                                            zSchemaName, zTabName, zName);
5906                 testcase( pX->zEName==0 );
5907               }
5908               pX->eEName = ENAME_TAB;
5909             }else if( longNames ){
5910               pX->zEName = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
5911               pX->eEName = ENAME_NAME;
5912             }else{
5913               pX->zEName = sqlite3DbStrDup(db, zName);
5914               pX->eEName = ENAME_NAME;
5915             }
5916           }
5917         }
5918         if( !tableSeen ){
5919           if( zTName ){
5920             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
5921           }else{
5922             sqlite3ErrorMsg(pParse, "no tables specified");
5923           }
5924         }
5925       }
5926     }
5927     sqlite3ExprListDelete(db, pEList);
5928     p->pEList = pNew;
5929   }
5930   if( p->pEList ){
5931     if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
5932       sqlite3ErrorMsg(pParse, "too many columns in result set");
5933       return WRC_Abort;
5934     }
5935     if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
5936       p->selFlags |= SF_ComplexResult;
5937     }
5938   }
5939 #if TREETRACE_ENABLED
5940   if( sqlite3TreeTrace & 0x100 ){
5941     SELECTTRACE(0x100,pParse,p,("After result-set wildcard expansion:\n"));
5942     sqlite3TreeViewSelect(0, p, 0);
5943   }
5944 #endif
5945   return WRC_Continue;
5946 }
5947 
5948 #if SQLITE_DEBUG
5949 /*
5950 ** Always assert.  This xSelectCallback2 implementation proves that the
5951 ** xSelectCallback2 is never invoked.
5952 */
5953 void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
5954   UNUSED_PARAMETER2(NotUsed, NotUsed2);
5955   assert( 0 );
5956 }
5957 #endif
5958 /*
5959 ** This routine "expands" a SELECT statement and all of its subqueries.
5960 ** For additional information on what it means to "expand" a SELECT
5961 ** statement, see the comment on the selectExpand worker callback above.
5962 **
5963 ** Expanding a SELECT statement is the first step in processing a
5964 ** SELECT statement.  The SELECT statement must be expanded before
5965 ** name resolution is performed.
5966 **
5967 ** If anything goes wrong, an error message is written into pParse.
5968 ** The calling function can detect the problem by looking at pParse->nErr
5969 ** and/or pParse->db->mallocFailed.
5970 */
5971 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
5972   Walker w;
5973   w.xExprCallback = sqlite3ExprWalkNoop;
5974   w.pParse = pParse;
5975   if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
5976     w.xSelectCallback = convertCompoundSelectToSubquery;
5977     w.xSelectCallback2 = 0;
5978     sqlite3WalkSelect(&w, pSelect);
5979   }
5980   w.xSelectCallback = selectExpander;
5981   w.xSelectCallback2 = sqlite3SelectPopWith;
5982   w.eCode = 0;
5983   sqlite3WalkSelect(&w, pSelect);
5984 }
5985 
5986 
5987 #ifndef SQLITE_OMIT_SUBQUERY
5988 /*
5989 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
5990 ** interface.
5991 **
5992 ** For each FROM-clause subquery, add Column.zType and Column.zColl
5993 ** information to the Table structure that represents the result set
5994 ** of that subquery.
5995 **
5996 ** The Table structure that represents the result set was constructed
5997 ** by selectExpander() but the type and collation information was omitted
5998 ** at that point because identifiers had not yet been resolved.  This
5999 ** routine is called after identifier resolution.
6000 */
6001 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
6002   Parse *pParse;
6003   int i;
6004   SrcList *pTabList;
6005   SrcItem *pFrom;
6006 
6007   assert( p->selFlags & SF_Resolved );
6008   if( p->selFlags & SF_HasTypeInfo ) return;
6009   p->selFlags |= SF_HasTypeInfo;
6010   pParse = pWalker->pParse;
6011   pTabList = p->pSrc;
6012   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
6013     Table *pTab = pFrom->pTab;
6014     assert( pTab!=0 );
6015     if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
6016       /* A sub-query in the FROM clause of a SELECT */
6017       Select *pSel = pFrom->pSelect;
6018       if( pSel ){
6019         while( pSel->pPrior ) pSel = pSel->pPrior;
6020         sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel,
6021                                                SQLITE_AFF_NONE);
6022       }
6023     }
6024   }
6025 }
6026 #endif
6027 
6028 
6029 /*
6030 ** This routine adds datatype and collating sequence information to
6031 ** the Table structures of all FROM-clause subqueries in a
6032 ** SELECT statement.
6033 **
6034 ** Use this routine after name resolution.
6035 */
6036 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
6037 #ifndef SQLITE_OMIT_SUBQUERY
6038   Walker w;
6039   w.xSelectCallback = sqlite3SelectWalkNoop;
6040   w.xSelectCallback2 = selectAddSubqueryTypeInfo;
6041   w.xExprCallback = sqlite3ExprWalkNoop;
6042   w.pParse = pParse;
6043   sqlite3WalkSelect(&w, pSelect);
6044 #endif
6045 }
6046 
6047 
6048 /*
6049 ** This routine sets up a SELECT statement for processing.  The
6050 ** following is accomplished:
6051 **
6052 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
6053 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
6054 **     *  ON and USING clauses are shifted into WHERE statements
6055 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
6056 **     *  Identifiers in expression are matched to tables.
6057 **
6058 ** This routine acts recursively on all subqueries within the SELECT.
6059 */
6060 void sqlite3SelectPrep(
6061   Parse *pParse,         /* The parser context */
6062   Select *p,             /* The SELECT statement being coded. */
6063   NameContext *pOuterNC  /* Name context for container */
6064 ){
6065   assert( p!=0 || pParse->db->mallocFailed );
6066   assert( pParse->db->pParse==pParse );
6067   if( pParse->db->mallocFailed ) return;
6068   if( p->selFlags & SF_HasTypeInfo ) return;
6069   sqlite3SelectExpand(pParse, p);
6070   if( pParse->nErr ) return;
6071   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
6072   if( pParse->nErr ) return;
6073   sqlite3SelectAddTypeInfo(pParse, p);
6074 }
6075 
6076 /*
6077 ** Reset the aggregate accumulator.
6078 **
6079 ** The aggregate accumulator is a set of memory cells that hold
6080 ** intermediate results while calculating an aggregate.  This
6081 ** routine generates code that stores NULLs in all of those memory
6082 ** cells.
6083 */
6084 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
6085   Vdbe *v = pParse->pVdbe;
6086   int i;
6087   struct AggInfo_func *pFunc;
6088   int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
6089   assert( pParse->db->pParse==pParse );
6090   assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
6091   if( nReg==0 ) return;
6092   if( pParse->nErr ) return;
6093 #ifdef SQLITE_DEBUG
6094   /* Verify that all AggInfo registers are within the range specified by
6095   ** AggInfo.mnReg..AggInfo.mxReg */
6096   assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
6097   for(i=0; i<pAggInfo->nColumn; i++){
6098     assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
6099          && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
6100   }
6101   for(i=0; i<pAggInfo->nFunc; i++){
6102     assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
6103          && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
6104   }
6105 #endif
6106   sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
6107   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
6108     if( pFunc->iDistinct>=0 ){
6109       Expr *pE = pFunc->pFExpr;
6110       assert( ExprUseXList(pE) );
6111       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
6112         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
6113            "argument");
6114         pFunc->iDistinct = -1;
6115       }else{
6116         KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
6117         pFunc->iDistAddr = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
6118             pFunc->iDistinct, 0, 0, (char*)pKeyInfo, P4_KEYINFO);
6119         ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s(DISTINCT)",
6120                           pFunc->pFunc->zName));
6121       }
6122     }
6123   }
6124 }
6125 
6126 /*
6127 ** Invoke the OP_AggFinalize opcode for every aggregate function
6128 ** in the AggInfo structure.
6129 */
6130 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
6131   Vdbe *v = pParse->pVdbe;
6132   int i;
6133   struct AggInfo_func *pF;
6134   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
6135     ExprList *pList;
6136     assert( ExprUseXList(pF->pFExpr) );
6137     pList = pF->pFExpr->x.pList;
6138     sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
6139     sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
6140   }
6141 }
6142 
6143 
6144 /*
6145 ** Update the accumulator memory cells for an aggregate based on
6146 ** the current cursor position.
6147 **
6148 ** If regAcc is non-zero and there are no min() or max() aggregates
6149 ** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
6150 ** registers if register regAcc contains 0. The caller will take care
6151 ** of setting and clearing regAcc.
6152 */
6153 static void updateAccumulator(
6154   Parse *pParse,
6155   int regAcc,
6156   AggInfo *pAggInfo,
6157   int eDistinctType
6158 ){
6159   Vdbe *v = pParse->pVdbe;
6160   int i;
6161   int regHit = 0;
6162   int addrHitTest = 0;
6163   struct AggInfo_func *pF;
6164   struct AggInfo_col *pC;
6165 
6166   pAggInfo->directMode = 1;
6167   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
6168     int nArg;
6169     int addrNext = 0;
6170     int regAgg;
6171     ExprList *pList;
6172     assert( ExprUseXList(pF->pFExpr) );
6173     assert( !IsWindowFunc(pF->pFExpr) );
6174     pList = pF->pFExpr->x.pList;
6175     if( ExprHasProperty(pF->pFExpr, EP_WinFunc) ){
6176       Expr *pFilter = pF->pFExpr->y.pWin->pFilter;
6177       if( pAggInfo->nAccumulator
6178        && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
6179        && regAcc
6180       ){
6181         /* If regAcc==0, there there exists some min() or max() function
6182         ** without a FILTER clause that will ensure the magnet registers
6183         ** are populated. */
6184         if( regHit==0 ) regHit = ++pParse->nMem;
6185         /* If this is the first row of the group (regAcc contains 0), clear the
6186         ** "magnet" register regHit so that the accumulator registers
6187         ** are populated if the FILTER clause jumps over the the
6188         ** invocation of min() or max() altogether. Or, if this is not
6189         ** the first row (regAcc contains 1), set the magnet register so that
6190         ** the accumulators are not populated unless the min()/max() is invoked
6191         ** and indicates that they should be.  */
6192         sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit);
6193       }
6194       addrNext = sqlite3VdbeMakeLabel(pParse);
6195       sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL);
6196     }
6197     if( pList ){
6198       nArg = pList->nExpr;
6199       regAgg = sqlite3GetTempRange(pParse, nArg);
6200       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
6201     }else{
6202       nArg = 0;
6203       regAgg = 0;
6204     }
6205     if( pF->iDistinct>=0 && pList ){
6206       if( addrNext==0 ){
6207         addrNext = sqlite3VdbeMakeLabel(pParse);
6208       }
6209       pF->iDistinct = codeDistinct(pParse, eDistinctType,
6210           pF->iDistinct, addrNext, pList, regAgg);
6211     }
6212     if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
6213       CollSeq *pColl = 0;
6214       struct ExprList_item *pItem;
6215       int j;
6216       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
6217       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
6218         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
6219       }
6220       if( !pColl ){
6221         pColl = pParse->db->pDfltColl;
6222       }
6223       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
6224       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
6225     }
6226     sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem);
6227     sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
6228     sqlite3VdbeChangeP5(v, (u8)nArg);
6229     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
6230     if( addrNext ){
6231       sqlite3VdbeResolveLabel(v, addrNext);
6232     }
6233   }
6234   if( regHit==0 && pAggInfo->nAccumulator ){
6235     regHit = regAcc;
6236   }
6237   if( regHit ){
6238     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
6239   }
6240   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
6241     sqlite3ExprCode(pParse, pC->pCExpr, pC->iMem);
6242   }
6243 
6244   pAggInfo->directMode = 0;
6245   if( addrHitTest ){
6246     sqlite3VdbeJumpHereOrPopInst(v, addrHitTest);
6247   }
6248 }
6249 
6250 /*
6251 ** Add a single OP_Explain instruction to the VDBE to explain a simple
6252 ** count(*) query ("SELECT count(*) FROM pTab").
6253 */
6254 #ifndef SQLITE_OMIT_EXPLAIN
6255 static void explainSimpleCount(
6256   Parse *pParse,                  /* Parse context */
6257   Table *pTab,                    /* Table being queried */
6258   Index *pIdx                     /* Index used to optimize scan, or NULL */
6259 ){
6260   if( pParse->explain==2 ){
6261     int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
6262     sqlite3VdbeExplain(pParse, 0, "SCAN %s%s%s",
6263         pTab->zName,
6264         bCover ? " USING COVERING INDEX " : "",
6265         bCover ? pIdx->zName : ""
6266     );
6267   }
6268 }
6269 #else
6270 # define explainSimpleCount(a,b,c)
6271 #endif
6272 
6273 /*
6274 ** sqlite3WalkExpr() callback used by havingToWhere().
6275 **
6276 ** If the node passed to the callback is a TK_AND node, return
6277 ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
6278 **
6279 ** Otherwise, return WRC_Prune. In this case, also check if the
6280 ** sub-expression matches the criteria for being moved to the WHERE
6281 ** clause. If so, add it to the WHERE clause and replace the sub-expression
6282 ** within the HAVING expression with a constant "1".
6283 */
6284 static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
6285   if( pExpr->op!=TK_AND ){
6286     Select *pS = pWalker->u.pSelect;
6287     /* This routine is called before the HAVING clause of the current
6288     ** SELECT is analyzed for aggregates. So if pExpr->pAggInfo is set
6289     ** here, it indicates that the expression is a correlated reference to a
6290     ** column from an outer aggregate query, or an aggregate function that
6291     ** belongs to an outer query. Do not move the expression to the WHERE
6292     ** clause in this obscure case, as doing so may corrupt the outer Select
6293     ** statements AggInfo structure.  */
6294     if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy)
6295      && ExprAlwaysFalse(pExpr)==0
6296      && pExpr->pAggInfo==0
6297     ){
6298       sqlite3 *db = pWalker->pParse->db;
6299       Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1");
6300       if( pNew ){
6301         Expr *pWhere = pS->pWhere;
6302         SWAP(Expr, *pNew, *pExpr);
6303         pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew);
6304         pS->pWhere = pNew;
6305         pWalker->eCode = 1;
6306       }
6307     }
6308     return WRC_Prune;
6309   }
6310   return WRC_Continue;
6311 }
6312 
6313 /*
6314 ** Transfer eligible terms from the HAVING clause of a query, which is
6315 ** processed after grouping, to the WHERE clause, which is processed before
6316 ** grouping. For example, the query:
6317 **
6318 **   SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
6319 **
6320 ** can be rewritten as:
6321 **
6322 **   SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
6323 **
6324 ** A term of the HAVING expression is eligible for transfer if it consists
6325 ** entirely of constants and expressions that are also GROUP BY terms that
6326 ** use the "BINARY" collation sequence.
6327 */
6328 static void havingToWhere(Parse *pParse, Select *p){
6329   Walker sWalker;
6330   memset(&sWalker, 0, sizeof(sWalker));
6331   sWalker.pParse = pParse;
6332   sWalker.xExprCallback = havingToWhereExprCb;
6333   sWalker.u.pSelect = p;
6334   sqlite3WalkExpr(&sWalker, p->pHaving);
6335 #if TREETRACE_ENABLED
6336   if( sWalker.eCode && (sqlite3TreeTrace & 0x100)!=0 ){
6337     SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
6338     sqlite3TreeViewSelect(0, p, 0);
6339   }
6340 #endif
6341 }
6342 
6343 /*
6344 ** Check to see if the pThis entry of pTabList is a self-join of a prior view.
6345 ** If it is, then return the SrcList_item for the prior view.  If it is not,
6346 ** then return 0.
6347 */
6348 static SrcItem *isSelfJoinView(
6349   SrcList *pTabList,           /* Search for self-joins in this FROM clause */
6350   SrcItem *pThis               /* Search for prior reference to this subquery */
6351 ){
6352   SrcItem *pItem;
6353   assert( pThis->pSelect!=0 );
6354   if( pThis->pSelect->selFlags & SF_PushDown ) return 0;
6355   for(pItem = pTabList->a; pItem<pThis; pItem++){
6356     Select *pS1;
6357     if( pItem->pSelect==0 ) continue;
6358     if( pItem->fg.viaCoroutine ) continue;
6359     if( pItem->zName==0 ) continue;
6360     assert( pItem->pTab!=0 );
6361     assert( pThis->pTab!=0 );
6362     if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue;
6363     if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
6364     pS1 = pItem->pSelect;
6365     if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){
6366       /* The query flattener left two different CTE tables with identical
6367       ** names in the same FROM clause. */
6368       continue;
6369     }
6370     if( pItem->pSelect->selFlags & SF_PushDown ){
6371       /* The view was modified by some other optimization such as
6372       ** pushDownWhereTerms() */
6373       continue;
6374     }
6375     return pItem;
6376   }
6377   return 0;
6378 }
6379 
6380 /*
6381 ** Deallocate a single AggInfo object
6382 */
6383 static void agginfoFree(sqlite3 *db, AggInfo *p){
6384   sqlite3DbFree(db, p->aCol);
6385   sqlite3DbFree(db, p->aFunc);
6386   sqlite3DbFreeNN(db, p);
6387 }
6388 
6389 #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
6390 /*
6391 ** Attempt to transform a query of the form
6392 **
6393 **    SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
6394 **
6395 ** Into this:
6396 **
6397 **    SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
6398 **
6399 ** The transformation only works if all of the following are true:
6400 **
6401 **   *  The subquery is a UNION ALL of two or more terms
6402 **   *  The subquery does not have a LIMIT clause
6403 **   *  There is no WHERE or GROUP BY or HAVING clauses on the subqueries
6404 **   *  The outer query is a simple count(*) with no WHERE clause or other
6405 **      extraneous syntax.
6406 **
6407 ** Return TRUE if the optimization is undertaken.
6408 */
6409 static int countOfViewOptimization(Parse *pParse, Select *p){
6410   Select *pSub, *pPrior;
6411   Expr *pExpr;
6412   Expr *pCount;
6413   sqlite3 *db;
6414   if( (p->selFlags & SF_Aggregate)==0 ) return 0;   /* This is an aggregate */
6415   if( p->pEList->nExpr!=1 ) return 0;               /* Single result column */
6416   if( p->pWhere ) return 0;
6417   if( p->pGroupBy ) return 0;
6418   pExpr = p->pEList->a[0].pExpr;
6419   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;        /* Result is an aggregate */
6420   assert( ExprUseUToken(pExpr) );
6421   if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0;  /* Is count() */
6422   assert( ExprUseXList(pExpr) );
6423   if( pExpr->x.pList!=0 ) return 0;                 /* Must be count(*) */
6424   if( p->pSrc->nSrc!=1 ) return 0;                  /* One table in FROM  */
6425   pSub = p->pSrc->a[0].pSelect;
6426   if( pSub==0 ) return 0;                           /* The FROM is a subquery */
6427   if( pSub->pPrior==0 ) return 0;                   /* Must be a compound ry */
6428   do{
6429     if( pSub->op!=TK_ALL && pSub->pPrior ) return 0;  /* Must be UNION ALL */
6430     if( pSub->pWhere ) return 0;                      /* No WHERE clause */
6431     if( pSub->pLimit ) return 0;                      /* No LIMIT clause */
6432     if( pSub->selFlags & SF_Aggregate ) return 0;     /* Not an aggregate */
6433     pSub = pSub->pPrior;                              /* Repeat over compound */
6434   }while( pSub );
6435 
6436   /* If we reach this point then it is OK to perform the transformation */
6437 
6438   db = pParse->db;
6439   pCount = pExpr;
6440   pExpr = 0;
6441   pSub = p->pSrc->a[0].pSelect;
6442   p->pSrc->a[0].pSelect = 0;
6443   sqlite3SrcListDelete(db, p->pSrc);
6444   p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
6445   while( pSub ){
6446     Expr *pTerm;
6447     pPrior = pSub->pPrior;
6448     pSub->pPrior = 0;
6449     pSub->pNext = 0;
6450     pSub->selFlags |= SF_Aggregate;
6451     pSub->selFlags &= ~SF_Compound;
6452     pSub->nSelectRow = 0;
6453     sqlite3ExprListDelete(db, pSub->pEList);
6454     pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
6455     pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
6456     pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
6457     sqlite3PExprAddSelect(pParse, pTerm, pSub);
6458     if( pExpr==0 ){
6459       pExpr = pTerm;
6460     }else{
6461       pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
6462     }
6463     pSub = pPrior;
6464   }
6465   p->pEList->a[0].pExpr = pExpr;
6466   p->selFlags &= ~SF_Aggregate;
6467 
6468 #if TREETRACE_ENABLED
6469   if( sqlite3TreeTrace & 0x400 ){
6470     SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
6471     sqlite3TreeViewSelect(0, p, 0);
6472   }
6473 #endif
6474   return 1;
6475 }
6476 #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
6477 
6478 /*
6479 ** Generate code for the SELECT statement given in the p argument.
6480 **
6481 ** The results are returned according to the SelectDest structure.
6482 ** See comments in sqliteInt.h for further information.
6483 **
6484 ** This routine returns the number of errors.  If any errors are
6485 ** encountered, then an appropriate error message is left in
6486 ** pParse->zErrMsg.
6487 **
6488 ** This routine does NOT free the Select structure passed in.  The
6489 ** calling function needs to do that.
6490 */
6491 int sqlite3Select(
6492   Parse *pParse,         /* The parser context */
6493   Select *p,             /* The SELECT statement being coded. */
6494   SelectDest *pDest      /* What to do with the query results */
6495 ){
6496   int i, j;              /* Loop counters */
6497   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
6498   Vdbe *v;               /* The virtual machine under construction */
6499   int isAgg;             /* True for select lists like "count(*)" */
6500   ExprList *pEList = 0;  /* List of columns to extract. */
6501   SrcList *pTabList;     /* List of tables to select from */
6502   Expr *pWhere;          /* The WHERE clause.  May be NULL */
6503   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
6504   Expr *pHaving;         /* The HAVING clause.  May be NULL */
6505   AggInfo *pAggInfo = 0; /* Aggregate information */
6506   int rc = 1;            /* Value to return from this function */
6507   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
6508   SortCtx sSort;         /* Info on how to code the ORDER BY clause */
6509   int iEnd;              /* Address of the end of the query */
6510   sqlite3 *db;           /* The database connection */
6511   ExprList *pMinMaxOrderBy = 0;  /* Added ORDER BY for min/max queries */
6512   u8 minMaxFlag;                 /* Flag for min/max queries */
6513 
6514   db = pParse->db;
6515   assert( pParse==db->pParse );
6516   v = sqlite3GetVdbe(pParse);
6517   if( p==0 || pParse->nErr ){
6518     return 1;
6519   }
6520   assert( db->mallocFailed==0 );
6521   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
6522 #if TREETRACE_ENABLED
6523   SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain));
6524   if( sqlite3TreeTrace & 0x10100 ){
6525     if( (sqlite3TreeTrace & 0x10001)==0x10000 ){
6526       sqlite3TreeViewLine(0, "In sqlite3Select() at %s:%d",
6527                            __FILE__, __LINE__);
6528     }
6529     sqlite3ShowSelect(p);
6530   }
6531 #endif
6532 
6533   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
6534   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
6535   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
6536   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
6537   if( IgnorableDistinct(pDest) ){
6538     assert(pDest->eDest==SRT_Exists     || pDest->eDest==SRT_Union ||
6539            pDest->eDest==SRT_Except     || pDest->eDest==SRT_Discard ||
6540            pDest->eDest==SRT_DistQueue  || pDest->eDest==SRT_DistFifo );
6541     /* All of these destinations are also able to ignore the ORDER BY clause */
6542     if( p->pOrderBy ){
6543 #if TREETRACE_ENABLED
6544       SELECTTRACE(1,pParse,p, ("dropping superfluous ORDER BY:\n"));
6545       if( sqlite3TreeTrace & 0x100 ){
6546         sqlite3TreeViewExprList(0, p->pOrderBy, 0, "ORDERBY");
6547       }
6548 #endif
6549       sqlite3ParserAddCleanup(pParse,
6550         (void(*)(sqlite3*,void*))sqlite3ExprListDelete,
6551         p->pOrderBy);
6552       testcase( pParse->earlyCleanup );
6553       p->pOrderBy = 0;
6554     }
6555     p->selFlags &= ~SF_Distinct;
6556     p->selFlags |= SF_NoopOrderBy;
6557   }
6558   sqlite3SelectPrep(pParse, p, 0);
6559   if( pParse->nErr ){
6560     goto select_end;
6561   }
6562   assert( db->mallocFailed==0 );
6563   assert( p->pEList!=0 );
6564 #if TREETRACE_ENABLED
6565   if( sqlite3TreeTrace & 0x104 ){
6566     SELECTTRACE(0x104,pParse,p, ("after name resolution:\n"));
6567     sqlite3TreeViewSelect(0, p, 0);
6568   }
6569 #endif
6570 
6571   /* If the SF_UFSrcCheck flag is set, then this function is being called
6572   ** as part of populating the temp table for an UPDATE...FROM statement.
6573   ** In this case, it is an error if the target object (pSrc->a[0]) name
6574   ** or alias is duplicated within FROM clause (pSrc->a[1..n]).
6575   **
6576   ** Postgres disallows this case too. The reason is that some other
6577   ** systems handle this case differently, and not all the same way,
6578   ** which is just confusing. To avoid this, we follow PG's lead and
6579   ** disallow it altogether.  */
6580   if( p->selFlags & SF_UFSrcCheck ){
6581     SrcItem *p0 = &p->pSrc->a[0];
6582     for(i=1; i<p->pSrc->nSrc; i++){
6583       SrcItem *p1 = &p->pSrc->a[i];
6584       if( p0->pTab==p1->pTab && 0==sqlite3_stricmp(p0->zAlias, p1->zAlias) ){
6585         sqlite3ErrorMsg(pParse,
6586             "target object/alias may not appear in FROM clause: %s",
6587             p0->zAlias ? p0->zAlias : p0->pTab->zName
6588         );
6589         goto select_end;
6590       }
6591     }
6592 
6593     /* Clear the SF_UFSrcCheck flag. The check has already been performed,
6594     ** and leaving this flag set can cause errors if a compound sub-query
6595     ** in p->pSrc is flattened into this query and this function called
6596     ** again as part of compound SELECT processing.  */
6597     p->selFlags &= ~SF_UFSrcCheck;
6598   }
6599 
6600   if( pDest->eDest==SRT_Output ){
6601     sqlite3GenerateColumnNames(pParse, p);
6602   }
6603 
6604 #ifndef SQLITE_OMIT_WINDOWFUNC
6605   if( sqlite3WindowRewrite(pParse, p) ){
6606     assert( pParse->nErr );
6607     goto select_end;
6608   }
6609 #if TREETRACE_ENABLED
6610   if( p->pWin && (sqlite3TreeTrace & 0x108)!=0 ){
6611     SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n"));
6612     sqlite3TreeViewSelect(0, p, 0);
6613   }
6614 #endif
6615 #endif /* SQLITE_OMIT_WINDOWFUNC */
6616   pTabList = p->pSrc;
6617   isAgg = (p->selFlags & SF_Aggregate)!=0;
6618   memset(&sSort, 0, sizeof(sSort));
6619   sSort.pOrderBy = p->pOrderBy;
6620 
6621   /* Try to do various optimizations (flattening subqueries, and strength
6622   ** reduction of join operators) in the FROM clause up into the main query
6623   */
6624 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
6625   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
6626     SrcItem *pItem = &pTabList->a[i];
6627     Select *pSub = pItem->pSelect;
6628     Table *pTab = pItem->pTab;
6629 
6630     /* The expander should have already created transient Table objects
6631     ** even for FROM clause elements such as subqueries that do not correspond
6632     ** to a real table */
6633     assert( pTab!=0 );
6634 
6635     /* Convert LEFT JOIN into JOIN if there are terms of the right table
6636     ** of the LEFT JOIN used in the WHERE clause.
6637     */
6638     if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))==JT_LEFT
6639      && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor)
6640      && OptimizationEnabled(db, SQLITE_SimplifyJoin)
6641     ){
6642       SELECTTRACE(0x100,pParse,p,
6643                 ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
6644       pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
6645       unsetJoinExpr(p->pWhere, pItem->iCursor);
6646     }
6647 
6648     /* No futher action if this term of the FROM clause is no a subquery */
6649     if( pSub==0 ) continue;
6650 
6651     /* Catch mismatch in the declared columns of a view and the number of
6652     ** columns in the SELECT on the RHS */
6653     if( pTab->nCol!=pSub->pEList->nExpr ){
6654       sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
6655                       pTab->nCol, pTab->zName, pSub->pEList->nExpr);
6656       goto select_end;
6657     }
6658 
6659     /* Do not try to flatten an aggregate subquery.
6660     **
6661     ** Flattening an aggregate subquery is only possible if the outer query
6662     ** is not a join.  But if the outer query is not a join, then the subquery
6663     ** will be implemented as a co-routine and there is no advantage to
6664     ** flattening in that case.
6665     */
6666     if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
6667     assert( pSub->pGroupBy==0 );
6668 
6669     /* If a FROM-clause subquery has an ORDER BY clause that is not
6670     ** really doing anything, then delete it now so that it does not
6671     ** interfere with query flattening.  See the discussion at
6672     ** https://sqlite.org/forum/forumpost/2d76f2bcf65d256a
6673     **
6674     ** Beware of these cases where the ORDER BY clause may not be safely
6675     ** omitted:
6676     **
6677     **    (1)   There is also a LIMIT clause
6678     **    (2)   The subquery was added to help with window-function
6679     **          processing
6680     **    (3)   The subquery is in the FROM clause of an UPDATE
6681     **    (4)   The outer query uses an aggregate function other than
6682     **          the built-in count(), min(), or max().
6683     **    (5)   The ORDER BY isn't going to accomplish anything because
6684     **          one of:
6685     **            (a)  The outer query has a different ORDER BY clause
6686     **            (b)  The subquery is part of a join
6687     **          See forum post 062d576715d277c8
6688     */
6689     if( pSub->pOrderBy!=0
6690      && (p->pOrderBy!=0 || pTabList->nSrc>1)      /* Condition (5) */
6691      && pSub->pLimit==0                           /* Condition (1) */
6692      && (pSub->selFlags & SF_OrderByReqd)==0      /* Condition (2) */
6693      && (p->selFlags & SF_OrderByReqd)==0         /* Condition (3) and (4) */
6694      && OptimizationEnabled(db, SQLITE_OmitOrderBy)
6695     ){
6696       SELECTTRACE(0x100,pParse,p,
6697                 ("omit superfluous ORDER BY on %r FROM-clause subquery\n",i+1));
6698       sqlite3ExprListDelete(db, pSub->pOrderBy);
6699       pSub->pOrderBy = 0;
6700     }
6701 
6702     /* If the outer query contains a "complex" result set (that is,
6703     ** if the result set of the outer query uses functions or subqueries)
6704     ** and if the subquery contains an ORDER BY clause and if
6705     ** it will be implemented as a co-routine, then do not flatten.  This
6706     ** restriction allows SQL constructs like this:
6707     **
6708     **  SELECT expensive_function(x)
6709     **    FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
6710     **
6711     ** The expensive_function() is only computed on the 10 rows that
6712     ** are output, rather than every row of the table.
6713     **
6714     ** The requirement that the outer query have a complex result set
6715     ** means that flattening does occur on simpler SQL constraints without
6716     ** the expensive_function() like:
6717     **
6718     **  SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
6719     */
6720     if( pSub->pOrderBy!=0
6721      && i==0
6722      && (p->selFlags & SF_ComplexResult)!=0
6723      && (pTabList->nSrc==1
6724          || (pTabList->a[1].fg.jointype&(JT_OUTER|JT_CROSS))!=0)
6725     ){
6726       continue;
6727     }
6728 
6729     if( flattenSubquery(pParse, p, i, isAgg) ){
6730       if( pParse->nErr ) goto select_end;
6731       /* This subquery can be absorbed into its parent. */
6732       i = -1;
6733     }
6734     pTabList = p->pSrc;
6735     if( db->mallocFailed ) goto select_end;
6736     if( !IgnorableOrderby(pDest) ){
6737       sSort.pOrderBy = p->pOrderBy;
6738     }
6739   }
6740 #endif
6741 
6742 #ifndef SQLITE_OMIT_COMPOUND_SELECT
6743   /* Handle compound SELECT statements using the separate multiSelect()
6744   ** procedure.
6745   */
6746   if( p->pPrior ){
6747     rc = multiSelect(pParse, p, pDest);
6748 #if TREETRACE_ENABLED
6749     SELECTTRACE(0x1,pParse,p,("end compound-select processing\n"));
6750     if( (sqlite3TreeTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
6751       sqlite3TreeViewSelect(0, p, 0);
6752     }
6753 #endif
6754     if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
6755     return rc;
6756   }
6757 #endif
6758 
6759   /* Do the WHERE-clause constant propagation optimization if this is
6760   ** a join.  No need to speed time on this operation for non-join queries
6761   ** as the equivalent optimization will be handled by query planner in
6762   ** sqlite3WhereBegin().
6763   */
6764   if( p->pWhere!=0
6765    && p->pWhere->op==TK_AND
6766    && OptimizationEnabled(db, SQLITE_PropagateConst)
6767    && propagateConstants(pParse, p)
6768   ){
6769 #if TREETRACE_ENABLED
6770     if( sqlite3TreeTrace & 0x100 ){
6771       SELECTTRACE(0x100,pParse,p,("After constant propagation:\n"));
6772       sqlite3TreeViewSelect(0, p, 0);
6773     }
6774 #endif
6775   }else{
6776     SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n"));
6777   }
6778 
6779 #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
6780   if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
6781    && countOfViewOptimization(pParse, p)
6782   ){
6783     if( db->mallocFailed ) goto select_end;
6784     pEList = p->pEList;
6785     pTabList = p->pSrc;
6786   }
6787 #endif
6788 
6789   /* For each term in the FROM clause, do two things:
6790   ** (1) Authorized unreferenced tables
6791   ** (2) Generate code for all sub-queries
6792   */
6793   for(i=0; i<pTabList->nSrc; i++){
6794     SrcItem *pItem = &pTabList->a[i];
6795     SrcItem *pPrior;
6796     SelectDest dest;
6797     Select *pSub;
6798 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
6799     const char *zSavedAuthContext;
6800 #endif
6801 
6802     /* Issue SQLITE_READ authorizations with a fake column name for any
6803     ** tables that are referenced but from which no values are extracted.
6804     ** Examples of where these kinds of null SQLITE_READ authorizations
6805     ** would occur:
6806     **
6807     **     SELECT count(*) FROM t1;   -- SQLITE_READ t1.""
6808     **     SELECT t1.* FROM t1, t2;   -- SQLITE_READ t2.""
6809     **
6810     ** The fake column name is an empty string.  It is possible for a table to
6811     ** have a column named by the empty string, in which case there is no way to
6812     ** distinguish between an unreferenced table and an actual reference to the
6813     ** "" column. The original design was for the fake column name to be a NULL,
6814     ** which would be unambiguous.  But legacy authorization callbacks might
6815     ** assume the column name is non-NULL and segfault.  The use of an empty
6816     ** string for the fake column name seems safer.
6817     */
6818     if( pItem->colUsed==0 && pItem->zName!=0 ){
6819       sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
6820     }
6821 
6822 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
6823     /* Generate code for all sub-queries in the FROM clause
6824     */
6825     pSub = pItem->pSelect;
6826     if( pSub==0 ) continue;
6827 
6828     /* The code for a subquery should only be generated once. */
6829     assert( pItem->addrFillSub==0 );
6830 
6831     /* Increment Parse.nHeight by the height of the largest expression
6832     ** tree referred to by this, the parent select. The child select
6833     ** may contain expression trees of at most
6834     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
6835     ** more conservative than necessary, but much easier than enforcing
6836     ** an exact limit.
6837     */
6838     pParse->nHeight += sqlite3SelectExprHeight(p);
6839 
6840     /* Make copies of constant WHERE-clause terms in the outer query down
6841     ** inside the subquery.  This can help the subquery to run more efficiently.
6842     */
6843     if( OptimizationEnabled(db, SQLITE_PushDown)
6844      && (pItem->fg.isCte==0
6845          || (pItem->u2.pCteUse->eM10d!=M10d_Yes && pItem->u2.pCteUse->nUse<2))
6846      && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem)
6847     ){
6848 #if TREETRACE_ENABLED
6849       if( sqlite3TreeTrace & 0x100 ){
6850         SELECTTRACE(0x100,pParse,p,
6851             ("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
6852         sqlite3TreeViewSelect(0, p, 0);
6853       }
6854 #endif
6855       assert( pItem->pSelect && (pItem->pSelect->selFlags & SF_PushDown)!=0 );
6856     }else{
6857       SELECTTRACE(0x100,pParse,p,("Push-down not possible\n"));
6858     }
6859 
6860     zSavedAuthContext = pParse->zAuthContext;
6861     pParse->zAuthContext = pItem->zName;
6862 
6863     /* Generate code to implement the subquery
6864     **
6865     ** The subquery is implemented as a co-routine all of the following are
6866     ** true:
6867     **
6868     **    (1)  the subquery is guaranteed to be the outer loop (so that
6869     **         it does not need to be computed more than once), and
6870     **    (2)  the subquery is not a CTE that should be materialized
6871     **    (3)  the subquery is not part of a left operand for a RIGHT JOIN
6872     */
6873     if( i==0
6874      && (pTabList->nSrc==1
6875             || (pTabList->a[1].fg.jointype&(JT_OUTER|JT_CROSS))!=0)  /* (1) */
6876      && (pItem->fg.isCte==0 || pItem->u2.pCteUse->eM10d!=M10d_Yes)   /* (2) */
6877      && (pTabList->a[0].fg.jointype & JT_LTORJ)==0                   /* (3) */
6878     ){
6879       /* Implement a co-routine that will return a single row of the result
6880       ** set on each invocation.
6881       */
6882       int addrTop = sqlite3VdbeCurrentAddr(v)+1;
6883 
6884       pItem->regReturn = ++pParse->nMem;
6885       sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
6886       VdbeComment((v, "%!S", pItem));
6887       pItem->addrFillSub = addrTop;
6888       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
6889       ExplainQueryPlan((pParse, 1, "CO-ROUTINE %!S", pItem));
6890       sqlite3Select(pParse, pSub, &dest);
6891       pItem->pTab->nRowLogEst = pSub->nSelectRow;
6892       pItem->fg.viaCoroutine = 1;
6893       pItem->regResult = dest.iSdst;
6894       sqlite3VdbeEndCoroutine(v, pItem->regReturn);
6895       sqlite3VdbeJumpHere(v, addrTop-1);
6896       sqlite3ClearTempRegCache(pParse);
6897     }else if( pItem->fg.isCte && pItem->u2.pCteUse->addrM9e>0 ){
6898       /* This is a CTE for which materialization code has already been
6899       ** generated.  Invoke the subroutine to compute the materialization,
6900       ** the make the pItem->iCursor be a copy of the ephemerial table that
6901       ** holds the result of the materialization. */
6902       CteUse *pCteUse = pItem->u2.pCteUse;
6903       sqlite3VdbeAddOp2(v, OP_Gosub, pCteUse->regRtn, pCteUse->addrM9e);
6904       if( pItem->iCursor!=pCteUse->iCur ){
6905         sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pCteUse->iCur);
6906         VdbeComment((v, "%!S", pItem));
6907       }
6908       pSub->nSelectRow = pCteUse->nRowEst;
6909     }else if( (pPrior = isSelfJoinView(pTabList, pItem))!=0 ){
6910       /* This view has already been materialized by a prior entry in
6911       ** this same FROM clause.  Reuse it. */
6912       if( pPrior->addrFillSub ){
6913         sqlite3VdbeAddOp2(v, OP_Gosub, pPrior->regReturn, pPrior->addrFillSub);
6914       }
6915       sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
6916       pSub->nSelectRow = pPrior->pSelect->nSelectRow;
6917     }else{
6918       /* Materialize the view.  If the view is not correlated, generate a
6919       ** subroutine to do the materialization so that subsequent uses of
6920       ** the same view can reuse the materialization. */
6921       int topAddr;
6922       int onceAddr = 0;
6923       int retAddr;
6924 
6925       pItem->regReturn = ++pParse->nMem;
6926       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
6927       pItem->addrFillSub = topAddr+1;
6928       if( pItem->fg.isCorrelated==0 ){
6929         /* If the subquery is not correlated and if we are not inside of
6930         ** a trigger, then we only need to compute the value of the subquery
6931         ** once. */
6932         onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
6933         VdbeComment((v, "materialize %!S", pItem));
6934       }else{
6935         VdbeNoopComment((v, "materialize %!S", pItem));
6936       }
6937       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
6938       ExplainQueryPlan((pParse, 1, "MATERIALIZE %!S", pItem));
6939       sqlite3Select(pParse, pSub, &dest);
6940       pItem->pTab->nRowLogEst = pSub->nSelectRow;
6941       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
6942       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
6943       VdbeComment((v, "end %!S", pItem));
6944       sqlite3VdbeChangeP1(v, topAddr, retAddr);
6945       sqlite3ClearTempRegCache(pParse);
6946       if( pItem->fg.isCte && pItem->fg.isCorrelated==0 ){
6947         CteUse *pCteUse = pItem->u2.pCteUse;
6948         pCteUse->addrM9e = pItem->addrFillSub;
6949         pCteUse->regRtn = pItem->regReturn;
6950         pCteUse->iCur = pItem->iCursor;
6951         pCteUse->nRowEst = pSub->nSelectRow;
6952       }
6953     }
6954     if( db->mallocFailed ) goto select_end;
6955     pParse->nHeight -= sqlite3SelectExprHeight(p);
6956     pParse->zAuthContext = zSavedAuthContext;
6957 #endif
6958   }
6959 
6960   /* Various elements of the SELECT copied into local variables for
6961   ** convenience */
6962   pEList = p->pEList;
6963   pWhere = p->pWhere;
6964   pGroupBy = p->pGroupBy;
6965   pHaving = p->pHaving;
6966   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
6967 
6968 #if TREETRACE_ENABLED
6969   if( sqlite3TreeTrace & 0x400 ){
6970     SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
6971     sqlite3TreeViewSelect(0, p, 0);
6972   }
6973 #endif
6974 
6975   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
6976   ** if the select-list is the same as the ORDER BY list, then this query
6977   ** can be rewritten as a GROUP BY. In other words, this:
6978   **
6979   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
6980   **
6981   ** is transformed to:
6982   **
6983   **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
6984   **
6985   ** The second form is preferred as a single index (or temp-table) may be
6986   ** used for both the ORDER BY and DISTINCT processing. As originally
6987   ** written the query must use a temp-table for at least one of the ORDER
6988   ** BY and DISTINCT, and an index or separate temp-table for the other.
6989   */
6990   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
6991    && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
6992 #ifndef SQLITE_OMIT_WINDOWFUNC
6993    && p->pWin==0
6994 #endif
6995   ){
6996     p->selFlags &= ~SF_Distinct;
6997     pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
6998     p->selFlags |= SF_Aggregate;
6999     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
7000     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
7001     ** original setting of the SF_Distinct flag, not the current setting */
7002     assert( sDistinct.isTnct );
7003     sDistinct.isTnct = 2;
7004 
7005 #if TREETRACE_ENABLED
7006     if( sqlite3TreeTrace & 0x400 ){
7007       SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
7008       sqlite3TreeViewSelect(0, p, 0);
7009     }
7010 #endif
7011   }
7012 
7013   /* If there is an ORDER BY clause, then create an ephemeral index to
7014   ** do the sorting.  But this sorting ephemeral index might end up
7015   ** being unused if the data can be extracted in pre-sorted order.
7016   ** If that is the case, then the OP_OpenEphemeral instruction will be
7017   ** changed to an OP_Noop once we figure out that the sorting index is
7018   ** not needed.  The sSort.addrSortIndex variable is used to facilitate
7019   ** that change.
7020   */
7021   if( sSort.pOrderBy ){
7022     KeyInfo *pKeyInfo;
7023     pKeyInfo = sqlite3KeyInfoFromExprList(
7024         pParse, sSort.pOrderBy, 0, pEList->nExpr);
7025     sSort.iECursor = pParse->nTab++;
7026     sSort.addrSortIndex =
7027       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
7028           sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
7029           (char*)pKeyInfo, P4_KEYINFO
7030       );
7031   }else{
7032     sSort.addrSortIndex = -1;
7033   }
7034 
7035   /* If the output is destined for a temporary table, open that table.
7036   */
7037   if( pDest->eDest==SRT_EphemTab ){
7038     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
7039     if( p->selFlags & SF_NestedFrom ){
7040       /* Delete or NULL-out result columns that will never be used */
7041       int ii;
7042       for(ii=pEList->nExpr-1; ii>0 && pEList->a[ii].bUsed==0; ii--){
7043         sqlite3ExprDelete(db, pEList->a[ii].pExpr);
7044         sqlite3DbFree(db, pEList->a[ii].zEName);
7045         pEList->nExpr--;
7046       }
7047       for(ii=0; ii<pEList->nExpr; ii++){
7048         if( pEList->a[ii].bUsed==0 ) pEList->a[ii].pExpr->op = TK_NULL;
7049       }
7050     }
7051   }
7052 
7053   /* Set the limiter.
7054   */
7055   iEnd = sqlite3VdbeMakeLabel(pParse);
7056   if( (p->selFlags & SF_FixedLimit)==0 ){
7057     p->nSelectRow = 320;  /* 4 billion rows */
7058   }
7059   computeLimitRegisters(pParse, p, iEnd);
7060   if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
7061     sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
7062     sSort.sortFlags |= SORTFLAG_UseSorter;
7063   }
7064 
7065   /* Open an ephemeral index to use for the distinct set.
7066   */
7067   if( p->selFlags & SF_Distinct ){
7068     sDistinct.tabTnct = pParse->nTab++;
7069     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
7070                        sDistinct.tabTnct, 0, 0,
7071                        (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
7072                        P4_KEYINFO);
7073     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
7074     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
7075   }else{
7076     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
7077   }
7078 
7079   if( !isAgg && pGroupBy==0 ){
7080     /* No aggregate functions and no GROUP BY clause */
7081     u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)
7082                    | (p->selFlags & SF_FixedLimit);
7083 #ifndef SQLITE_OMIT_WINDOWFUNC
7084     Window *pWin = p->pWin;      /* Main window object (or NULL) */
7085     if( pWin ){
7086       sqlite3WindowCodeInit(pParse, p);
7087     }
7088 #endif
7089     assert( WHERE_USE_LIMIT==SF_FixedLimit );
7090 
7091 
7092     /* Begin the database scan. */
7093     SELECTTRACE(1,pParse,p,("WhereBegin\n"));
7094     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
7095                                p->pEList, p, wctrlFlags, p->nSelectRow);
7096     if( pWInfo==0 ) goto select_end;
7097     if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
7098       p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
7099     }
7100     if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
7101       sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
7102     }
7103     if( sSort.pOrderBy ){
7104       sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
7105       sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);
7106       if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
7107         sSort.pOrderBy = 0;
7108       }
7109     }
7110     SELECTTRACE(1,pParse,p,("WhereBegin returns\n"));
7111 
7112     /* If sorting index that was created by a prior OP_OpenEphemeral
7113     ** instruction ended up not being needed, then change the OP_OpenEphemeral
7114     ** into an OP_Noop.
7115     */
7116     if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
7117       sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
7118     }
7119 
7120     assert( p->pEList==pEList );
7121 #ifndef SQLITE_OMIT_WINDOWFUNC
7122     if( pWin ){
7123       int addrGosub = sqlite3VdbeMakeLabel(pParse);
7124       int iCont = sqlite3VdbeMakeLabel(pParse);
7125       int iBreak = sqlite3VdbeMakeLabel(pParse);
7126       int regGosub = ++pParse->nMem;
7127 
7128       sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);
7129 
7130       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
7131       sqlite3VdbeResolveLabel(v, addrGosub);
7132       VdbeNoopComment((v, "inner-loop subroutine"));
7133       sSort.labelOBLopt = 0;
7134       selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
7135       sqlite3VdbeResolveLabel(v, iCont);
7136       sqlite3VdbeAddOp1(v, OP_Return, regGosub);
7137       VdbeComment((v, "end inner-loop subroutine"));
7138       sqlite3VdbeResolveLabel(v, iBreak);
7139     }else
7140 #endif /* SQLITE_OMIT_WINDOWFUNC */
7141     {
7142       /* Use the standard inner loop. */
7143       selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
7144           sqlite3WhereContinueLabel(pWInfo),
7145           sqlite3WhereBreakLabel(pWInfo));
7146 
7147       /* End the database scan loop.
7148       */
7149       SELECTTRACE(1,pParse,p,("WhereEnd\n"));
7150       sqlite3WhereEnd(pWInfo);
7151     }
7152   }else{
7153     /* This case when there exist aggregate functions or a GROUP BY clause
7154     ** or both */
7155     NameContext sNC;    /* Name context for processing aggregate information */
7156     int iAMem;          /* First Mem address for storing current GROUP BY */
7157     int iBMem;          /* First Mem address for previous GROUP BY */
7158     int iUseFlag;       /* Mem address holding flag indicating that at least
7159                         ** one row of the input to the aggregator has been
7160                         ** processed */
7161     int iAbortFlag;     /* Mem address which causes query abort if positive */
7162     int groupBySort;    /* Rows come from source in GROUP BY order */
7163     int addrEnd;        /* End of processing for this SELECT */
7164     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
7165     int sortOut = 0;    /* Output register from the sorter */
7166     int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
7167 
7168     /* Remove any and all aliases between the result set and the
7169     ** GROUP BY clause.
7170     */
7171     if( pGroupBy ){
7172       int k;                        /* Loop counter */
7173       struct ExprList_item *pItem;  /* For looping over expression in a list */
7174 
7175       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
7176         pItem->u.x.iAlias = 0;
7177       }
7178       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
7179         pItem->u.x.iAlias = 0;
7180       }
7181       assert( 66==sqlite3LogEst(100) );
7182       if( p->nSelectRow>66 ) p->nSelectRow = 66;
7183 
7184       /* If there is both a GROUP BY and an ORDER BY clause and they are
7185       ** identical, then it may be possible to disable the ORDER BY clause
7186       ** on the grounds that the GROUP BY will cause elements to come out
7187       ** in the correct order. It also may not - the GROUP BY might use a
7188       ** database index that causes rows to be grouped together as required
7189       ** but not actually sorted. Either way, record the fact that the
7190       ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
7191       ** variable.  */
7192       if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){
7193         int ii;
7194         /* The GROUP BY processing doesn't care whether rows are delivered in
7195         ** ASC or DESC order - only that each group is returned contiguously.
7196         ** So set the ASC/DESC flags in the GROUP BY to match those in the
7197         ** ORDER BY to maximize the chances of rows being delivered in an
7198         ** order that makes the ORDER BY redundant.  */
7199         for(ii=0; ii<pGroupBy->nExpr; ii++){
7200           u8 sortFlags = sSort.pOrderBy->a[ii].sortFlags & KEYINFO_ORDER_DESC;
7201           pGroupBy->a[ii].sortFlags = sortFlags;
7202         }
7203         if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
7204           orderByGrp = 1;
7205         }
7206       }
7207     }else{
7208       assert( 0==sqlite3LogEst(1) );
7209       p->nSelectRow = 0;
7210     }
7211 
7212     /* Create a label to jump to when we want to abort the query */
7213     addrEnd = sqlite3VdbeMakeLabel(pParse);
7214 
7215     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
7216     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
7217     ** SELECT statement.
7218     */
7219     pAggInfo = sqlite3DbMallocZero(db, sizeof(*pAggInfo) );
7220     if( pAggInfo ){
7221       sqlite3ParserAddCleanup(pParse,
7222           (void(*)(sqlite3*,void*))agginfoFree, pAggInfo);
7223       testcase( pParse->earlyCleanup );
7224     }
7225     if( db->mallocFailed ){
7226       goto select_end;
7227     }
7228     pAggInfo->selId = p->selId;
7229     memset(&sNC, 0, sizeof(sNC));
7230     sNC.pParse = pParse;
7231     sNC.pSrcList = pTabList;
7232     sNC.uNC.pAggInfo = pAggInfo;
7233     VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
7234     pAggInfo->mnReg = pParse->nMem+1;
7235     pAggInfo->nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
7236     pAggInfo->pGroupBy = pGroupBy;
7237     sqlite3ExprAnalyzeAggList(&sNC, pEList);
7238     sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
7239     if( pHaving ){
7240       if( pGroupBy ){
7241         assert( pWhere==p->pWhere );
7242         assert( pHaving==p->pHaving );
7243         assert( pGroupBy==p->pGroupBy );
7244         havingToWhere(pParse, p);
7245         pWhere = p->pWhere;
7246       }
7247       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
7248     }
7249     pAggInfo->nAccumulator = pAggInfo->nColumn;
7250     if( p->pGroupBy==0 && p->pHaving==0 && pAggInfo->nFunc==1 ){
7251       minMaxFlag = minMaxQuery(db, pAggInfo->aFunc[0].pFExpr, &pMinMaxOrderBy);
7252     }else{
7253       minMaxFlag = WHERE_ORDERBY_NORMAL;
7254     }
7255     for(i=0; i<pAggInfo->nFunc; i++){
7256       Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
7257       assert( ExprUseXList(pExpr) );
7258       sNC.ncFlags |= NC_InAggFunc;
7259       sqlite3ExprAnalyzeAggList(&sNC, pExpr->x.pList);
7260 #ifndef SQLITE_OMIT_WINDOWFUNC
7261       assert( !IsWindowFunc(pExpr) );
7262       if( ExprHasProperty(pExpr, EP_WinFunc) ){
7263         sqlite3ExprAnalyzeAggregates(&sNC, pExpr->y.pWin->pFilter);
7264       }
7265 #endif
7266       sNC.ncFlags &= ~NC_InAggFunc;
7267     }
7268     pAggInfo->mxReg = pParse->nMem;
7269     if( db->mallocFailed ) goto select_end;
7270 #if TREETRACE_ENABLED
7271     if( sqlite3TreeTrace & 0x400 ){
7272       int ii;
7273       SELECTTRACE(0x400,pParse,p,("After aggregate analysis %p:\n", pAggInfo));
7274       sqlite3TreeViewSelect(0, p, 0);
7275       if( minMaxFlag ){
7276         sqlite3DebugPrintf("MIN/MAX Optimization (0x%02x) adds:\n", minMaxFlag);
7277         sqlite3TreeViewExprList(0, pMinMaxOrderBy, 0, "ORDERBY");
7278       }
7279       for(ii=0; ii<pAggInfo->nColumn; ii++){
7280         sqlite3DebugPrintf("agg-column[%d] iMem=%d\n",
7281             ii, pAggInfo->aCol[ii].iMem);
7282         sqlite3TreeViewExpr(0, pAggInfo->aCol[ii].pCExpr, 0);
7283       }
7284       for(ii=0; ii<pAggInfo->nFunc; ii++){
7285         sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
7286             ii, pAggInfo->aFunc[ii].iMem);
7287         sqlite3TreeViewExpr(0, pAggInfo->aFunc[ii].pFExpr, 0);
7288       }
7289     }
7290 #endif
7291 
7292 
7293     /* Processing for aggregates with GROUP BY is very different and
7294     ** much more complex than aggregates without a GROUP BY.
7295     */
7296     if( pGroupBy ){
7297       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
7298       int addr1;          /* A-vs-B comparision jump */
7299       int addrOutputRow;  /* Start of subroutine that outputs a result row */
7300       int regOutputRow;   /* Return address register for output subroutine */
7301       int addrSetAbort;   /* Set the abort flag and return */
7302       int addrTopOfLoop;  /* Top of the input loop */
7303       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
7304       int addrReset;      /* Subroutine for resetting the accumulator */
7305       int regReset;       /* Return address register for reset subroutine */
7306       ExprList *pDistinct = 0;
7307       u16 distFlag = 0;
7308       int eDist = WHERE_DISTINCT_NOOP;
7309 
7310       if( pAggInfo->nFunc==1
7311        && pAggInfo->aFunc[0].iDistinct>=0
7312        && ALWAYS(pAggInfo->aFunc[0].pFExpr!=0)
7313        && ALWAYS(ExprUseXList(pAggInfo->aFunc[0].pFExpr))
7314        && pAggInfo->aFunc[0].pFExpr->x.pList!=0
7315       ){
7316         Expr *pExpr = pAggInfo->aFunc[0].pFExpr->x.pList->a[0].pExpr;
7317         pExpr = sqlite3ExprDup(db, pExpr, 0);
7318         pDistinct = sqlite3ExprListDup(db, pGroupBy, 0);
7319         pDistinct = sqlite3ExprListAppend(pParse, pDistinct, pExpr);
7320         distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0;
7321       }
7322 
7323       /* If there is a GROUP BY clause we might need a sorting index to
7324       ** implement it.  Allocate that sorting index now.  If it turns out
7325       ** that we do not need it after all, the OP_SorterOpen instruction
7326       ** will be converted into a Noop.
7327       */
7328       pAggInfo->sortingIdx = pParse->nTab++;
7329       pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pGroupBy,
7330                                             0, pAggInfo->nColumn);
7331       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
7332           pAggInfo->sortingIdx, pAggInfo->nSortingColumn,
7333           0, (char*)pKeyInfo, P4_KEYINFO);
7334 
7335       /* Initialize memory locations used by GROUP BY aggregate processing
7336       */
7337       iUseFlag = ++pParse->nMem;
7338       iAbortFlag = ++pParse->nMem;
7339       regOutputRow = ++pParse->nMem;
7340       addrOutputRow = sqlite3VdbeMakeLabel(pParse);
7341       regReset = ++pParse->nMem;
7342       addrReset = sqlite3VdbeMakeLabel(pParse);
7343       iAMem = pParse->nMem + 1;
7344       pParse->nMem += pGroupBy->nExpr;
7345       iBMem = pParse->nMem + 1;
7346       pParse->nMem += pGroupBy->nExpr;
7347       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
7348       VdbeComment((v, "clear abort flag"));
7349       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
7350 
7351       /* Begin a loop that will extract all source rows in GROUP BY order.
7352       ** This might involve two separate loops with an OP_Sort in between, or
7353       ** it might be a single loop that uses an index to extract information
7354       ** in the right order to begin with.
7355       */
7356       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
7357       SELECTTRACE(1,pParse,p,("WhereBegin\n"));
7358       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, pDistinct,
7359           0, (sDistinct.isTnct==2 ? WHERE_DISTINCTBY : WHERE_GROUPBY)
7360           |  (orderByGrp ? WHERE_SORTBYGROUP : 0) | distFlag, 0
7361       );
7362       if( pWInfo==0 ){
7363         sqlite3ExprListDelete(db, pDistinct);
7364         goto select_end;
7365       }
7366       eDist = sqlite3WhereIsDistinct(pWInfo);
7367       SELECTTRACE(1,pParse,p,("WhereBegin returns\n"));
7368       if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
7369         /* The optimizer is able to deliver rows in group by order so
7370         ** we do not have to sort.  The OP_OpenEphemeral table will be
7371         ** cancelled later because we still need to use the pKeyInfo
7372         */
7373         groupBySort = 0;
7374       }else{
7375         /* Rows are coming out in undetermined order.  We have to push
7376         ** each row into a sorting index, terminate the first loop,
7377         ** then loop over the sorting index in order to get the output
7378         ** in sorted order
7379         */
7380         int regBase;
7381         int regRecord;
7382         int nCol;
7383         int nGroupBy;
7384 
7385         explainTempTable(pParse,
7386             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
7387                     "DISTINCT" : "GROUP BY");
7388 
7389         groupBySort = 1;
7390         nGroupBy = pGroupBy->nExpr;
7391         nCol = nGroupBy;
7392         j = nGroupBy;
7393         for(i=0; i<pAggInfo->nColumn; i++){
7394           if( pAggInfo->aCol[i].iSorterColumn>=j ){
7395             nCol++;
7396             j++;
7397           }
7398         }
7399         regBase = sqlite3GetTempRange(pParse, nCol);
7400         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
7401         j = nGroupBy;
7402         for(i=0; i<pAggInfo->nColumn; i++){
7403           struct AggInfo_col *pCol = &pAggInfo->aCol[i];
7404           if( pCol->iSorterColumn>=j ){
7405             int r1 = j + regBase;
7406             sqlite3ExprCodeGetColumnOfTable(v,
7407                                pCol->pTab, pCol->iTable, pCol->iColumn, r1);
7408             j++;
7409           }
7410         }
7411         regRecord = sqlite3GetTempReg(pParse);
7412         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
7413         sqlite3VdbeAddOp2(v, OP_SorterInsert, pAggInfo->sortingIdx, regRecord);
7414         sqlite3ReleaseTempReg(pParse, regRecord);
7415         sqlite3ReleaseTempRange(pParse, regBase, nCol);
7416         SELECTTRACE(1,pParse,p,("WhereEnd\n"));
7417         sqlite3WhereEnd(pWInfo);
7418         pAggInfo->sortingIdxPTab = sortPTab = pParse->nTab++;
7419         sortOut = sqlite3GetTempReg(pParse);
7420         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
7421         sqlite3VdbeAddOp2(v, OP_SorterSort, pAggInfo->sortingIdx, addrEnd);
7422         VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
7423         pAggInfo->useSortingIdx = 1;
7424       }
7425 
7426       /* If the index or temporary table used by the GROUP BY sort
7427       ** will naturally deliver rows in the order required by the ORDER BY
7428       ** clause, cancel the ephemeral table open coded earlier.
7429       **
7430       ** This is an optimization - the correct answer should result regardless.
7431       ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
7432       ** disable this optimization for testing purposes.  */
7433       if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
7434        && (groupBySort || sqlite3WhereIsSorted(pWInfo))
7435       ){
7436         sSort.pOrderBy = 0;
7437         sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
7438       }
7439 
7440       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
7441       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
7442       ** Then compare the current GROUP BY terms against the GROUP BY terms
7443       ** from the previous row currently stored in a0, a1, a2...
7444       */
7445       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
7446       if( groupBySort ){
7447         sqlite3VdbeAddOp3(v, OP_SorterData, pAggInfo->sortingIdx,
7448                           sortOut, sortPTab);
7449       }
7450       for(j=0; j<pGroupBy->nExpr; j++){
7451         if( groupBySort ){
7452           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
7453         }else{
7454           pAggInfo->directMode = 1;
7455           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
7456         }
7457       }
7458       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
7459                           (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
7460       addr1 = sqlite3VdbeCurrentAddr(v);
7461       sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
7462 
7463       /* Generate code that runs whenever the GROUP BY changes.
7464       ** Changes in the GROUP BY are detected by the previous code
7465       ** block.  If there were no changes, this block is skipped.
7466       **
7467       ** This code copies current group by terms in b0,b1,b2,...
7468       ** over to a0,a1,a2.  It then calls the output subroutine
7469       ** and resets the aggregate accumulator registers in preparation
7470       ** for the next GROUP BY batch.
7471       */
7472       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
7473       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
7474       VdbeComment((v, "output one row"));
7475       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
7476       VdbeComment((v, "check abort flag"));
7477       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
7478       VdbeComment((v, "reset accumulator"));
7479 
7480       /* Update the aggregate accumulators based on the content of
7481       ** the current row
7482       */
7483       sqlite3VdbeJumpHere(v, addr1);
7484       updateAccumulator(pParse, iUseFlag, pAggInfo, eDist);
7485       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
7486       VdbeComment((v, "indicate data in accumulator"));
7487 
7488       /* End of the loop
7489       */
7490       if( groupBySort ){
7491         sqlite3VdbeAddOp2(v, OP_SorterNext, pAggInfo->sortingIdx,addrTopOfLoop);
7492         VdbeCoverage(v);
7493       }else{
7494         SELECTTRACE(1,pParse,p,("WhereEnd\n"));
7495         sqlite3WhereEnd(pWInfo);
7496         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
7497       }
7498       sqlite3ExprListDelete(db, pDistinct);
7499 
7500       /* Output the final row of result
7501       */
7502       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
7503       VdbeComment((v, "output final row"));
7504 
7505       /* Jump over the subroutines
7506       */
7507       sqlite3VdbeGoto(v, addrEnd);
7508 
7509       /* Generate a subroutine that outputs a single row of the result
7510       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
7511       ** is less than or equal to zero, the subroutine is a no-op.  If
7512       ** the processing calls for the query to abort, this subroutine
7513       ** increments the iAbortFlag memory location before returning in
7514       ** order to signal the caller to abort.
7515       */
7516       addrSetAbort = sqlite3VdbeCurrentAddr(v);
7517       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
7518       VdbeComment((v, "set abort flag"));
7519       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
7520       sqlite3VdbeResolveLabel(v, addrOutputRow);
7521       addrOutputRow = sqlite3VdbeCurrentAddr(v);
7522       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
7523       VdbeCoverage(v);
7524       VdbeComment((v, "Groupby result generator entry point"));
7525       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
7526       finalizeAggFunctions(pParse, pAggInfo);
7527       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
7528       selectInnerLoop(pParse, p, -1, &sSort,
7529                       &sDistinct, pDest,
7530                       addrOutputRow+1, addrSetAbort);
7531       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
7532       VdbeComment((v, "end groupby result generator"));
7533 
7534       /* Generate a subroutine that will reset the group-by accumulator
7535       */
7536       sqlite3VdbeResolveLabel(v, addrReset);
7537       resetAccumulator(pParse, pAggInfo);
7538       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
7539       VdbeComment((v, "indicate accumulator empty"));
7540       sqlite3VdbeAddOp1(v, OP_Return, regReset);
7541 
7542       if( distFlag!=0 && eDist!=WHERE_DISTINCT_NOOP ){
7543         struct AggInfo_func *pF = &pAggInfo->aFunc[0];
7544         fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
7545       }
7546     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
7547     else {
7548       Table *pTab;
7549       if( (pTab = isSimpleCount(p, pAggInfo))!=0 ){
7550         /* If isSimpleCount() returns a pointer to a Table structure, then
7551         ** the SQL statement is of the form:
7552         **
7553         **   SELECT count(*) FROM <tbl>
7554         **
7555         ** where the Table structure returned represents table <tbl>.
7556         **
7557         ** This statement is so common that it is optimized specially. The
7558         ** OP_Count instruction is executed either on the intkey table that
7559         ** contains the data for table <tbl> or on one of its indexes. It
7560         ** is better to execute the op on an index, as indexes are almost
7561         ** always spread across less pages than their corresponding tables.
7562         */
7563         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
7564         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
7565         Index *pIdx;                         /* Iterator variable */
7566         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
7567         Index *pBest = 0;                    /* Best index found so far */
7568         Pgno iRoot = pTab->tnum;             /* Root page of scanned b-tree */
7569 
7570         sqlite3CodeVerifySchema(pParse, iDb);
7571         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
7572 
7573         /* Search for the index that has the lowest scan cost.
7574         **
7575         ** (2011-04-15) Do not do a full scan of an unordered index.
7576         **
7577         ** (2013-10-03) Do not count the entries in a partial index.
7578         **
7579         ** In practice the KeyInfo structure will not be used. It is only
7580         ** passed to keep OP_OpenRead happy.
7581         */
7582         if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
7583         if( !p->pSrc->a[0].fg.notIndexed ){
7584           for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
7585             if( pIdx->bUnordered==0
7586              && pIdx->szIdxRow<pTab->szTabRow
7587              && pIdx->pPartIdxWhere==0
7588              && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
7589             ){
7590               pBest = pIdx;
7591             }
7592           }
7593         }
7594         if( pBest ){
7595           iRoot = pBest->tnum;
7596           pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
7597         }
7598 
7599         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
7600         sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, (int)iRoot, iDb, 1);
7601         if( pKeyInfo ){
7602           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
7603         }
7604         sqlite3VdbeAddOp2(v, OP_Count, iCsr, pAggInfo->aFunc[0].iMem);
7605         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
7606         explainSimpleCount(pParse, pTab, pBest);
7607       }else{
7608         int regAcc = 0;           /* "populate accumulators" flag */
7609         ExprList *pDistinct = 0;
7610         u16 distFlag = 0;
7611         int eDist;
7612 
7613         /* If there are accumulator registers but no min() or max() functions
7614         ** without FILTER clauses, allocate register regAcc. Register regAcc
7615         ** will contain 0 the first time the inner loop runs, and 1 thereafter.
7616         ** The code generated by updateAccumulator() uses this to ensure
7617         ** that the accumulator registers are (a) updated only once if
7618         ** there are no min() or max functions or (b) always updated for the
7619         ** first row visited by the aggregate, so that they are updated at
7620         ** least once even if the FILTER clause means the min() or max()
7621         ** function visits zero rows.  */
7622         if( pAggInfo->nAccumulator ){
7623           for(i=0; i<pAggInfo->nFunc; i++){
7624             if( ExprHasProperty(pAggInfo->aFunc[i].pFExpr, EP_WinFunc) ){
7625               continue;
7626             }
7627             if( pAggInfo->aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ){
7628               break;
7629             }
7630           }
7631           if( i==pAggInfo->nFunc ){
7632             regAcc = ++pParse->nMem;
7633             sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
7634           }
7635         }else if( pAggInfo->nFunc==1 && pAggInfo->aFunc[0].iDistinct>=0 ){
7636           assert( ExprUseXList(pAggInfo->aFunc[0].pFExpr) );
7637           pDistinct = pAggInfo->aFunc[0].pFExpr->x.pList;
7638           distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0;
7639         }
7640 
7641         /* This case runs if the aggregate has no GROUP BY clause.  The
7642         ** processing is much simpler since there is only a single row
7643         ** of output.
7644         */
7645         assert( p->pGroupBy==0 );
7646         resetAccumulator(pParse, pAggInfo);
7647 
7648         /* If this query is a candidate for the min/max optimization, then
7649         ** minMaxFlag will have been previously set to either
7650         ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
7651         ** be an appropriate ORDER BY expression for the optimization.
7652         */
7653         assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
7654         assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
7655 
7656         SELECTTRACE(1,pParse,p,("WhereBegin\n"));
7657         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
7658                                    pDistinct, 0, minMaxFlag|distFlag, 0);
7659         if( pWInfo==0 ){
7660           goto select_end;
7661         }
7662         SELECTTRACE(1,pParse,p,("WhereBegin returns\n"));
7663         eDist = sqlite3WhereIsDistinct(pWInfo);
7664         updateAccumulator(pParse, regAcc, pAggInfo, eDist);
7665         if( eDist!=WHERE_DISTINCT_NOOP ){
7666           struct AggInfo_func *pF = &pAggInfo->aFunc[0];
7667           if( pF ){
7668             fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
7669           }
7670         }
7671 
7672         if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
7673         if( minMaxFlag ){
7674           sqlite3WhereMinMaxOptEarlyOut(v, pWInfo);
7675         }
7676         SELECTTRACE(1,pParse,p,("WhereEnd\n"));
7677         sqlite3WhereEnd(pWInfo);
7678         finalizeAggFunctions(pParse, pAggInfo);
7679       }
7680 
7681       sSort.pOrderBy = 0;
7682       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
7683       selectInnerLoop(pParse, p, -1, 0, 0,
7684                       pDest, addrEnd, addrEnd);
7685     }
7686     sqlite3VdbeResolveLabel(v, addrEnd);
7687 
7688   } /* endif aggregate query */
7689 
7690   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
7691     explainTempTable(pParse, "DISTINCT");
7692   }
7693 
7694   /* If there is an ORDER BY clause, then we need to sort the results
7695   ** and send them to the callback one by one.
7696   */
7697   if( sSort.pOrderBy ){
7698     explainTempTable(pParse,
7699                      sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
7700     assert( p->pEList==pEList );
7701     generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
7702   }
7703 
7704   /* Jump here to skip this query
7705   */
7706   sqlite3VdbeResolveLabel(v, iEnd);
7707 
7708   /* The SELECT has been coded. If there is an error in the Parse structure,
7709   ** set the return code to 1. Otherwise 0. */
7710   rc = (pParse->nErr>0);
7711 
7712   /* Control jumps to here if an error is encountered above, or upon
7713   ** successful coding of the SELECT.
7714   */
7715 select_end:
7716   assert( db->mallocFailed==0 || db->mallocFailed==1 );
7717   assert( db->mallocFailed==0 || pParse->nErr!=0 );
7718   sqlite3ExprListDelete(db, pMinMaxOrderBy);
7719 #ifdef SQLITE_DEBUG
7720   if( pAggInfo && !db->mallocFailed ){
7721     for(i=0; i<pAggInfo->nColumn; i++){
7722       Expr *pExpr = pAggInfo->aCol[i].pCExpr;
7723       assert( pExpr!=0 );
7724       assert( pExpr->pAggInfo==pAggInfo );
7725       assert( pExpr->iAgg==i );
7726     }
7727     for(i=0; i<pAggInfo->nFunc; i++){
7728       Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
7729       assert( pExpr!=0 );
7730       assert( pExpr->pAggInfo==pAggInfo );
7731       assert( pExpr->iAgg==i );
7732     }
7733   }
7734 #endif
7735 
7736 #if TREETRACE_ENABLED
7737   SELECTTRACE(0x1,pParse,p,("end processing\n"));
7738   if( (sqlite3TreeTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
7739     sqlite3TreeViewSelect(0, p, 0);
7740   }
7741 #endif
7742   ExplainQueryPlanPop(pParse);
7743   return rc;
7744 }
7745