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