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