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