xref: /sqlite-3.40.0/src/select.c (revision 1c826650)
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 ** $Id: select.c,v 1.472 2008/09/01 15:52:11 drh Exp $
16 */
17 #include "sqliteInt.h"
18 
19 
20 /*
21 ** Delete all the content of a Select structure but do not deallocate
22 ** the select structure itself.
23 */
24 static void clearSelect(sqlite3 *db, Select *p){
25   sqlite3ExprListDelete(db, p->pEList);
26   sqlite3SrcListDelete(db, p->pSrc);
27   sqlite3ExprDelete(db, p->pWhere);
28   sqlite3ExprListDelete(db, p->pGroupBy);
29   sqlite3ExprDelete(db, p->pHaving);
30   sqlite3ExprListDelete(db, p->pOrderBy);
31   sqlite3SelectDelete(db, p->pPrior);
32   sqlite3ExprDelete(db, p->pLimit);
33   sqlite3ExprDelete(db, p->pOffset);
34 }
35 
36 /*
37 ** Initialize a SelectDest structure.
38 */
39 void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
40   pDest->eDest = eDest;
41   pDest->iParm = iParm;
42   pDest->affinity = 0;
43   pDest->iMem = 0;
44   pDest->nMem = 0;
45 }
46 
47 
48 /*
49 ** Allocate a new Select structure and return a pointer to that
50 ** structure.
51 */
52 Select *sqlite3SelectNew(
53   Parse *pParse,        /* Parsing context */
54   ExprList *pEList,     /* which columns to include in the result */
55   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
56   Expr *pWhere,         /* the WHERE clause */
57   ExprList *pGroupBy,   /* the GROUP BY clause */
58   Expr *pHaving,        /* the HAVING clause */
59   ExprList *pOrderBy,   /* the ORDER BY clause */
60   int isDistinct,       /* true if the DISTINCT keyword is present */
61   Expr *pLimit,         /* LIMIT value.  NULL means not used */
62   Expr *pOffset         /* OFFSET value.  NULL means no offset */
63 ){
64   Select *pNew;
65   Select standin;
66   sqlite3 *db = pParse->db;
67   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
68   assert( !pOffset || pLimit );   /* Can't have OFFSET without LIMIT. */
69   if( pNew==0 ){
70     pNew = &standin;
71     memset(pNew, 0, sizeof(*pNew));
72   }
73   if( pEList==0 ){
74     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
75   }
76   pNew->pEList = pEList;
77   pNew->pSrc = pSrc;
78   pNew->pWhere = pWhere;
79   pNew->pGroupBy = pGroupBy;
80   pNew->pHaving = pHaving;
81   pNew->pOrderBy = pOrderBy;
82   pNew->selFlags = isDistinct ? SF_Distinct : 0;
83   pNew->op = TK_SELECT;
84   assert( pOffset==0 || pLimit!=0 );
85   pNew->pLimit = pLimit;
86   pNew->pOffset = pOffset;
87   pNew->addrOpenEphm[0] = -1;
88   pNew->addrOpenEphm[1] = -1;
89   pNew->addrOpenEphm[2] = -1;
90   if( db->mallocFailed ) {
91     clearSelect(db, pNew);
92     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
93     pNew = 0;
94   }
95   return pNew;
96 }
97 
98 /*
99 ** Delete the given Select structure and all of its substructures.
100 */
101 void sqlite3SelectDelete(sqlite3 *db, Select *p){
102   if( p ){
103     clearSelect(db, p);
104     sqlite3DbFree(db, p);
105   }
106 }
107 
108 /*
109 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
110 ** type of join.  Return an integer constant that expresses that type
111 ** in terms of the following bit values:
112 **
113 **     JT_INNER
114 **     JT_CROSS
115 **     JT_OUTER
116 **     JT_NATURAL
117 **     JT_LEFT
118 **     JT_RIGHT
119 **
120 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
121 **
122 ** If an illegal or unsupported join type is seen, then still return
123 ** a join type, but put an error in the pParse structure.
124 */
125 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
126   int jointype = 0;
127   Token *apAll[3];
128   Token *p;
129   static const struct {
130     const char zKeyword[8];
131     u8 nChar;
132     u8 code;
133   } keywords[] = {
134     { "natural", 7, JT_NATURAL },
135     { "left",    4, JT_LEFT|JT_OUTER },
136     { "right",   5, JT_RIGHT|JT_OUTER },
137     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
138     { "outer",   5, JT_OUTER },
139     { "inner",   5, JT_INNER },
140     { "cross",   5, JT_INNER|JT_CROSS },
141   };
142   int i, j;
143   apAll[0] = pA;
144   apAll[1] = pB;
145   apAll[2] = pC;
146   for(i=0; i<3 && apAll[i]; i++){
147     p = apAll[i];
148     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
149       if( p->n==keywords[j].nChar
150           && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
151         jointype |= keywords[j].code;
152         break;
153       }
154     }
155     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
156       jointype |= JT_ERROR;
157       break;
158     }
159   }
160   if(
161      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
162      (jointype & JT_ERROR)!=0
163   ){
164     const char *zSp = " ";
165     assert( pB!=0 );
166     if( pC==0 ){ zSp++; }
167     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
168        "%T %T%s%T", pA, pB, zSp, pC);
169     jointype = JT_INNER;
170   }else if( jointype & JT_RIGHT ){
171     sqlite3ErrorMsg(pParse,
172       "RIGHT and FULL OUTER JOINs are not currently supported");
173     jointype = JT_INNER;
174   }
175   return jointype;
176 }
177 
178 /*
179 ** Return the index of a column in a table.  Return -1 if the column
180 ** is not contained in the table.
181 */
182 static int columnIndex(Table *pTab, const char *zCol){
183   int i;
184   for(i=0; i<pTab->nCol; i++){
185     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
186   }
187   return -1;
188 }
189 
190 /*
191 ** Set the value of a token to a '\000'-terminated string.
192 */
193 static void setToken(Token *p, const char *z){
194   p->z = (u8*)z;
195   p->n = z ? strlen(z) : 0;
196   p->dyn = 0;
197 }
198 
199 /*
200 ** Set the token to the double-quoted and escaped version of the string pointed
201 ** to by z. For example;
202 **
203 **    {a"bc}  ->  {"a""bc"}
204 */
205 static void setQuotedToken(Parse *pParse, Token *p, const char *z){
206 
207   /* Check if the string contains any " characters. If it does, then
208   ** this function will malloc space to create a quoted version of
209   ** the string in. Otherwise, save a call to sqlite3MPrintf() by
210   ** just copying the pointer to the string.
211   */
212   const char *z2 = z;
213   while( *z2 ){
214     if( *z2=='"' ) break;
215     z2++;
216   }
217 
218   if( *z2 ){
219     /* String contains " characters - copy and quote the string. */
220     p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z);
221     if( p->z ){
222       p->n = strlen((char *)p->z);
223       p->dyn = 1;
224     }
225   }else{
226     /* String contains no " characters - copy the pointer. */
227     p->z = (u8*)z;
228     p->n = (z2 - z);
229     p->dyn = 0;
230   }
231 }
232 
233 /*
234 ** Create an expression node for an identifier with the name of zName
235 */
236 Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
237   Token dummy;
238   setToken(&dummy, zName);
239   return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
240 }
241 
242 /*
243 ** Add a term to the WHERE expression in *ppExpr that requires the
244 ** zCol column to be equal in the two tables pTab1 and pTab2.
245 */
246 static void addWhereTerm(
247   Parse *pParse,           /* Parsing context */
248   const char *zCol,        /* Name of the column */
249   const Table *pTab1,      /* First table */
250   const char *zAlias1,     /* Alias for first table.  May be NULL */
251   const Table *pTab2,      /* Second table */
252   const char *zAlias2,     /* Alias for second table.  May be NULL */
253   int iRightJoinTable,     /* VDBE cursor for the right table */
254   Expr **ppExpr,           /* Add the equality term to this expression */
255   int isOuterJoin          /* True if dealing with an OUTER join */
256 ){
257   Expr *pE1a, *pE1b, *pE1c;
258   Expr *pE2a, *pE2b, *pE2c;
259   Expr *pE;
260 
261   pE1a = sqlite3CreateIdExpr(pParse, zCol);
262   pE2a = sqlite3CreateIdExpr(pParse, zCol);
263   if( zAlias1==0 ){
264     zAlias1 = pTab1->zName;
265   }
266   pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
267   if( zAlias2==0 ){
268     zAlias2 = pTab2->zName;
269   }
270   pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
271   pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
272   pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
273   pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
274   if( pE && isOuterJoin ){
275     ExprSetProperty(pE, EP_FromJoin);
276     pE->iRightJoinTable = iRightJoinTable;
277   }
278   *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
279 }
280 
281 /*
282 ** Set the EP_FromJoin property on all terms of the given expression.
283 ** And set the Expr.iRightJoinTable to iTable for every term in the
284 ** expression.
285 **
286 ** The EP_FromJoin property is used on terms of an expression to tell
287 ** the LEFT OUTER JOIN processing logic that this term is part of the
288 ** join restriction specified in the ON or USING clause and not a part
289 ** of the more general WHERE clause.  These terms are moved over to the
290 ** WHERE clause during join processing but we need to remember that they
291 ** originated in the ON or USING clause.
292 **
293 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
294 ** expression depends on table iRightJoinTable even if that table is not
295 ** explicitly mentioned in the expression.  That information is needed
296 ** for cases like this:
297 **
298 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
299 **
300 ** The where clause needs to defer the handling of the t1.x=5
301 ** term until after the t2 loop of the join.  In that way, a
302 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
303 ** defer the handling of t1.x=5, it will be processed immediately
304 ** after the t1 loop and rows with t1.x!=5 will never appear in
305 ** the output, which is incorrect.
306 */
307 static void setJoinExpr(Expr *p, int iTable){
308   while( p ){
309     ExprSetProperty(p, EP_FromJoin);
310     p->iRightJoinTable = iTable;
311     setJoinExpr(p->pLeft, iTable);
312     p = p->pRight;
313   }
314 }
315 
316 /*
317 ** This routine processes the join information for a SELECT statement.
318 ** ON and USING clauses are converted into extra terms of the WHERE clause.
319 ** NATURAL joins also create extra WHERE clause terms.
320 **
321 ** The terms of a FROM clause are contained in the Select.pSrc structure.
322 ** The left most table is the first entry in Select.pSrc.  The right-most
323 ** table is the last entry.  The join operator is held in the entry to
324 ** the left.  Thus entry 0 contains the join operator for the join between
325 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
326 ** also attached to the left entry.
327 **
328 ** This routine returns the number of errors encountered.
329 */
330 static int sqliteProcessJoin(Parse *pParse, Select *p){
331   SrcList *pSrc;                  /* All tables in the FROM clause */
332   int i, j;                       /* Loop counters */
333   struct SrcList_item *pLeft;     /* Left table being joined */
334   struct SrcList_item *pRight;    /* Right table being joined */
335 
336   pSrc = p->pSrc;
337   pLeft = &pSrc->a[0];
338   pRight = &pLeft[1];
339   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
340     Table *pLeftTab = pLeft->pTab;
341     Table *pRightTab = pRight->pTab;
342     int isOuter;
343 
344     if( pLeftTab==0 || pRightTab==0 ) continue;
345     isOuter = (pRight->jointype & JT_OUTER)!=0;
346 
347     /* When the NATURAL keyword is present, add WHERE clause terms for
348     ** every column that the two tables have in common.
349     */
350     if( pRight->jointype & JT_NATURAL ){
351       if( pRight->pOn || pRight->pUsing ){
352         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
353            "an ON or USING clause", 0);
354         return 1;
355       }
356       for(j=0; j<pLeftTab->nCol; j++){
357         char *zName = pLeftTab->aCol[j].zName;
358         if( columnIndex(pRightTab, zName)>=0 ){
359           addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
360                               pRightTab, pRight->zAlias,
361                               pRight->iCursor, &p->pWhere, isOuter);
362 
363         }
364       }
365     }
366 
367     /* Disallow both ON and USING clauses in the same join
368     */
369     if( pRight->pOn && pRight->pUsing ){
370       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
371         "clauses in the same join");
372       return 1;
373     }
374 
375     /* Add the ON clause to the end of the WHERE clause, connected by
376     ** an AND operator.
377     */
378     if( pRight->pOn ){
379       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
380       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
381       pRight->pOn = 0;
382     }
383 
384     /* Create extra terms on the WHERE clause for each column named
385     ** in the USING clause.  Example: If the two tables to be joined are
386     ** A and B and the USING clause names X, Y, and Z, then add this
387     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
388     ** Report an error if any column mentioned in the USING clause is
389     ** not contained in both tables to be joined.
390     */
391     if( pRight->pUsing ){
392       IdList *pList = pRight->pUsing;
393       for(j=0; j<pList->nId; j++){
394         char *zName = pList->a[j].zName;
395         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
396           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
397             "not present in both tables", zName);
398           return 1;
399         }
400         addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
401                             pRightTab, pRight->zAlias,
402                             pRight->iCursor, &p->pWhere, isOuter);
403       }
404     }
405   }
406   return 0;
407 }
408 
409 /*
410 ** Insert code into "v" that will push the record on the top of the
411 ** stack into the sorter.
412 */
413 static void pushOntoSorter(
414   Parse *pParse,         /* Parser context */
415   ExprList *pOrderBy,    /* The ORDER BY clause */
416   Select *pSelect,       /* The whole SELECT statement */
417   int regData            /* Register holding data to be sorted */
418 ){
419   Vdbe *v = pParse->pVdbe;
420   int nExpr = pOrderBy->nExpr;
421   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
422   int regRecord = sqlite3GetTempReg(pParse);
423   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
424   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
425   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
426   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
427   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
428   sqlite3ReleaseTempReg(pParse, regRecord);
429   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
430   if( pSelect->iLimit ){
431     int addr1, addr2;
432     int iLimit;
433     if( pSelect->iOffset ){
434       iLimit = pSelect->iOffset+1;
435     }else{
436       iLimit = pSelect->iLimit;
437     }
438     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
439     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
440     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
441     sqlite3VdbeJumpHere(v, addr1);
442     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
443     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
444     sqlite3VdbeJumpHere(v, addr2);
445     pSelect->iLimit = 0;
446   }
447 }
448 
449 /*
450 ** Add code to implement the OFFSET
451 */
452 static void codeOffset(
453   Vdbe *v,          /* Generate code into this VM */
454   Select *p,        /* The SELECT statement being coded */
455   int iContinue     /* Jump here to skip the current record */
456 ){
457   if( p->iOffset && iContinue!=0 ){
458     int addr;
459     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
460     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
461     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
462     VdbeComment((v, "skip OFFSET records"));
463     sqlite3VdbeJumpHere(v, addr);
464   }
465 }
466 
467 /*
468 ** Add code that will check to make sure the N registers starting at iMem
469 ** form a distinct entry.  iTab is a sorting index that holds previously
470 ** seen combinations of the N values.  A new entry is made in iTab
471 ** if the current N values are new.
472 **
473 ** A jump to addrRepeat is made and the N+1 values are popped from the
474 ** stack if the top N elements are not distinct.
475 */
476 static void codeDistinct(
477   Parse *pParse,     /* Parsing and code generating context */
478   int iTab,          /* A sorting index used to test for distinctness */
479   int addrRepeat,    /* Jump to here if not distinct */
480   int N,             /* Number of elements */
481   int iMem           /* First element */
482 ){
483   Vdbe *v;
484   int r1;
485 
486   v = pParse->pVdbe;
487   r1 = sqlite3GetTempReg(pParse);
488   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
489   sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1);
490   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
491   sqlite3ReleaseTempReg(pParse, r1);
492 }
493 
494 /*
495 ** Generate an error message when a SELECT is used within a subexpression
496 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
497 ** column.  We do this in a subroutine because the error occurs in multiple
498 ** places.
499 */
500 static int checkForMultiColumnSelectError(
501   Parse *pParse,       /* Parse context. */
502   SelectDest *pDest,   /* Destination of SELECT results */
503   int nExpr            /* Number of result columns returned by SELECT */
504 ){
505   int eDest = pDest->eDest;
506   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
507     sqlite3ErrorMsg(pParse, "only a single result allowed for "
508        "a SELECT that is part of an expression");
509     return 1;
510   }else{
511     return 0;
512   }
513 }
514 
515 /*
516 ** This routine generates the code for the inside of the inner loop
517 ** of a SELECT.
518 **
519 ** If srcTab and nColumn are both zero, then the pEList expressions
520 ** are evaluated in order to get the data for this row.  If nColumn>0
521 ** then data is pulled from srcTab and pEList is used only to get the
522 ** datatypes for each column.
523 */
524 static void selectInnerLoop(
525   Parse *pParse,          /* The parser context */
526   Select *p,              /* The complete select statement being coded */
527   ExprList *pEList,       /* List of values being extracted */
528   int srcTab,             /* Pull data from this table */
529   int nColumn,            /* Number of columns in the source table */
530   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
531   int distinct,           /* If >=0, make sure results are distinct */
532   SelectDest *pDest,      /* How to dispose of the results */
533   int iContinue,          /* Jump here to continue with next row */
534   int iBreak              /* Jump here to break out of the inner loop */
535 ){
536   Vdbe *v = pParse->pVdbe;
537   int i;
538   int hasDistinct;        /* True if the DISTINCT keyword is present */
539   int regResult;              /* Start of memory holding result set */
540   int eDest = pDest->eDest;   /* How to dispose of results */
541   int iParm = pDest->iParm;   /* First argument to disposal method */
542   int nResultCol;             /* Number of result columns */
543 
544   if( v==0 ) return;
545   assert( pEList!=0 );
546   hasDistinct = distinct>=0;
547   if( pOrderBy==0 && !hasDistinct ){
548     codeOffset(v, p, iContinue);
549   }
550 
551   /* Pull the requested columns.
552   */
553   if( nColumn>0 ){
554     nResultCol = nColumn;
555   }else{
556     nResultCol = pEList->nExpr;
557   }
558   if( pDest->iMem==0 ){
559     pDest->iMem = pParse->nMem+1;
560     pDest->nMem = nResultCol;
561     pParse->nMem += nResultCol;
562   }else if( pDest->nMem!=nResultCol ){
563     /* This happens when two SELECTs of a compound SELECT have differing
564     ** numbers of result columns.  The error message will be generated by
565     ** a higher-level routine. */
566     return;
567   }
568   regResult = pDest->iMem;
569   if( nColumn>0 ){
570     for(i=0; i<nColumn; i++){
571       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
572     }
573   }else if( eDest!=SRT_Exists ){
574     /* If the destination is an EXISTS(...) expression, the actual
575     ** values returned by the SELECT are not required.
576     */
577     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
578   }
579   nColumn = nResultCol;
580 
581   /* If the DISTINCT keyword was present on the SELECT statement
582   ** and this row has been seen before, then do not make this row
583   ** part of the result.
584   */
585   if( hasDistinct ){
586     assert( pEList!=0 );
587     assert( pEList->nExpr==nColumn );
588     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
589     if( pOrderBy==0 ){
590       codeOffset(v, p, iContinue);
591     }
592   }
593 
594   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
595     return;
596   }
597 
598   switch( eDest ){
599     /* In this mode, write each query result to the key of the temporary
600     ** table iParm.
601     */
602 #ifndef SQLITE_OMIT_COMPOUND_SELECT
603     case SRT_Union: {
604       int r1;
605       r1 = sqlite3GetTempReg(pParse);
606       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
607       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
608       sqlite3ReleaseTempReg(pParse, r1);
609       break;
610     }
611 
612     /* Construct a record from the query result, but instead of
613     ** saving that record, use it as a key to delete elements from
614     ** the temporary table iParm.
615     */
616     case SRT_Except: {
617       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
618       break;
619     }
620 #endif
621 
622     /* Store the result as data using a unique key.
623     */
624     case SRT_Table:
625     case SRT_EphemTab: {
626       int r1 = sqlite3GetTempReg(pParse);
627       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
628       if( pOrderBy ){
629         pushOntoSorter(pParse, pOrderBy, p, r1);
630       }else{
631         int r2 = sqlite3GetTempReg(pParse);
632         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
633         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
634         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
635         sqlite3ReleaseTempReg(pParse, r2);
636       }
637       sqlite3ReleaseTempReg(pParse, r1);
638       break;
639     }
640 
641 #ifndef SQLITE_OMIT_SUBQUERY
642     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
643     ** then there should be a single item on the stack.  Write this
644     ** item into the set table with bogus data.
645     */
646     case SRT_Set: {
647       assert( nColumn==1 );
648       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
649       if( pOrderBy ){
650         /* At first glance you would think we could optimize out the
651         ** ORDER BY in this case since the order of entries in the set
652         ** does not matter.  But there might be a LIMIT clause, in which
653         ** case the order does matter */
654         pushOntoSorter(pParse, pOrderBy, p, regResult);
655       }else{
656         int r1 = sqlite3GetTempReg(pParse);
657         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
658         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
659         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
660         sqlite3ReleaseTempReg(pParse, r1);
661       }
662       break;
663     }
664 
665     /* If any row exist in the result set, record that fact and abort.
666     */
667     case SRT_Exists: {
668       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
669       /* The LIMIT clause will terminate the loop for us */
670       break;
671     }
672 
673     /* If this is a scalar select that is part of an expression, then
674     ** store the results in the appropriate memory cell and break out
675     ** of the scan loop.
676     */
677     case SRT_Mem: {
678       assert( nColumn==1 );
679       if( pOrderBy ){
680         pushOntoSorter(pParse, pOrderBy, p, regResult);
681       }else{
682         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
683         /* The LIMIT clause will jump out of the loop for us */
684       }
685       break;
686     }
687 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
688 
689     /* Send the data to the callback function or to a subroutine.  In the
690     ** case of a subroutine, the subroutine itself is responsible for
691     ** popping the data from the stack.
692     */
693     case SRT_Coroutine:
694     case SRT_Output: {
695       if( pOrderBy ){
696         int r1 = sqlite3GetTempReg(pParse);
697         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
698         pushOntoSorter(pParse, pOrderBy, p, r1);
699         sqlite3ReleaseTempReg(pParse, r1);
700       }else if( eDest==SRT_Coroutine ){
701         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
702       }else{
703         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
704         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
705       }
706       break;
707     }
708 
709 #if !defined(SQLITE_OMIT_TRIGGER)
710     /* Discard the results.  This is used for SELECT statements inside
711     ** the body of a TRIGGER.  The purpose of such selects is to call
712     ** user-defined functions that have side effects.  We do not care
713     ** about the actual results of the select.
714     */
715     default: {
716       assert( eDest==SRT_Discard );
717       break;
718     }
719 #endif
720   }
721 
722   /* Jump to the end of the loop if the LIMIT is reached.
723   */
724   if( p->iLimit ){
725     assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
726                             ** pushOntoSorter() would have cleared p->iLimit */
727     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
728     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
729   }
730 }
731 
732 /*
733 ** Given an expression list, generate a KeyInfo structure that records
734 ** the collating sequence for each expression in that expression list.
735 **
736 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
737 ** KeyInfo structure is appropriate for initializing a virtual index to
738 ** implement that clause.  If the ExprList is the result set of a SELECT
739 ** then the KeyInfo structure is appropriate for initializing a virtual
740 ** index to implement a DISTINCT test.
741 **
742 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
743 ** function is responsible for seeing that this structure is eventually
744 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
745 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
746 */
747 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
748   sqlite3 *db = pParse->db;
749   int nExpr;
750   KeyInfo *pInfo;
751   struct ExprList_item *pItem;
752   int i;
753 
754   nExpr = pList->nExpr;
755   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
756   if( pInfo ){
757     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
758     pInfo->nField = nExpr;
759     pInfo->enc = ENC(db);
760     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
761       CollSeq *pColl;
762       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
763       if( !pColl ){
764         pColl = db->pDfltColl;
765       }
766       pInfo->aColl[i] = pColl;
767       pInfo->aSortOrder[i] = pItem->sortOrder;
768     }
769   }
770   return pInfo;
771 }
772 
773 
774 /*
775 ** If the inner loop was generated using a non-null pOrderBy argument,
776 ** then the results were placed in a sorter.  After the loop is terminated
777 ** we need to run the sorter and output the results.  The following
778 ** routine generates the code needed to do that.
779 */
780 static void generateSortTail(
781   Parse *pParse,    /* Parsing context */
782   Select *p,        /* The SELECT statement */
783   Vdbe *v,          /* Generate code into this VDBE */
784   int nColumn,      /* Number of columns of data */
785   SelectDest *pDest /* Write the sorted results here */
786 ){
787   int brk = sqlite3VdbeMakeLabel(v);
788   int cont = sqlite3VdbeMakeLabel(v);
789   int addr;
790   int iTab;
791   int pseudoTab = 0;
792   ExprList *pOrderBy = p->pOrderBy;
793 
794   int eDest = pDest->eDest;
795   int iParm = pDest->iParm;
796 
797   int regRow;
798   int regRowid;
799 
800   iTab = pOrderBy->iECursor;
801   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
802     pseudoTab = pParse->nTab++;
803     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nColumn);
804     sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, eDest==SRT_Output);
805   }
806   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, brk);
807   codeOffset(v, p, cont);
808   regRow = sqlite3GetTempReg(pParse);
809   regRowid = sqlite3GetTempReg(pParse);
810   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
811   switch( eDest ){
812     case SRT_Table:
813     case SRT_EphemTab: {
814       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
815       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
816       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
817       break;
818     }
819 #ifndef SQLITE_OMIT_SUBQUERY
820     case SRT_Set: {
821       assert( nColumn==1 );
822       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
823       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
824       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
825       break;
826     }
827     case SRT_Mem: {
828       assert( nColumn==1 );
829       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
830       /* The LIMIT clause will terminate the loop for us */
831       break;
832     }
833 #endif
834     case SRT_Output:
835     case SRT_Coroutine: {
836       int i;
837       sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid);
838       sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid);
839       for(i=0; i<nColumn; i++){
840         assert( regRow!=pDest->iMem+i );
841         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
842       }
843       if( eDest==SRT_Output ){
844         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
845         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
846       }else{
847         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
848       }
849       break;
850     }
851     default: {
852       /* Do nothing */
853       break;
854     }
855   }
856   sqlite3ReleaseTempReg(pParse, regRow);
857   sqlite3ReleaseTempReg(pParse, regRowid);
858 
859   /* LIMIT has been implemented by the pushOntoSorter() routine.
860   */
861   assert( p->iLimit==0 );
862 
863   /* The bottom of the loop
864   */
865   sqlite3VdbeResolveLabel(v, cont);
866   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
867   sqlite3VdbeResolveLabel(v, brk);
868   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
869     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
870   }
871 
872 }
873 
874 /*
875 ** Return a pointer to a string containing the 'declaration type' of the
876 ** expression pExpr. The string may be treated as static by the caller.
877 **
878 ** The declaration type is the exact datatype definition extracted from the
879 ** original CREATE TABLE statement if the expression is a column. The
880 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
881 ** is considered a column can be complex in the presence of subqueries. The
882 ** result-set expression in all of the following SELECT statements is
883 ** considered a column by this function.
884 **
885 **   SELECT col FROM tbl;
886 **   SELECT (SELECT col FROM tbl;
887 **   SELECT (SELECT col FROM tbl);
888 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
889 **
890 ** The declaration type for any expression other than a column is NULL.
891 */
892 static const char *columnType(
893   NameContext *pNC,
894   Expr *pExpr,
895   const char **pzOriginDb,
896   const char **pzOriginTab,
897   const char **pzOriginCol
898 ){
899   char const *zType = 0;
900   char const *zOriginDb = 0;
901   char const *zOriginTab = 0;
902   char const *zOriginCol = 0;
903   int j;
904   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
905 
906   switch( pExpr->op ){
907     case TK_AGG_COLUMN:
908     case TK_COLUMN: {
909       /* The expression is a column. Locate the table the column is being
910       ** extracted from in NameContext.pSrcList. This table may be real
911       ** database table or a subquery.
912       */
913       Table *pTab = 0;            /* Table structure column is extracted from */
914       Select *pS = 0;             /* Select the column is extracted from */
915       int iCol = pExpr->iColumn;  /* Index of column in pTab */
916       while( pNC && !pTab ){
917         SrcList *pTabList = pNC->pSrcList;
918         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
919         if( j<pTabList->nSrc ){
920           pTab = pTabList->a[j].pTab;
921           pS = pTabList->a[j].pSelect;
922         }else{
923           pNC = pNC->pNext;
924         }
925       }
926 
927       if( pTab==0 ){
928         /* FIX ME:
929         ** This can occurs if you have something like "SELECT new.x;" inside
930         ** a trigger.  In other words, if you reference the special "new"
931         ** table in the result set of a select.  We do not have a good way
932         ** to find the actual table type, so call it "TEXT".  This is really
933         ** something of a bug, but I do not know how to fix it.
934         **
935         ** This code does not produce the correct answer - it just prevents
936         ** a segfault.  See ticket #1229.
937         */
938         zType = "TEXT";
939         break;
940       }
941 
942       assert( pTab );
943       if( pS ){
944         /* The "table" is actually a sub-select or a view in the FROM clause
945         ** of the SELECT statement. Return the declaration type and origin
946         ** data for the result-set column of the sub-select.
947         */
948         if( iCol>=0 && iCol<pS->pEList->nExpr ){
949           /* If iCol is less than zero, then the expression requests the
950           ** rowid of the sub-select or view. This expression is legal (see
951           ** test case misc2.2.2) - it always evaluates to NULL.
952           */
953           NameContext sNC;
954           Expr *p = pS->pEList->a[iCol].pExpr;
955           sNC.pSrcList = pS->pSrc;
956           sNC.pNext = 0;
957           sNC.pParse = pNC->pParse;
958           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
959         }
960       }else if( pTab->pSchema ){
961         /* A real table */
962         assert( !pS );
963         if( iCol<0 ) iCol = pTab->iPKey;
964         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
965         if( iCol<0 ){
966           zType = "INTEGER";
967           zOriginCol = "rowid";
968         }else{
969           zType = pTab->aCol[iCol].zType;
970           zOriginCol = pTab->aCol[iCol].zName;
971         }
972         zOriginTab = pTab->zName;
973         if( pNC->pParse ){
974           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
975           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
976         }
977       }
978       break;
979     }
980 #ifndef SQLITE_OMIT_SUBQUERY
981     case TK_SELECT: {
982       /* The expression is a sub-select. Return the declaration type and
983       ** origin info for the single column in the result set of the SELECT
984       ** statement.
985       */
986       NameContext sNC;
987       Select *pS = pExpr->pSelect;
988       Expr *p = pS->pEList->a[0].pExpr;
989       sNC.pSrcList = pS->pSrc;
990       sNC.pNext = pNC;
991       sNC.pParse = pNC->pParse;
992       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
993       break;
994     }
995 #endif
996   }
997 
998   if( pzOriginDb ){
999     assert( pzOriginTab && pzOriginCol );
1000     *pzOriginDb = zOriginDb;
1001     *pzOriginTab = zOriginTab;
1002     *pzOriginCol = zOriginCol;
1003   }
1004   return zType;
1005 }
1006 
1007 /*
1008 ** Generate code that will tell the VDBE the declaration types of columns
1009 ** in the result set.
1010 */
1011 static void generateColumnTypes(
1012   Parse *pParse,      /* Parser context */
1013   SrcList *pTabList,  /* List of tables */
1014   ExprList *pEList    /* Expressions defining the result set */
1015 ){
1016 #ifndef SQLITE_OMIT_DECLTYPE
1017   Vdbe *v = pParse->pVdbe;
1018   int i;
1019   NameContext sNC;
1020   sNC.pSrcList = pTabList;
1021   sNC.pParse = pParse;
1022   for(i=0; i<pEList->nExpr; i++){
1023     Expr *p = pEList->a[i].pExpr;
1024     const char *zType;
1025 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1026     const char *zOrigDb = 0;
1027     const char *zOrigTab = 0;
1028     const char *zOrigCol = 0;
1029     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
1030 
1031     /* The vdbe must make its own copy of the column-type and other
1032     ** column specific strings, in case the schema is reset before this
1033     ** virtual machine is deleted.
1034     */
1035     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P4_TRANSIENT);
1036     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P4_TRANSIENT);
1037     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P4_TRANSIENT);
1038 #else
1039     zType = columnType(&sNC, p, 0, 0, 0);
1040 #endif
1041     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P4_TRANSIENT);
1042   }
1043 #endif /* SQLITE_OMIT_DECLTYPE */
1044 }
1045 
1046 /*
1047 ** Generate code that will tell the VDBE the names of columns
1048 ** in the result set.  This information is used to provide the
1049 ** azCol[] values in the callback.
1050 */
1051 static void generateColumnNames(
1052   Parse *pParse,      /* Parser context */
1053   SrcList *pTabList,  /* List of tables */
1054   ExprList *pEList    /* Expressions defining the result set */
1055 ){
1056   Vdbe *v = pParse->pVdbe;
1057   int i, j;
1058   sqlite3 *db = pParse->db;
1059   int fullNames, shortNames;
1060 
1061 #ifndef SQLITE_OMIT_EXPLAIN
1062   /* If this is an EXPLAIN, skip this step */
1063   if( pParse->explain ){
1064     return;
1065   }
1066 #endif
1067 
1068   assert( v!=0 );
1069   if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
1070   pParse->colNamesSet = 1;
1071   fullNames = (db->flags & SQLITE_FullColNames)!=0;
1072   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
1073   sqlite3VdbeSetNumCols(v, pEList->nExpr);
1074   for(i=0; i<pEList->nExpr; i++){
1075     Expr *p;
1076     p = pEList->a[i].pExpr;
1077     if( p==0 ) continue;
1078     if( pEList->a[i].zName ){
1079       char *zName = pEList->a[i].zName;
1080       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
1081     }else if( p->op==TK_COLUMN && pTabList ){
1082       Table *pTab;
1083       char *zCol;
1084       int iCol = p->iColumn;
1085       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
1086       assert( j<pTabList->nSrc );
1087       pTab = pTabList->a[j].pTab;
1088       if( iCol<0 ) iCol = pTab->iPKey;
1089       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1090       if( iCol<0 ){
1091         zCol = "rowid";
1092       }else{
1093         zCol = pTab->aCol[iCol].zName;
1094       }
1095       if( !shortNames && !fullNames ){
1096         sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
1097       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
1098         char *zName = 0;
1099         char *zTab;
1100 
1101         zTab = pTabList->a[j].zAlias;
1102         if( fullNames || zTab==0 ) zTab = pTab->zName;
1103         zName = sqlite3MPrintf(db, "%s.%s", zTab, zCol);
1104         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P4_DYNAMIC);
1105       }else{
1106         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
1107       }
1108     }else{
1109       sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
1110     }
1111   }
1112   generateColumnTypes(pParse, pTabList, pEList);
1113 }
1114 
1115 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1116 /*
1117 ** Name of the connection operator, used for error messages.
1118 */
1119 static const char *selectOpName(int id){
1120   char *z;
1121   switch( id ){
1122     case TK_ALL:       z = "UNION ALL";   break;
1123     case TK_INTERSECT: z = "INTERSECT";   break;
1124     case TK_EXCEPT:    z = "EXCEPT";      break;
1125     default:           z = "UNION";       break;
1126   }
1127   return z;
1128 }
1129 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1130 
1131 /*
1132 ** Given a an expression list (which is really the list of expressions
1133 ** that form the result set of a SELECT statement) compute appropriate
1134 ** column names for a table that would hold the expression list.
1135 **
1136 ** All column names will be unique.
1137 **
1138 ** Only the column names are computed.  Column.zType, Column.zColl,
1139 ** and other fields of Column are zeroed.
1140 **
1141 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
1142 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
1143 */
1144 static int selectColumnsFromExprList(
1145   Parse *pParse,          /* Parsing context */
1146   ExprList *pEList,       /* Expr list from which to derive column names */
1147   int *pnCol,             /* Write the number of columns here */
1148   Column **paCol          /* Write the new column list here */
1149 ){
1150   sqlite3 *db = pParse->db;
1151   int i, j, cnt;
1152   Column *aCol, *pCol;
1153   int nCol;
1154   Expr *p;
1155   char *zName;
1156   int nName;
1157 
1158   *pnCol = nCol = pEList->nExpr;
1159   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
1160   if( aCol==0 ) return SQLITE_NOMEM;
1161   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
1162     /* Get an appropriate name for the column
1163     */
1164     p = pEList->a[i].pExpr;
1165     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
1166     if( (zName = pEList->a[i].zName)!=0 ){
1167       /* If the column contains an "AS <name>" phrase, use <name> as the name */
1168       zName = sqlite3DbStrDup(db, zName);
1169     }else{
1170       Expr *pCol = p;
1171       Table *pTab;
1172       while( pCol->op==TK_DOT ) pCol = pCol->pRight;
1173       if( pCol->op==TK_COLUMN && (pTab = pCol->pTab)!=0 ){
1174         /* For columns use the column name name */
1175         int iCol = pCol->iColumn;
1176         if( iCol<0 ) iCol = pTab->iPKey;
1177         zName = sqlite3MPrintf(db, "%s",
1178                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
1179       }else{
1180         /* Use the original text of the column expression as its name */
1181         zName = sqlite3MPrintf(db, "%T", &pCol->span);
1182       }
1183     }
1184     if( db->mallocFailed ){
1185       sqlite3DbFree(db, zName);
1186       break;
1187     }
1188     sqlite3Dequote(zName);
1189 
1190     /* Make sure the column name is unique.  If the name is not unique,
1191     ** append a integer to the name so that it becomes unique.
1192     */
1193     nName = strlen(zName);
1194     for(j=cnt=0; j<i; j++){
1195       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
1196         char *zNewName;
1197         zName[nName] = 0;
1198         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
1199         sqlite3DbFree(db, zName);
1200         zName = zNewName;
1201         j = -1;
1202         if( zName==0 ) break;
1203       }
1204     }
1205     pCol->zName = zName;
1206   }
1207   if( db->mallocFailed ){
1208     int j;
1209     for(j=0; j<i; j++){
1210       sqlite3DbFree(db, aCol[j].zName);
1211     }
1212     sqlite3DbFree(db, aCol);
1213     *paCol = 0;
1214     *pnCol = 0;
1215     return SQLITE_NOMEM;
1216   }
1217   return SQLITE_OK;
1218 }
1219 
1220 /*
1221 ** Add type and collation information to a column list based on
1222 ** a SELECT statement.
1223 **
1224 ** The column list presumably came from selectColumnNamesFromExprList().
1225 ** The column list has only names, not types or collations.  This
1226 ** routine goes through and adds the types and collations.
1227 **
1228 ** This routine requires that all indentifiers in the SELECT
1229 ** statement be resolved.
1230 */
1231 static void selectAddColumnTypeAndCollation(
1232   Parse *pParse,        /* Parsing contexts */
1233   int nCol,             /* Number of columns */
1234   Column *aCol,         /* List of columns */
1235   Select *pSelect       /* SELECT used to determine types and collations */
1236 ){
1237   sqlite3 *db = pParse->db;
1238   NameContext sNC;
1239   Column *pCol;
1240   CollSeq *pColl;
1241   int i;
1242   Expr *p;
1243   struct ExprList_item *a;
1244 
1245   assert( pSelect!=0 );
1246   assert( (pSelect->selFlags & SF_Resolved)!=0 );
1247   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
1248   if( db->mallocFailed ) return;
1249   memset(&sNC, 0, sizeof(sNC));
1250   sNC.pSrcList = pSelect->pSrc;
1251   a = pSelect->pEList->a;
1252   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
1253     p = a[i].pExpr;
1254     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
1255     pCol->affinity = sqlite3ExprAffinity(p);
1256     pColl = sqlite3ExprCollSeq(pParse, p);
1257     if( pColl ){
1258       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
1259     }
1260   }
1261 }
1262 
1263 /*
1264 ** Given a SELECT statement, generate a Table structure that describes
1265 ** the result set of that SELECT.
1266 */
1267 Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
1268   Table *pTab;
1269   sqlite3 *db = pParse->db;
1270   int savedFlags;
1271 
1272   savedFlags = db->flags;
1273   db->flags &= ~SQLITE_FullColNames;
1274   db->flags |= SQLITE_ShortColNames;
1275   sqlite3SelectPrep(pParse, pSelect, 0);
1276   if( pParse->nErr ) return 0;
1277   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
1278   db->flags = savedFlags;
1279   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
1280   if( pTab==0 ){
1281     return 0;
1282   }
1283   pTab->db = db;
1284   pTab->nRef = 1;
1285   pTab->zName = 0;
1286   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
1287   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
1288   pTab->iPKey = -1;
1289   if( db->mallocFailed ){
1290     sqlite3DeleteTable(pTab);
1291     return 0;
1292   }
1293   return pTab;
1294 }
1295 
1296 /*
1297 ** Get a VDBE for the given parser context.  Create a new one if necessary.
1298 ** If an error occurs, return NULL and leave a message in pParse.
1299 */
1300 Vdbe *sqlite3GetVdbe(Parse *pParse){
1301   Vdbe *v = pParse->pVdbe;
1302   if( v==0 ){
1303     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1304 #ifndef SQLITE_OMIT_TRACE
1305     if( v ){
1306       sqlite3VdbeAddOp0(v, OP_Trace);
1307     }
1308 #endif
1309   }
1310   return v;
1311 }
1312 
1313 
1314 /*
1315 ** Compute the iLimit and iOffset fields of the SELECT based on the
1316 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
1317 ** that appear in the original SQL statement after the LIMIT and OFFSET
1318 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1319 ** are the integer memory register numbers for counters used to compute
1320 ** the limit and offset.  If there is no limit and/or offset, then
1321 ** iLimit and iOffset are negative.
1322 **
1323 ** This routine changes the values of iLimit and iOffset only if
1324 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
1325 ** iOffset should have been preset to appropriate default values
1326 ** (usually but not always -1) prior to calling this routine.
1327 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
1328 ** redefined.  The UNION ALL operator uses this property to force
1329 ** the reuse of the same limit and offset registers across multiple
1330 ** SELECT statements.
1331 */
1332 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
1333   Vdbe *v = 0;
1334   int iLimit = 0;
1335   int iOffset;
1336   int addr1;
1337   if( p->iLimit ) return;
1338 
1339   /*
1340   ** "LIMIT -1" always shows all rows.  There is some
1341   ** contraversy about what the correct behavior should be.
1342   ** The current implementation interprets "LIMIT 0" to mean
1343   ** no rows.
1344   */
1345   if( p->pLimit ){
1346     p->iLimit = iLimit = ++pParse->nMem;
1347     v = sqlite3GetVdbe(pParse);
1348     if( v==0 ) return;
1349     sqlite3ExprCode(pParse, p->pLimit, iLimit);
1350     sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
1351     VdbeComment((v, "LIMIT counter"));
1352     sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
1353   }
1354   if( p->pOffset ){
1355     p->iOffset = iOffset = ++pParse->nMem;
1356     if( p->pLimit ){
1357       pParse->nMem++;   /* Allocate an extra register for limit+offset */
1358     }
1359     v = sqlite3GetVdbe(pParse);
1360     if( v==0 ) return;
1361     sqlite3ExprCode(pParse, p->pOffset, iOffset);
1362     sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
1363     VdbeComment((v, "OFFSET counter"));
1364     addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
1365     sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
1366     sqlite3VdbeJumpHere(v, addr1);
1367     if( p->pLimit ){
1368       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
1369       VdbeComment((v, "LIMIT+OFFSET"));
1370       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
1371       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
1372       sqlite3VdbeJumpHere(v, addr1);
1373     }
1374   }
1375 }
1376 
1377 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1378 /*
1379 ** Return the appropriate collating sequence for the iCol-th column of
1380 ** the result set for the compound-select statement "p".  Return NULL if
1381 ** the column has no default collating sequence.
1382 **
1383 ** The collating sequence for the compound select is taken from the
1384 ** left-most term of the select that has a collating sequence.
1385 */
1386 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1387   CollSeq *pRet;
1388   if( p->pPrior ){
1389     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1390   }else{
1391     pRet = 0;
1392   }
1393   if( pRet==0 ){
1394     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1395   }
1396   return pRet;
1397 }
1398 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1399 
1400 /* Forward reference */
1401 static int multiSelectOrderBy(
1402   Parse *pParse,        /* Parsing context */
1403   Select *p,            /* The right-most of SELECTs to be coded */
1404   SelectDest *pDest     /* What to do with query results */
1405 );
1406 
1407 
1408 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1409 /*
1410 ** This routine is called to process a compound query form from
1411 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
1412 ** INTERSECT
1413 **
1414 ** "p" points to the right-most of the two queries.  the query on the
1415 ** left is p->pPrior.  The left query could also be a compound query
1416 ** in which case this routine will be called recursively.
1417 **
1418 ** The results of the total query are to be written into a destination
1419 ** of type eDest with parameter iParm.
1420 **
1421 ** Example 1:  Consider a three-way compound SQL statement.
1422 **
1423 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1424 **
1425 ** This statement is parsed up as follows:
1426 **
1427 **     SELECT c FROM t3
1428 **      |
1429 **      `----->  SELECT b FROM t2
1430 **                |
1431 **                `------>  SELECT a FROM t1
1432 **
1433 ** The arrows in the diagram above represent the Select.pPrior pointer.
1434 ** So if this routine is called with p equal to the t3 query, then
1435 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1436 **
1437 ** Notice that because of the way SQLite parses compound SELECTs, the
1438 ** individual selects always group from left to right.
1439 */
1440 static int multiSelect(
1441   Parse *pParse,        /* Parsing context */
1442   Select *p,            /* The right-most of SELECTs to be coded */
1443   SelectDest *pDest     /* What to do with query results */
1444 ){
1445   int rc = SQLITE_OK;   /* Success code from a subroutine */
1446   Select *pPrior;       /* Another SELECT immediately to our left */
1447   Vdbe *v;              /* Generate code to this VDBE */
1448   SelectDest dest;      /* Alternative data destination */
1449   Select *pDelete = 0;  /* Chain of simple selects to delete */
1450   sqlite3 *db;          /* Database connection */
1451 
1452   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1453   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
1454   */
1455   assert( p && p->pPrior );  /* Calling function guarantees this much */
1456   db = pParse->db;
1457   pPrior = p->pPrior;
1458   assert( pPrior->pRightmost!=pPrior );
1459   assert( pPrior->pRightmost==p->pRightmost );
1460   dest = *pDest;
1461   if( pPrior->pOrderBy ){
1462     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1463       selectOpName(p->op));
1464     rc = 1;
1465     goto multi_select_end;
1466   }
1467   if( pPrior->pLimit ){
1468     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
1469       selectOpName(p->op));
1470     rc = 1;
1471     goto multi_select_end;
1472   }
1473 
1474   v = sqlite3GetVdbe(pParse);
1475   assert( v!=0 );  /* The VDBE already created by calling function */
1476 
1477   /* Create the destination temporary table if necessary
1478   */
1479   if( dest.eDest==SRT_EphemTab ){
1480     assert( p->pEList );
1481     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
1482     dest.eDest = SRT_Table;
1483   }
1484 
1485   /* Make sure all SELECTs in the statement have the same number of elements
1486   ** in their result sets.
1487   */
1488   assert( p->pEList && pPrior->pEList );
1489   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
1490     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
1491       " do not have the same number of result columns", selectOpName(p->op));
1492     rc = 1;
1493     goto multi_select_end;
1494   }
1495 
1496   /* Compound SELECTs that have an ORDER BY clause are handled separately.
1497   */
1498   if( p->pOrderBy ){
1499     return multiSelectOrderBy(pParse, p, pDest);
1500   }
1501 
1502   /* Generate code for the left and right SELECT statements.
1503   */
1504   switch( p->op ){
1505     case TK_ALL: {
1506       int addr = 0;
1507       assert( !pPrior->pLimit );
1508       pPrior->pLimit = p->pLimit;
1509       pPrior->pOffset = p->pOffset;
1510       rc = sqlite3Select(pParse, pPrior, &dest);
1511       p->pLimit = 0;
1512       p->pOffset = 0;
1513       if( rc ){
1514         goto multi_select_end;
1515       }
1516       p->pPrior = 0;
1517       p->iLimit = pPrior->iLimit;
1518       p->iOffset = pPrior->iOffset;
1519       if( p->iLimit ){
1520         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
1521         VdbeComment((v, "Jump ahead if LIMIT reached"));
1522       }
1523       rc = sqlite3Select(pParse, p, &dest);
1524       pDelete = p->pPrior;
1525       p->pPrior = pPrior;
1526       if( rc ){
1527         goto multi_select_end;
1528       }
1529       if( addr ){
1530         sqlite3VdbeJumpHere(v, addr);
1531       }
1532       break;
1533     }
1534     case TK_EXCEPT:
1535     case TK_UNION: {
1536       int unionTab;    /* Cursor number of the temporary table holding result */
1537       int op = 0;      /* One of the SRT_ operations to apply to self */
1538       int priorOp;     /* The SRT_ operation to apply to prior selects */
1539       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
1540       int addr;
1541       SelectDest uniondest;
1542 
1543       priorOp = SRT_Union;
1544       if( dest.eDest==priorOp && !p->pLimit && !p->pOffset ){
1545         /* We can reuse a temporary table generated by a SELECT to our
1546         ** right.
1547         */
1548         unionTab = dest.iParm;
1549       }else{
1550         /* We will need to create our own temporary table to hold the
1551         ** intermediate results.
1552         */
1553         unionTab = pParse->nTab++;
1554         assert( p->pOrderBy==0 );
1555         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
1556         assert( p->addrOpenEphm[0] == -1 );
1557         p->addrOpenEphm[0] = addr;
1558         p->pRightmost->selFlags |= SF_UsesEphemeral;
1559         assert( p->pEList );
1560       }
1561 
1562       /* Code the SELECT statements to our left
1563       */
1564       assert( !pPrior->pOrderBy );
1565       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
1566       rc = sqlite3Select(pParse, pPrior, &uniondest);
1567       if( rc ){
1568         goto multi_select_end;
1569       }
1570 
1571       /* Code the current SELECT statement
1572       */
1573       if( p->op==TK_EXCEPT ){
1574         op = SRT_Except;
1575       }else{
1576         assert( p->op==TK_UNION );
1577         op = SRT_Union;
1578       }
1579       p->pPrior = 0;
1580       pLimit = p->pLimit;
1581       p->pLimit = 0;
1582       pOffset = p->pOffset;
1583       p->pOffset = 0;
1584       uniondest.eDest = op;
1585       rc = sqlite3Select(pParse, p, &uniondest);
1586       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
1587       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
1588       sqlite3ExprListDelete(db, p->pOrderBy);
1589       pDelete = p->pPrior;
1590       p->pPrior = pPrior;
1591       p->pOrderBy = 0;
1592       sqlite3ExprDelete(db, p->pLimit);
1593       p->pLimit = pLimit;
1594       p->pOffset = pOffset;
1595       p->iLimit = 0;
1596       p->iOffset = 0;
1597       if( rc ){
1598         goto multi_select_end;
1599       }
1600 
1601 
1602       /* Convert the data in the temporary table into whatever form
1603       ** it is that we currently need.
1604       */
1605       if( dest.eDest!=priorOp || unionTab!=dest.iParm ){
1606         int iCont, iBreak, iStart;
1607         assert( p->pEList );
1608         if( dest.eDest==SRT_Output ){
1609           Select *pFirst = p;
1610           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
1611           generateColumnNames(pParse, 0, pFirst->pEList);
1612         }
1613         iBreak = sqlite3VdbeMakeLabel(v);
1614         iCont = sqlite3VdbeMakeLabel(v);
1615         computeLimitRegisters(pParse, p, iBreak);
1616         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
1617         iStart = sqlite3VdbeCurrentAddr(v);
1618         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
1619                         0, -1, &dest, iCont, iBreak);
1620         sqlite3VdbeResolveLabel(v, iCont);
1621         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
1622         sqlite3VdbeResolveLabel(v, iBreak);
1623         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
1624       }
1625       break;
1626     }
1627     case TK_INTERSECT: {
1628       int tab1, tab2;
1629       int iCont, iBreak, iStart;
1630       Expr *pLimit, *pOffset;
1631       int addr;
1632       SelectDest intersectdest;
1633       int r1;
1634 
1635       /* INTERSECT is different from the others since it requires
1636       ** two temporary tables.  Hence it has its own case.  Begin
1637       ** by allocating the tables we will need.
1638       */
1639       tab1 = pParse->nTab++;
1640       tab2 = pParse->nTab++;
1641       assert( p->pOrderBy==0 );
1642 
1643       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
1644       assert( p->addrOpenEphm[0] == -1 );
1645       p->addrOpenEphm[0] = addr;
1646       p->pRightmost->selFlags |= SF_UsesEphemeral;
1647       assert( p->pEList );
1648 
1649       /* Code the SELECTs to our left into temporary table "tab1".
1650       */
1651       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
1652       rc = sqlite3Select(pParse, pPrior, &intersectdest);
1653       if( rc ){
1654         goto multi_select_end;
1655       }
1656 
1657       /* Code the current SELECT into temporary table "tab2"
1658       */
1659       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
1660       assert( p->addrOpenEphm[1] == -1 );
1661       p->addrOpenEphm[1] = addr;
1662       p->pPrior = 0;
1663       pLimit = p->pLimit;
1664       p->pLimit = 0;
1665       pOffset = p->pOffset;
1666       p->pOffset = 0;
1667       intersectdest.iParm = tab2;
1668       rc = sqlite3Select(pParse, p, &intersectdest);
1669       pDelete = p->pPrior;
1670       p->pPrior = pPrior;
1671       sqlite3ExprDelete(db, p->pLimit);
1672       p->pLimit = pLimit;
1673       p->pOffset = pOffset;
1674       if( rc ){
1675         goto multi_select_end;
1676       }
1677 
1678       /* Generate code to take the intersection of the two temporary
1679       ** tables.
1680       */
1681       assert( p->pEList );
1682       if( dest.eDest==SRT_Output ){
1683         Select *pFirst = p;
1684         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
1685         generateColumnNames(pParse, 0, pFirst->pEList);
1686       }
1687       iBreak = sqlite3VdbeMakeLabel(v);
1688       iCont = sqlite3VdbeMakeLabel(v);
1689       computeLimitRegisters(pParse, p, iBreak);
1690       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
1691       r1 = sqlite3GetTempReg(pParse);
1692       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
1693       sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1);
1694       sqlite3ReleaseTempReg(pParse, r1);
1695       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
1696                       0, -1, &dest, iCont, iBreak);
1697       sqlite3VdbeResolveLabel(v, iCont);
1698       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
1699       sqlite3VdbeResolveLabel(v, iBreak);
1700       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
1701       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
1702       break;
1703     }
1704   }
1705 
1706   /* Compute collating sequences used by
1707   ** temporary tables needed to implement the compound select.
1708   ** Attach the KeyInfo structure to all temporary tables.
1709   **
1710   ** This section is run by the right-most SELECT statement only.
1711   ** SELECT statements to the left always skip this part.  The right-most
1712   ** SELECT might also skip this part if it has no ORDER BY clause and
1713   ** no temp tables are required.
1714   */
1715   if( p->selFlags & SF_UsesEphemeral ){
1716     int i;                        /* Loop counter */
1717     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
1718     Select *pLoop;                /* For looping through SELECT statements */
1719     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
1720     int nCol;                     /* Number of columns in result set */
1721 
1722     assert( p->pRightmost==p );
1723     nCol = p->pEList->nExpr;
1724     pKeyInfo = sqlite3DbMallocZero(db,
1725                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
1726     if( !pKeyInfo ){
1727       rc = SQLITE_NOMEM;
1728       goto multi_select_end;
1729     }
1730 
1731     pKeyInfo->enc = ENC(db);
1732     pKeyInfo->nField = nCol;
1733 
1734     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
1735       *apColl = multiSelectCollSeq(pParse, p, i);
1736       if( 0==*apColl ){
1737         *apColl = db->pDfltColl;
1738       }
1739     }
1740 
1741     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
1742       for(i=0; i<2; i++){
1743         int addr = pLoop->addrOpenEphm[i];
1744         if( addr<0 ){
1745           /* If [0] is unused then [1] is also unused.  So we can
1746           ** always safely abort as soon as the first unused slot is found */
1747           assert( pLoop->addrOpenEphm[1]<0 );
1748           break;
1749         }
1750         sqlite3VdbeChangeP2(v, addr, nCol);
1751         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
1752         pLoop->addrOpenEphm[i] = -1;
1753       }
1754     }
1755     sqlite3DbFree(db, pKeyInfo);
1756   }
1757 
1758 multi_select_end:
1759   pDest->iMem = dest.iMem;
1760   pDest->nMem = dest.nMem;
1761   sqlite3SelectDelete(db, pDelete);
1762   return rc;
1763 }
1764 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1765 
1766 /*
1767 ** Code an output subroutine for a coroutine implementation of a
1768 ** SELECT statment.
1769 **
1770 ** The data to be output is contained in pIn->iMem.  There are
1771 ** pIn->nMem columns to be output.  pDest is where the output should
1772 ** be sent.
1773 **
1774 ** regReturn is the number of the register holding the subroutine
1775 ** return address.
1776 **
1777 ** If regPrev>0 then it is a the first register in a vector that
1778 ** records the previous output.  mem[regPrev] is a flag that is false
1779 ** if there has been no previous output.  If regPrev>0 then code is
1780 ** generated to suppress duplicates.  pKeyInfo is used for comparing
1781 ** keys.
1782 **
1783 ** If the LIMIT found in p->iLimit is reached, jump immediately to
1784 ** iBreak.
1785 */
1786 static int generateOutputSubroutine(
1787   Parse *pParse,          /* Parsing context */
1788   Select *p,              /* The SELECT statement */
1789   SelectDest *pIn,        /* Coroutine supplying data */
1790   SelectDest *pDest,      /* Where to send the data */
1791   int regReturn,          /* The return address register */
1792   int regPrev,            /* Previous result register.  No uniqueness if 0 */
1793   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
1794   int p4type,             /* The p4 type for pKeyInfo */
1795   int iBreak              /* Jump here if we hit the LIMIT */
1796 ){
1797   Vdbe *v = pParse->pVdbe;
1798   int iContinue;
1799   int addr;
1800 
1801   addr = sqlite3VdbeCurrentAddr(v);
1802   iContinue = sqlite3VdbeMakeLabel(v);
1803 
1804   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
1805   */
1806   if( regPrev ){
1807     int j1, j2;
1808     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
1809     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
1810                               (char*)pKeyInfo, p4type);
1811     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
1812     sqlite3VdbeJumpHere(v, j1);
1813     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
1814     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
1815   }
1816   if( pParse->db->mallocFailed ) return 0;
1817 
1818   /* Suppress the the first OFFSET entries if there is an OFFSET clause
1819   */
1820   codeOffset(v, p, iContinue);
1821 
1822   switch( pDest->eDest ){
1823     /* Store the result as data using a unique key.
1824     */
1825     case SRT_Table:
1826     case SRT_EphemTab: {
1827       int r1 = sqlite3GetTempReg(pParse);
1828       int r2 = sqlite3GetTempReg(pParse);
1829       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
1830       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
1831       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
1832       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1833       sqlite3ReleaseTempReg(pParse, r2);
1834       sqlite3ReleaseTempReg(pParse, r1);
1835       break;
1836     }
1837 
1838 #ifndef SQLITE_OMIT_SUBQUERY
1839     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
1840     ** then there should be a single item on the stack.  Write this
1841     ** item into the set table with bogus data.
1842     */
1843     case SRT_Set: {
1844       int r1;
1845       assert( pIn->nMem==1 );
1846       p->affinity =
1847          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
1848       r1 = sqlite3GetTempReg(pParse);
1849       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
1850       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
1851       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
1852       sqlite3ReleaseTempReg(pParse, r1);
1853       break;
1854     }
1855 
1856 #if 0  /* Never occurs on an ORDER BY query */
1857     /* If any row exist in the result set, record that fact and abort.
1858     */
1859     case SRT_Exists: {
1860       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
1861       /* The LIMIT clause will terminate the loop for us */
1862       break;
1863     }
1864 #endif
1865 
1866     /* If this is a scalar select that is part of an expression, then
1867     ** store the results in the appropriate memory cell and break out
1868     ** of the scan loop.
1869     */
1870     case SRT_Mem: {
1871       assert( pIn->nMem==1 );
1872       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
1873       /* The LIMIT clause will jump out of the loop for us */
1874       break;
1875     }
1876 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
1877 
1878     /* The results are stored in a sequence of registers
1879     ** starting at pDest->iMem.  Then the co-routine yields.
1880     */
1881     case SRT_Coroutine: {
1882       if( pDest->iMem==0 ){
1883         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
1884         pDest->nMem = pIn->nMem;
1885       }
1886       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
1887       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
1888       break;
1889     }
1890 
1891     /* Results are stored in a sequence of registers.  Then the
1892     ** OP_ResultRow opcode is used to cause sqlite3_step() to return
1893     ** the next row of result.
1894     */
1895     case SRT_Output: {
1896       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
1897       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
1898       break;
1899     }
1900 
1901 #if !defined(SQLITE_OMIT_TRIGGER)
1902     /* Discard the results.  This is used for SELECT statements inside
1903     ** the body of a TRIGGER.  The purpose of such selects is to call
1904     ** user-defined functions that have side effects.  We do not care
1905     ** about the actual results of the select.
1906     */
1907     default: {
1908       break;
1909     }
1910 #endif
1911   }
1912 
1913   /* Jump to the end of the loop if the LIMIT is reached.
1914   */
1915   if( p->iLimit ){
1916     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
1917     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
1918   }
1919 
1920   /* Generate the subroutine return
1921   */
1922   sqlite3VdbeResolveLabel(v, iContinue);
1923   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
1924 
1925   return addr;
1926 }
1927 
1928 /*
1929 ** Alternative compound select code generator for cases when there
1930 ** is an ORDER BY clause.
1931 **
1932 ** We assume a query of the following form:
1933 **
1934 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
1935 **
1936 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
1937 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
1938 ** co-routines.  Then run the co-routines in parallel and merge the results
1939 ** into the output.  In addition to the two coroutines (called selectA and
1940 ** selectB) there are 7 subroutines:
1941 **
1942 **    outA:    Move the output of the selectA coroutine into the output
1943 **             of the compound query.
1944 **
1945 **    outB:    Move the output of the selectB coroutine into the output
1946 **             of the compound query.  (Only generated for UNION and
1947 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
1948 **             appears only in B.)
1949 **
1950 **    AltB:    Called when there is data from both coroutines and A<B.
1951 **
1952 **    AeqB:    Called when there is data from both coroutines and A==B.
1953 **
1954 **    AgtB:    Called when there is data from both coroutines and A>B.
1955 **
1956 **    EofA:    Called when data is exhausted from selectA.
1957 **
1958 **    EofB:    Called when data is exhausted from selectB.
1959 **
1960 ** The implementation of the latter five subroutines depend on which
1961 ** <operator> is used:
1962 **
1963 **
1964 **             UNION ALL         UNION            EXCEPT          INTERSECT
1965 **          -------------  -----------------  --------------  -----------------
1966 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
1967 **
1968 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
1969 **
1970 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
1971 **
1972 **   EofA:   outB, nextB      outB, nextB          halt             halt
1973 **
1974 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
1975 **
1976 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
1977 ** causes an immediate jump to EofA and an EOF on B following nextB causes
1978 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
1979 ** following nextX causes a jump to the end of the select processing.
1980 **
1981 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
1982 ** within the output subroutine.  The regPrev register set holds the previously
1983 ** output value.  A comparison is made against this value and the output
1984 ** is skipped if the next results would be the same as the previous.
1985 **
1986 ** The implementation plan is to implement the two coroutines and seven
1987 ** subroutines first, then put the control logic at the bottom.  Like this:
1988 **
1989 **          goto Init
1990 **     coA: coroutine for left query (A)
1991 **     coB: coroutine for right query (B)
1992 **    outA: output one row of A
1993 **    outB: output one row of B (UNION and UNION ALL only)
1994 **    EofA: ...
1995 **    EofB: ...
1996 **    AltB: ...
1997 **    AeqB: ...
1998 **    AgtB: ...
1999 **    Init: initialize coroutine registers
2000 **          yield coA
2001 **          if eof(A) goto EofA
2002 **          yield coB
2003 **          if eof(B) goto EofB
2004 **    Cmpr: Compare A, B
2005 **          Jump AltB, AeqB, AgtB
2006 **     End: ...
2007 **
2008 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
2009 ** actually called using Gosub and they do not Return.  EofA and EofB loop
2010 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
2011 ** and AgtB jump to either L2 or to one of EofA or EofB.
2012 */
2013 #ifndef SQLITE_OMIT_COMPOUND_SELECT
2014 static int multiSelectOrderBy(
2015   Parse *pParse,        /* Parsing context */
2016   Select *p,            /* The right-most of SELECTs to be coded */
2017   SelectDest *pDest     /* What to do with query results */
2018 ){
2019   int i, j;             /* Loop counters */
2020   Select *pPrior;       /* Another SELECT immediately to our left */
2021   Vdbe *v;              /* Generate code to this VDBE */
2022   SelectDest destA;     /* Destination for coroutine A */
2023   SelectDest destB;     /* Destination for coroutine B */
2024   int regAddrA;         /* Address register for select-A coroutine */
2025   int regEofA;          /* Flag to indicate when select-A is complete */
2026   int regAddrB;         /* Address register for select-B coroutine */
2027   int regEofB;          /* Flag to indicate when select-B is complete */
2028   int addrSelectA;      /* Address of the select-A coroutine */
2029   int addrSelectB;      /* Address of the select-B coroutine */
2030   int regOutA;          /* Address register for the output-A subroutine */
2031   int regOutB;          /* Address register for the output-B subroutine */
2032   int addrOutA;         /* Address of the output-A subroutine */
2033   int addrOutB;         /* Address of the output-B subroutine */
2034   int addrEofA;         /* Address of the select-A-exhausted subroutine */
2035   int addrEofB;         /* Address of the select-B-exhausted subroutine */
2036   int addrAltB;         /* Address of the A<B subroutine */
2037   int addrAeqB;         /* Address of the A==B subroutine */
2038   int addrAgtB;         /* Address of the A>B subroutine */
2039   int regLimitA;        /* Limit register for select-A */
2040   int regLimitB;        /* Limit register for select-A */
2041   int regPrev;          /* A range of registers to hold previous output */
2042   int savedLimit;       /* Saved value of p->iLimit */
2043   int savedOffset;      /* Saved value of p->iOffset */
2044   int labelCmpr;        /* Label for the start of the merge algorithm */
2045   int labelEnd;         /* Label for the end of the overall SELECT stmt */
2046   int j1;               /* Jump instructions that get retargetted */
2047   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
2048   KeyInfo *pKeyDup;     /* Comparison information for duplicate removal */
2049   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
2050   sqlite3 *db;          /* Database connection */
2051   ExprList *pOrderBy;   /* The ORDER BY clause */
2052   int nOrderBy;         /* Number of terms in the ORDER BY clause */
2053   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
2054 
2055   assert( p->pOrderBy!=0 );
2056   db = pParse->db;
2057   v = pParse->pVdbe;
2058   if( v==0 ) return SQLITE_NOMEM;
2059   labelEnd = sqlite3VdbeMakeLabel(v);
2060   labelCmpr = sqlite3VdbeMakeLabel(v);
2061 
2062 
2063   /* Patch up the ORDER BY clause
2064   */
2065   op = p->op;
2066   pPrior = p->pPrior;
2067   assert( pPrior->pOrderBy==0 );
2068   pOrderBy = p->pOrderBy;
2069   assert( pOrderBy );
2070   nOrderBy = pOrderBy->nExpr;
2071 
2072   /* For operators other than UNION ALL we have to make sure that
2073   ** the ORDER BY clause covers every term of the result set.  Add
2074   ** terms to the ORDER BY clause as necessary.
2075   */
2076   if( op!=TK_ALL ){
2077     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
2078       struct ExprList_item *pItem;
2079       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
2080         assert( pItem->iCol>0 );
2081         if( pItem->iCol==i ) break;
2082       }
2083       if( j==nOrderBy ){
2084         Expr *pNew = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, 0);
2085         if( pNew==0 ) return SQLITE_NOMEM;
2086         pNew->flags |= EP_IntValue;
2087         pNew->iTable = i;
2088         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew, 0);
2089         pOrderBy->a[nOrderBy++].iCol = i;
2090       }
2091     }
2092   }
2093 
2094   /* Compute the comparison permutation and keyinfo that is used with
2095   ** the permutation in order to comparisons to determine if the next
2096   ** row of results comes from selectA or selectB.  Also add explicit
2097   ** collations to the ORDER BY clause terms so that when the subqueries
2098   ** to the right and the left are evaluated, they use the correct
2099   ** collation.
2100   */
2101   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
2102   if( aPermute ){
2103     struct ExprList_item *pItem;
2104     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
2105       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
2106       aPermute[i] = pItem->iCol - 1;
2107     }
2108     pKeyMerge =
2109       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
2110     if( pKeyMerge ){
2111       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
2112       pKeyMerge->nField = nOrderBy;
2113       pKeyMerge->enc = ENC(db);
2114       for(i=0; i<nOrderBy; i++){
2115         CollSeq *pColl;
2116         Expr *pTerm = pOrderBy->a[i].pExpr;
2117         if( pTerm->flags & EP_ExpCollate ){
2118           pColl = pTerm->pColl;
2119         }else{
2120           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
2121           pTerm->flags |= EP_ExpCollate;
2122           pTerm->pColl = pColl;
2123         }
2124         pKeyMerge->aColl[i] = pColl;
2125         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
2126       }
2127     }
2128   }else{
2129     pKeyMerge = 0;
2130   }
2131 
2132   /* Reattach the ORDER BY clause to the query.
2133   */
2134   p->pOrderBy = pOrderBy;
2135   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy);
2136 
2137   /* Allocate a range of temporary registers and the KeyInfo needed
2138   ** for the logic that removes duplicate result rows when the
2139   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
2140   */
2141   if( op==TK_ALL ){
2142     regPrev = 0;
2143   }else{
2144     int nExpr = p->pEList->nExpr;
2145     assert( nOrderBy>=nExpr );
2146     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
2147     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
2148     pKeyDup = sqlite3DbMallocZero(db,
2149                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
2150     if( pKeyDup ){
2151       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
2152       pKeyDup->nField = nExpr;
2153       pKeyDup->enc = ENC(db);
2154       for(i=0; i<nExpr; i++){
2155         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
2156         pKeyDup->aSortOrder[i] = 0;
2157       }
2158     }
2159   }
2160 
2161   /* Separate the left and the right query from one another
2162   */
2163   p->pPrior = 0;
2164   pPrior->pRightmost = 0;
2165   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
2166   if( pPrior->pPrior==0 ){
2167     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
2168   }
2169 
2170   /* Compute the limit registers */
2171   computeLimitRegisters(pParse, p, labelEnd);
2172   if( p->iLimit && op==TK_ALL ){
2173     regLimitA = ++pParse->nMem;
2174     regLimitB = ++pParse->nMem;
2175     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
2176                                   regLimitA);
2177     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
2178   }else{
2179     regLimitA = regLimitB = 0;
2180   }
2181   sqlite3ExprDelete(db, p->pLimit);
2182   p->pLimit = 0;
2183   sqlite3ExprDelete(db, p->pOffset);
2184   p->pOffset = 0;
2185 
2186   regAddrA = ++pParse->nMem;
2187   regEofA = ++pParse->nMem;
2188   regAddrB = ++pParse->nMem;
2189   regEofB = ++pParse->nMem;
2190   regOutA = ++pParse->nMem;
2191   regOutB = ++pParse->nMem;
2192   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
2193   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
2194 
2195   /* Jump past the various subroutines and coroutines to the main
2196   ** merge loop
2197   */
2198   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
2199   addrSelectA = sqlite3VdbeCurrentAddr(v);
2200 
2201 
2202   /* Generate a coroutine to evaluate the SELECT statement to the
2203   ** left of the compound operator - the "A" select.
2204   */
2205   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
2206   pPrior->iLimit = regLimitA;
2207   sqlite3Select(pParse, pPrior, &destA);
2208   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
2209   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2210   VdbeNoopComment((v, "End coroutine for left SELECT"));
2211 
2212   /* Generate a coroutine to evaluate the SELECT statement on
2213   ** the right - the "B" select
2214   */
2215   addrSelectB = sqlite3VdbeCurrentAddr(v);
2216   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
2217   savedLimit = p->iLimit;
2218   savedOffset = p->iOffset;
2219   p->iLimit = regLimitB;
2220   p->iOffset = 0;
2221   sqlite3Select(pParse, p, &destB);
2222   p->iLimit = savedLimit;
2223   p->iOffset = savedOffset;
2224   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
2225   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
2226   VdbeNoopComment((v, "End coroutine for right SELECT"));
2227 
2228   /* Generate a subroutine that outputs the current row of the A
2229   ** select as the next output row of the compound select.
2230   */
2231   VdbeNoopComment((v, "Output routine for A"));
2232   addrOutA = generateOutputSubroutine(pParse,
2233                  p, &destA, pDest, regOutA,
2234                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
2235 
2236   /* Generate a subroutine that outputs the current row of the B
2237   ** select as the next output row of the compound select.
2238   */
2239   if( op==TK_ALL || op==TK_UNION ){
2240     VdbeNoopComment((v, "Output routine for B"));
2241     addrOutB = generateOutputSubroutine(pParse,
2242                  p, &destB, pDest, regOutB,
2243                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
2244   }
2245 
2246   /* Generate a subroutine to run when the results from select A
2247   ** are exhausted and only data in select B remains.
2248   */
2249   VdbeNoopComment((v, "eof-A subroutine"));
2250   if( op==TK_EXCEPT || op==TK_INTERSECT ){
2251     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
2252   }else{
2253     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
2254     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
2255     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
2256     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
2257   }
2258 
2259   /* Generate a subroutine to run when the results from select B
2260   ** are exhausted and only data in select A remains.
2261   */
2262   if( op==TK_INTERSECT ){
2263     addrEofB = addrEofA;
2264   }else{
2265     VdbeNoopComment((v, "eof-B subroutine"));
2266     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
2267     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
2268     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2269     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
2270   }
2271 
2272   /* Generate code to handle the case of A<B
2273   */
2274   VdbeNoopComment((v, "A-lt-B subroutine"));
2275   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
2276   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2277   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
2278   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2279 
2280   /* Generate code to handle the case of A==B
2281   */
2282   if( op==TK_ALL ){
2283     addrAeqB = addrAltB;
2284   }else if( op==TK_INTERSECT ){
2285     addrAeqB = addrAltB;
2286     addrAltB++;
2287   }else{
2288     VdbeNoopComment((v, "A-eq-B subroutine"));
2289     addrAeqB =
2290     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2291     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
2292     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2293   }
2294 
2295   /* Generate code to handle the case of A>B
2296   */
2297   VdbeNoopComment((v, "A-gt-B subroutine"));
2298   addrAgtB = sqlite3VdbeCurrentAddr(v);
2299   if( op==TK_ALL || op==TK_UNION ){
2300     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
2301   }
2302   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
2303   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
2304   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2305 
2306   /* This code runs once to initialize everything.
2307   */
2308   sqlite3VdbeJumpHere(v, j1);
2309   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
2310   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
2311   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
2312   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
2313   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
2314   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
2315 
2316   /* Implement the main merge loop
2317   */
2318   sqlite3VdbeResolveLabel(v, labelCmpr);
2319   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
2320   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
2321                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
2322   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
2323 
2324   /* Release temporary registers
2325   */
2326   if( regPrev ){
2327     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
2328   }
2329 
2330   /* Jump to the this point in order to terminate the query.
2331   */
2332   sqlite3VdbeResolveLabel(v, labelEnd);
2333 
2334   /* Set the number of output columns
2335   */
2336   if( pDest->eDest==SRT_Output ){
2337     Select *pFirst = pPrior;
2338     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
2339     generateColumnNames(pParse, 0, pFirst->pEList);
2340   }
2341 
2342   /* Reassembly the compound query so that it will be freed correctly
2343   ** by the calling function */
2344   if( p->pPrior ){
2345     sqlite3SelectDelete(db, p->pPrior);
2346   }
2347   p->pPrior = pPrior;
2348 
2349   /*** TBD:  Insert subroutine calls to close cursors on incomplete
2350   **** subqueries ****/
2351   return SQLITE_OK;
2352 }
2353 #endif
2354 
2355 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
2356 /* Forward Declarations */
2357 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
2358 static void substSelect(sqlite3*, Select *, int, ExprList *);
2359 
2360 /*
2361 ** Scan through the expression pExpr.  Replace every reference to
2362 ** a column in table number iTable with a copy of the iColumn-th
2363 ** entry in pEList.  (But leave references to the ROWID column
2364 ** unchanged.)
2365 **
2366 ** This routine is part of the flattening procedure.  A subquery
2367 ** whose result set is defined by pEList appears as entry in the
2368 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
2369 ** FORM clause entry is iTable.  This routine make the necessary
2370 ** changes to pExpr so that it refers directly to the source table
2371 ** of the subquery rather the result set of the subquery.
2372 */
2373 static void substExpr(
2374   sqlite3 *db,        /* Report malloc errors to this connection */
2375   Expr *pExpr,        /* Expr in which substitution occurs */
2376   int iTable,         /* Table to be substituted */
2377   ExprList *pEList    /* Substitute expressions */
2378 ){
2379   if( pExpr==0 ) return;
2380   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
2381     if( pExpr->iColumn<0 ){
2382       pExpr->op = TK_NULL;
2383     }else{
2384       Expr *pNew;
2385       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
2386       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
2387       pNew = pEList->a[pExpr->iColumn].pExpr;
2388       assert( pNew!=0 );
2389       pExpr->op = pNew->op;
2390       assert( pExpr->pLeft==0 );
2391       pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
2392       assert( pExpr->pRight==0 );
2393       pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
2394       assert( pExpr->pList==0 );
2395       pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
2396       pExpr->iTable = pNew->iTable;
2397       pExpr->pTab = pNew->pTab;
2398       pExpr->iColumn = pNew->iColumn;
2399       pExpr->iAgg = pNew->iAgg;
2400       sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
2401       sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
2402       pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
2403       pExpr->flags = pNew->flags;
2404     }
2405   }else{
2406     substExpr(db, pExpr->pLeft, iTable, pEList);
2407     substExpr(db, pExpr->pRight, iTable, pEList);
2408     substSelect(db, pExpr->pSelect, iTable, pEList);
2409     substExprList(db, pExpr->pList, iTable, pEList);
2410   }
2411 }
2412 static void substExprList(
2413   sqlite3 *db,         /* Report malloc errors here */
2414   ExprList *pList,     /* List to scan and in which to make substitutes */
2415   int iTable,          /* Table to be substituted */
2416   ExprList *pEList     /* Substitute values */
2417 ){
2418   int i;
2419   if( pList==0 ) return;
2420   for(i=0; i<pList->nExpr; i++){
2421     substExpr(db, pList->a[i].pExpr, iTable, pEList);
2422   }
2423 }
2424 static void substSelect(
2425   sqlite3 *db,         /* Report malloc errors here */
2426   Select *p,           /* SELECT statement in which to make substitutions */
2427   int iTable,          /* Table to be replaced */
2428   ExprList *pEList     /* Substitute values */
2429 ){
2430   SrcList *pSrc;
2431   struct SrcList_item *pItem;
2432   int i;
2433   if( !p ) return;
2434   substExprList(db, p->pEList, iTable, pEList);
2435   substExprList(db, p->pGroupBy, iTable, pEList);
2436   substExprList(db, p->pOrderBy, iTable, pEList);
2437   substExpr(db, p->pHaving, iTable, pEList);
2438   substExpr(db, p->pWhere, iTable, pEList);
2439   substSelect(db, p->pPrior, iTable, pEList);
2440   pSrc = p->pSrc;
2441   if( pSrc ){
2442     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
2443       substSelect(db, pItem->pSelect, iTable, pEList);
2444     }
2445   }
2446 }
2447 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
2448 
2449 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
2450 /*
2451 ** This routine attempts to flatten subqueries in order to speed
2452 ** execution.  It returns 1 if it makes changes and 0 if no flattening
2453 ** occurs.
2454 **
2455 ** To understand the concept of flattening, consider the following
2456 ** query:
2457 **
2458 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
2459 **
2460 ** The default way of implementing this query is to execute the
2461 ** subquery first and store the results in a temporary table, then
2462 ** run the outer query on that temporary table.  This requires two
2463 ** passes over the data.  Furthermore, because the temporary table
2464 ** has no indices, the WHERE clause on the outer query cannot be
2465 ** optimized.
2466 **
2467 ** This routine attempts to rewrite queries such as the above into
2468 ** a single flat select, like this:
2469 **
2470 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
2471 **
2472 ** The code generated for this simpification gives the same result
2473 ** but only has to scan the data once.  And because indices might
2474 ** exist on the table t1, a complete scan of the data might be
2475 ** avoided.
2476 **
2477 ** Flattening is only attempted if all of the following are true:
2478 **
2479 **   (1)  The subquery and the outer query do not both use aggregates.
2480 **
2481 **   (2)  The subquery is not an aggregate or the outer query is not a join.
2482 **
2483 **   (3)  The subquery is not the right operand of a left outer join
2484 **        (Originally ticket #306.  Strenghtened by ticket #3300)
2485 **
2486 **   (4)  The subquery is not DISTINCT or the outer query is not a join.
2487 **
2488 **   (5)  The subquery is not DISTINCT or the outer query does not use
2489 **        aggregates.
2490 **
2491 **   (6)  The subquery does not use aggregates or the outer query is not
2492 **        DISTINCT.
2493 **
2494 **   (7)  The subquery has a FROM clause.
2495 **
2496 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
2497 **
2498 **   (9)  The subquery does not use LIMIT or the outer query does not use
2499 **        aggregates.
2500 **
2501 **  (10)  The subquery does not use aggregates or the outer query does not
2502 **        use LIMIT.
2503 **
2504 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
2505 **
2506 **  (12)  Not implemented.  Subsumed into restriction (3).  Was previously
2507 **        a separate restriction deriving from ticket #350.
2508 **
2509 **  (13)  The subquery and outer query do not both use LIMIT
2510 **
2511 **  (14)  The subquery does not use OFFSET
2512 **
2513 **  (15)  The outer query is not part of a compound select or the
2514 **        subquery does not have both an ORDER BY and a LIMIT clause.
2515 **        (See ticket #2339)
2516 **
2517 **  (16)  The outer query is not an aggregate or the subquery does
2518 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
2519 **        until we introduced the group_concat() function.
2520 **
2521 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
2522 **        compound clause made up entirely of non-aggregate queries, and
2523 **        the parent query:
2524 **
2525 **          * is not itself part of a compound select,
2526 **          * is not an aggregate or DISTINCT query, and
2527 **          * has no other tables or sub-selects in the FROM clause.
2528 **
2529 **        The parent and sub-query may contain WHERE clauses. Subject to
2530 **        rules (11), (13) and (14), they may also contain ORDER BY,
2531 **        LIMIT and OFFSET clauses.
2532 **
2533 **  (18)  If the sub-query is a compound select, then all terms of the
2534 **        ORDER by clause of the parent must be simple references to
2535 **        columns of the sub-query.
2536 **
2537 **  (19)  The subquery does not use LIMIT or the outer query does not
2538 **        have a WHERE clause.
2539 **
2540 ** In this routine, the "p" parameter is a pointer to the outer query.
2541 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
2542 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
2543 **
2544 ** If flattening is not attempted, this routine is a no-op and returns 0.
2545 ** If flattening is attempted this routine returns 1.
2546 **
2547 ** All of the expression analysis must occur on both the outer query and
2548 ** the subquery before this routine runs.
2549 */
2550 static int flattenSubquery(
2551   Parse *pParse,       /* Parsing context */
2552   Select *p,           /* The parent or outer SELECT statement */
2553   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
2554   int isAgg,           /* True if outer SELECT uses aggregate functions */
2555   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
2556 ){
2557   const char *zSavedAuthContext = pParse->zAuthContext;
2558   Select *pParent;
2559   Select *pSub;       /* The inner query or "subquery" */
2560   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
2561   SrcList *pSrc;      /* The FROM clause of the outer query */
2562   SrcList *pSubSrc;   /* The FROM clause of the subquery */
2563   ExprList *pList;    /* The result set of the outer query */
2564   int iParent;        /* VDBE cursor number of the pSub result set temp table */
2565   int i;              /* Loop counter */
2566   Expr *pWhere;                    /* The WHERE clause */
2567   struct SrcList_item *pSubitem;   /* The subquery */
2568   sqlite3 *db = pParse->db;
2569 
2570   /* Check to see if flattening is permitted.  Return 0 if not.
2571   */
2572   if( p==0 ) return 0;
2573   pSrc = p->pSrc;
2574   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
2575   pSubitem = &pSrc->a[iFrom];
2576   iParent = pSubitem->iCursor;
2577   pSub = pSubitem->pSelect;
2578   assert( pSub!=0 );
2579   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
2580   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
2581   pSubSrc = pSub->pSrc;
2582   assert( pSubSrc );
2583   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
2584   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
2585   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
2586   ** became arbitrary expressions, we were forced to add restrictions (13)
2587   ** and (14). */
2588   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
2589   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
2590   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
2591     return 0;                                            /* Restriction (15) */
2592   }
2593   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
2594   if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit)
2595          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
2596      return 0;
2597   }
2598   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
2599      return 0;         /* Restriction (6)  */
2600   }
2601   if( p->pOrderBy && pSub->pOrderBy ){
2602      return 0;                                           /* Restriction (11) */
2603   }
2604   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
2605   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
2606 
2607   /* OBSOLETE COMMENT 1:
2608   ** Restriction 3:  If the subquery is a join, make sure the subquery is
2609   ** not used as the right operand of an outer join.  Examples of why this
2610   ** is not allowed:
2611   **
2612   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
2613   **
2614   ** If we flatten the above, we would get
2615   **
2616   **         (t1 LEFT OUTER JOIN t2) JOIN t3
2617   **
2618   ** which is not at all the same thing.
2619   **
2620   ** OBSOLETE COMMENT 2:
2621   ** Restriction 12:  If the subquery is the right operand of a left outer
2622   ** join, make sure the subquery has no WHERE clause.
2623   ** An examples of why this is not allowed:
2624   **
2625   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
2626   **
2627   ** If we flatten the above, we would get
2628   **
2629   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
2630   **
2631   ** But the t2.x>0 test will always fail on a NULL row of t2, which
2632   ** effectively converts the OUTER JOIN into an INNER JOIN.
2633   **
2634   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
2635   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
2636   ** is fraught with danger.  Best to avoid the whole thing.  If the
2637   ** subquery is the right term of a LEFT JOIN, then do not flatten.
2638   */
2639   if( (pSubitem->jointype & JT_OUTER)!=0 ){
2640     return 0;
2641   }
2642 
2643   /* Restriction 17: If the sub-query is a compound SELECT, then it must
2644   ** use only the UNION ALL operator. And none of the simple select queries
2645   ** that make up the compound SELECT are allowed to be aggregate or distinct
2646   ** queries.
2647   */
2648   if( pSub->pPrior ){
2649     if( p->pPrior || isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
2650       return 0;
2651     }
2652     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
2653       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
2654        || (pSub1->pPrior && pSub1->op!=TK_ALL)
2655        || !pSub1->pSrc || pSub1->pSrc->nSrc!=1
2656       ){
2657         return 0;
2658       }
2659     }
2660 
2661     /* Restriction 18. */
2662     if( p->pOrderBy ){
2663       int ii;
2664       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
2665         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
2666       }
2667     }
2668   }
2669 
2670   /***** If we reach this point, flattening is permitted. *****/
2671 
2672   /* Authorize the subquery */
2673   pParse->zAuthContext = pSubitem->zName;
2674   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
2675   pParse->zAuthContext = zSavedAuthContext;
2676 
2677   /* If the sub-query is a compound SELECT statement, then (by restrictions
2678   ** 17 and 18 above) it must be a UNION ALL and the parent query must
2679   ** be of the form:
2680   **
2681   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
2682   **
2683   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
2684   ** creates N copies of the parent query without any ORDER BY, LIMIT or
2685   ** OFFSET clauses and joins them to the left-hand-side of the original
2686   ** using UNION ALL operators. In this case N is the number of simple
2687   ** select statements in the compound sub-query.
2688   */
2689   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
2690     Select *pNew;
2691     ExprList *pOrderBy = p->pOrderBy;
2692     Expr *pLimit = p->pLimit;
2693     Expr *pOffset = p->pOffset;
2694     Select *pPrior = p->pPrior;
2695     p->pOrderBy = 0;
2696     p->pSrc = 0;
2697     p->pPrior = 0;
2698     p->pLimit = 0;
2699     pNew = sqlite3SelectDup(db, p);
2700     pNew->pPrior = pPrior;
2701     p->pPrior = pNew;
2702     p->pOrderBy = pOrderBy;
2703     p->op = TK_ALL;
2704     p->pSrc = pSrc;
2705     p->pLimit = pLimit;
2706     p->pOffset = pOffset;
2707     p->pRightmost = 0;
2708     pNew->pRightmost = 0;
2709   }
2710 
2711   /* Begin flattening the iFrom-th entry of the FROM clause
2712   ** in the outer query.
2713   */
2714   pSub = pSub1 = pSubitem->pSelect;
2715   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
2716     int nSubSrc = pSubSrc->nSrc;
2717     int jointype = 0;
2718     pSubSrc = pSub->pSrc;
2719     pSrc = pParent->pSrc;
2720 
2721     /* Move all of the FROM elements of the subquery into the
2722     ** the FROM clause of the outer query.  Before doing this, remember
2723     ** the cursor number for the original outer query FROM element in
2724     ** iParent.  The iParent cursor will never be used.  Subsequent code
2725     ** will scan expressions looking for iParent references and replace
2726     ** those references with expressions that resolve to the subquery FROM
2727     ** elements we are now copying in.
2728     */
2729     if( pSrc ){
2730       Table *pTabToDel;
2731       pSubitem = &pSrc->a[iFrom];
2732       nSubSrc = pSubSrc->nSrc;
2733       jointype = pSubitem->jointype;
2734       sqlite3DbFree(db, pSubitem->zDatabase);
2735       sqlite3DbFree(db, pSubitem->zName);
2736       sqlite3DbFree(db, pSubitem->zAlias);
2737       pSubitem->zDatabase = 0;
2738       pSubitem->zName = 0;
2739       pSubitem->zAlias = 0;
2740 
2741       /* If the FROM element is a subquery, defer deleting the Table
2742       ** object associated with that subquery until code generation is
2743       ** complete, since there may still exist Expr.pTab entires that
2744       ** refer to the subquery even after flattening.  Ticket #3346.
2745       */
2746       if( (pTabToDel = pSubitem->pTab)!=0 ){
2747         if( pTabToDel->nRef==1 ){
2748           pTabToDel->pNextZombie = pParse->pZombieTab;
2749           pParse->pZombieTab = pTabToDel;
2750         }else{
2751           pTabToDel->nRef--;
2752         }
2753       }
2754       pSubitem->pTab = 0;
2755     }
2756     if( nSubSrc!=1 || !pSrc ){
2757       int extra = nSubSrc - 1;
2758       for(i=(pSrc?1:0); i<nSubSrc; i++){
2759         pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0);
2760         if( pSrc==0 ){
2761           pParent->pSrc = 0;
2762           return 1;
2763         }
2764       }
2765       pParent->pSrc = pSrc;
2766       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2767         pSrc->a[i] = pSrc->a[i-extra];
2768       }
2769     }
2770     for(i=0; i<nSubSrc; i++){
2771       pSrc->a[i+iFrom] = pSubSrc->a[i];
2772       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2773     }
2774     pSrc->a[iFrom].jointype = jointype;
2775 
2776     /* Now begin substituting subquery result set expressions for
2777     ** references to the iParent in the outer query.
2778     **
2779     ** Example:
2780     **
2781     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2782     **   \                     \_____________ subquery __________/          /
2783     **    \_____________________ outer query ______________________________/
2784     **
2785     ** We look at every expression in the outer query and every place we see
2786     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2787     */
2788     pList = pParent->pEList;
2789     for(i=0; i<pList->nExpr; i++){
2790       Expr *pExpr;
2791       if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
2792         pList->a[i].zName =
2793                sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
2794       }
2795     }
2796     substExprList(db, pParent->pEList, iParent, pSub->pEList);
2797     if( isAgg ){
2798       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
2799       substExpr(db, pParent->pHaving, iParent, pSub->pEList);
2800     }
2801     if( pSub->pOrderBy ){
2802       assert( pParent->pOrderBy==0 );
2803       pParent->pOrderBy = pSub->pOrderBy;
2804       pSub->pOrderBy = 0;
2805     }else if( pParent->pOrderBy ){
2806       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
2807     }
2808     if( pSub->pWhere ){
2809       pWhere = sqlite3ExprDup(db, pSub->pWhere);
2810     }else{
2811       pWhere = 0;
2812     }
2813     if( subqueryIsAgg ){
2814       assert( pParent->pHaving==0 );
2815       pParent->pHaving = pParent->pWhere;
2816       pParent->pWhere = pWhere;
2817       substExpr(db, pParent->pHaving, iParent, pSub->pEList);
2818       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
2819                                   sqlite3ExprDup(db, pSub->pHaving));
2820       assert( pParent->pGroupBy==0 );
2821       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
2822     }else{
2823       substExpr(db, pParent->pWhere, iParent, pSub->pEList);
2824       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
2825     }
2826 
2827     /* The flattened query is distinct if either the inner or the
2828     ** outer query is distinct.
2829     */
2830     pParent->selFlags |= pSub->selFlags & SF_Distinct;
2831 
2832     /*
2833     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2834     **
2835     ** One is tempted to try to add a and b to combine the limits.  But this
2836     ** does not work if either limit is negative.
2837     */
2838     if( pSub->pLimit ){
2839       pParent->pLimit = pSub->pLimit;
2840       pSub->pLimit = 0;
2841     }
2842   }
2843 
2844   /* Finially, delete what is left of the subquery and return
2845   ** success.
2846   */
2847   sqlite3SelectDelete(db, pSub1);
2848 
2849   return 1;
2850 }
2851 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
2852 
2853 /*
2854 ** Analyze the SELECT statement passed as an argument to see if it
2855 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
2856 ** it is, or 0 otherwise. At present, a query is considered to be
2857 ** a min()/max() query if:
2858 **
2859 **   1. There is a single object in the FROM clause.
2860 **
2861 **   2. There is a single expression in the result set, and it is
2862 **      either min(x) or max(x), where x is a column reference.
2863 */
2864 static int minMaxQuery(Parse *pParse, Select *p){
2865   Expr *pExpr;
2866   ExprList *pEList = p->pEList;
2867 
2868   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
2869   pExpr = pEList->a[0].pExpr;
2870   pEList = pExpr->pList;
2871   if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0;
2872   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
2873   if( pExpr->token.n!=3 ) return WHERE_ORDERBY_NORMAL;
2874   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
2875     return WHERE_ORDERBY_MIN;
2876   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
2877     return WHERE_ORDERBY_MAX;
2878   }
2879   return WHERE_ORDERBY_NORMAL;
2880 }
2881 
2882 /*
2883 ** This routine is a Walker callback for "expanding" a SELECT statement.
2884 ** "Expanding" means to do the following:
2885 **
2886 **    (1)  Make sure VDBE cursor numbers have been assigned to every
2887 **         element of the FROM clause.
2888 **
2889 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
2890 **         defines FROM clause.  When views appear in the FROM clause,
2891 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
2892 **         that implements the view.  A copy is made of the view's SELECT
2893 **         statement so that we can freely modify or delete that statement
2894 **         without worrying about messing up the presistent representation
2895 **         of the view.
2896 **
2897 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
2898 **         on joins and the ON and USING clause of joins.
2899 **
2900 **    (4)  Scan the list of columns in the result set (pEList) looking
2901 **         for instances of the "*" operator or the TABLE.* operator.
2902 **         If found, expand each "*" to be every column in every table
2903 **         and TABLE.* to be every column in TABLE.
2904 **
2905 */
2906 static int selectExpander(Walker *pWalker, Select *p){
2907   Parse *pParse = pWalker->pParse;
2908   int i, j, k;
2909   SrcList *pTabList;
2910   ExprList *pEList;
2911   struct SrcList_item *pFrom;
2912   sqlite3 *db = pParse->db;
2913 
2914   if( db->mallocFailed  ){
2915     return WRC_Abort;
2916   }
2917   if( p->pSrc==0 || (p->selFlags & SF_Expanded)!=0 ){
2918     return WRC_Prune;
2919   }
2920   p->selFlags |= SF_Expanded;
2921   pTabList = p->pSrc;
2922   pEList = p->pEList;
2923 
2924   /* Make sure cursor numbers have been assigned to all entries in
2925   ** the FROM clause of the SELECT statement.
2926   */
2927   sqlite3SrcListAssignCursors(pParse, pTabList);
2928 
2929   /* Look up every table named in the FROM clause of the select.  If
2930   ** an entry of the FROM clause is a subquery instead of a table or view,
2931   ** then create a transient table structure to describe the subquery.
2932   */
2933   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
2934     Table *pTab;
2935     if( pFrom->pTab!=0 ){
2936       /* This statement has already been prepared.  There is no need
2937       ** to go further. */
2938       assert( i==0 );
2939       return WRC_Prune;
2940     }
2941     if( pFrom->zName==0 ){
2942 #ifndef SQLITE_OMIT_SUBQUERY
2943       Select *pSel = pFrom->pSelect;
2944       /* A sub-query in the FROM clause of a SELECT */
2945       assert( pSel!=0 );
2946       assert( pFrom->pTab==0 );
2947       sqlite3WalkSelect(pWalker, pSel);
2948       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
2949       if( pTab==0 ) return WRC_Abort;
2950       pTab->db = db;
2951       pTab->nRef = 1;
2952       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
2953       while( pSel->pPrior ){ pSel = pSel->pPrior; }
2954       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
2955       pTab->iPKey = -1;
2956       pTab->tabFlags |= TF_Ephemeral;
2957 #endif
2958     }else{
2959       /* An ordinary table or view name in the FROM clause */
2960       assert( pFrom->pTab==0 );
2961       pFrom->pTab = pTab =
2962         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
2963       if( pTab==0 ) return WRC_Abort;
2964       pTab->nRef++;
2965 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
2966       if( pTab->pSelect || IsVirtual(pTab) ){
2967         /* We reach here if the named table is a really a view */
2968         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
2969 
2970         /* If pFrom->pSelect!=0 it means we are dealing with a
2971         ** view within a view.  The SELECT structure has already been
2972         ** copied by the outer view so we can skip the copy step here
2973         ** in the inner view.
2974         */
2975         if( pFrom->pSelect==0 ){
2976           pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
2977           sqlite3WalkSelect(pWalker, pFrom->pSelect);
2978         }
2979       }
2980 #endif
2981     }
2982   }
2983 
2984   /* Process NATURAL keywords, and ON and USING clauses of joins.
2985   */
2986   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
2987     return WRC_Abort;
2988   }
2989 
2990   /* For every "*" that occurs in the column list, insert the names of
2991   ** all columns in all tables.  And for every TABLE.* insert the names
2992   ** of all columns in TABLE.  The parser inserted a special expression
2993   ** with the TK_ALL operator for each "*" that it found in the column list.
2994   ** The following code just has to locate the TK_ALL expressions and expand
2995   ** each one to the list of all columns in all tables.
2996   **
2997   ** The first loop just checks to see if there are any "*" operators
2998   ** that need expanding.
2999   */
3000   for(k=0; k<pEList->nExpr; k++){
3001     Expr *pE = pEList->a[k].pExpr;
3002     if( pE->op==TK_ALL ) break;
3003     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
3004          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
3005   }
3006   if( k<pEList->nExpr ){
3007     /*
3008     ** If we get here it means the result set contains one or more "*"
3009     ** operators that need to be expanded.  Loop through each expression
3010     ** in the result set and expand them one by one.
3011     */
3012     struct ExprList_item *a = pEList->a;
3013     ExprList *pNew = 0;
3014     int flags = pParse->db->flags;
3015     int longNames = (flags & SQLITE_FullColNames)!=0
3016                       && (flags & SQLITE_ShortColNames)==0;
3017 
3018     for(k=0; k<pEList->nExpr; k++){
3019       Expr *pE = a[k].pExpr;
3020       if( pE->op!=TK_ALL &&
3021            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
3022         /* This particular expression does not need to be expanded.
3023         */
3024         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
3025         if( pNew ){
3026           pNew->a[pNew->nExpr-1].zName = a[k].zName;
3027         }
3028         a[k].pExpr = 0;
3029         a[k].zName = 0;
3030       }else{
3031         /* This expression is a "*" or a "TABLE.*" and needs to be
3032         ** expanded. */
3033         int tableSeen = 0;      /* Set to 1 when TABLE matches */
3034         char *zTName;            /* text of name of TABLE */
3035         if( pE->op==TK_DOT && pE->pLeft ){
3036           zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
3037         }else{
3038           zTName = 0;
3039         }
3040         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
3041           Table *pTab = pFrom->pTab;
3042           char *zTabName = pFrom->zAlias;
3043           if( zTabName==0 || zTabName[0]==0 ){
3044             zTabName = pTab->zName;
3045           }
3046           if( db->mallocFailed ) break;
3047           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
3048             continue;
3049           }
3050           tableSeen = 1;
3051           for(j=0; j<pTab->nCol; j++){
3052             Expr *pExpr, *pRight;
3053             char *zName = pTab->aCol[j].zName;
3054 
3055             /* If a column is marked as 'hidden' (currently only possible
3056             ** for virtual tables), do not include it in the expanded
3057             ** result-set list.
3058             */
3059             if( IsHiddenColumn(&pTab->aCol[j]) ){
3060               assert(IsVirtual(pTab));
3061               continue;
3062             }
3063 
3064             if( i>0 ){
3065               struct SrcList_item *pLeft = &pTabList->a[i-1];
3066               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
3067                         columnIndex(pLeft->pTab, zName)>=0 ){
3068                 /* In a NATURAL join, omit the join columns from the
3069                 ** table on the right */
3070                 continue;
3071               }
3072               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
3073                 /* In a join with a USING clause, omit columns in the
3074                 ** using clause from the table on the right. */
3075                 continue;
3076               }
3077             }
3078             pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
3079             if( pRight==0 ) break;
3080             setQuotedToken(pParse, &pRight->token, zName);
3081             if( longNames || pTabList->nSrc>1 ){
3082               Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
3083               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
3084               if( pExpr==0 ) break;
3085               setQuotedToken(pParse, &pLeft->token, zTabName);
3086               setToken(&pExpr->span,
3087                   sqlite3MPrintf(db, "%s.%s", zTabName, zName));
3088               pExpr->span.dyn = 1;
3089               pExpr->token.z = 0;
3090               pExpr->token.n = 0;
3091               pExpr->token.dyn = 0;
3092             }else{
3093               pExpr = pRight;
3094               pExpr->span = pExpr->token;
3095               pExpr->span.dyn = 0;
3096             }
3097             if( longNames ){
3098               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
3099             }else{
3100               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
3101             }
3102           }
3103         }
3104         if( !tableSeen ){
3105           if( zTName ){
3106             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
3107           }else{
3108             sqlite3ErrorMsg(pParse, "no tables specified");
3109           }
3110         }
3111         sqlite3DbFree(db, zTName);
3112       }
3113     }
3114     sqlite3ExprListDelete(db, pEList);
3115     p->pEList = pNew;
3116   }
3117 #if SQLITE_MAX_COLUMN
3118   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
3119     sqlite3ErrorMsg(pParse, "too many columns in result set");
3120   }
3121 #endif
3122   return WRC_Continue;
3123 }
3124 
3125 /*
3126 ** No-op routine for the parse-tree walker.
3127 **
3128 ** When this routine is the Walker.xExprCallback then expression trees
3129 ** are walked without any actions being taken at each node.  Presumably,
3130 ** when this routine is used for Walker.xExprCallback then
3131 ** Walker.xSelectCallback is set to do something useful for every
3132 ** subquery in the parser tree.
3133 */
3134 static int exprWalkNoop(Walker *pWalker, Expr *pExpr){
3135   return WRC_Continue;
3136 }
3137 
3138 /*
3139 ** This routine "expands" a SELECT statement and all of its subqueries.
3140 ** For additional information on what it means to "expand" a SELECT
3141 ** statement, see the comment on the selectExpand worker callback above.
3142 **
3143 ** Expanding a SELECT statement is the first step in processing a
3144 ** SELECT statement.  The SELECT statement must be expanded before
3145 ** name resolution is performed.
3146 **
3147 ** If anything goes wrong, an error message is written into pParse.
3148 ** The calling function can detect the problem by looking at pParse->nErr
3149 ** and/or pParse->db->mallocFailed.
3150 */
3151 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
3152   Walker w;
3153   w.xSelectCallback = selectExpander;
3154   w.xExprCallback = exprWalkNoop;
3155   w.pParse = pParse;
3156   sqlite3WalkSelect(&w, pSelect);
3157 }
3158 
3159 
3160 #ifndef SQLITE_OMIT_SUBQUERY
3161 /*
3162 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
3163 ** interface.
3164 **
3165 ** For each FROM-clause subquery, add Column.zType and Column.zColl
3166 ** information to the Table structure that represents the result set
3167 ** of that subquery.
3168 **
3169 ** The Table structure that represents the result set was constructed
3170 ** by selectExpander() but the type and collation information was omitted
3171 ** at that point because identifiers had not yet been resolved.  This
3172 ** routine is called after identifier resolution.
3173 */
3174 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
3175   Parse *pParse;
3176   int i;
3177   SrcList *pTabList;
3178   struct SrcList_item *pFrom;
3179 
3180   assert( p->selFlags & SF_Resolved );
3181   if( (p->selFlags & SF_HasTypeInfo)==0 ){
3182     p->selFlags |= SF_HasTypeInfo;
3183     pParse = pWalker->pParse;
3184     pTabList = p->pSrc;
3185     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
3186       Table *pTab = pFrom->pTab;
3187       if( pTab && (pTab->tabFlags & TF_Ephemeral)!=0 ){
3188         /* A sub-query in the FROM clause of a SELECT */
3189         Select *pSel = pFrom->pSelect;
3190         assert( pSel );
3191         while( pSel->pPrior ) pSel = pSel->pPrior;
3192         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
3193       }
3194     }
3195   }
3196   return WRC_Continue;
3197 }
3198 #endif
3199 
3200 
3201 /*
3202 ** This routine adds datatype and collating sequence information to
3203 ** the Table structures of all FROM-clause subqueries in a
3204 ** SELECT statement.
3205 **
3206 ** Use this routine after name resolution.
3207 */
3208 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
3209 #ifndef SQLITE_OMIT_SUBQUERY
3210   Walker w;
3211   w.xSelectCallback = selectAddSubqueryTypeInfo;
3212   w.xExprCallback = exprWalkNoop;
3213   w.pParse = pParse;
3214   sqlite3WalkSelect(&w, pSelect);
3215 #endif
3216 }
3217 
3218 
3219 /*
3220 ** This routine sets of a SELECT statement for processing.  The
3221 ** following is accomplished:
3222 **
3223 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
3224 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
3225 **     *  ON and USING clauses are shifted into WHERE statements
3226 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
3227 **     *  Identifiers in expression are matched to tables.
3228 **
3229 ** This routine acts recursively on all subqueries within the SELECT.
3230 */
3231 void sqlite3SelectPrep(
3232   Parse *pParse,         /* The parser context */
3233   Select *p,             /* The SELECT statement being coded. */
3234   NameContext *pOuterNC  /* Name context for container */
3235 ){
3236   sqlite3 *db;
3237   if( p==0 ) return;
3238   db = pParse->db;
3239   if( p->selFlags & SF_HasTypeInfo ) return;
3240   if( pParse->nErr || db->mallocFailed ) return;
3241   sqlite3SelectExpand(pParse, p);
3242   if( pParse->nErr || db->mallocFailed ) return;
3243   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
3244   if( pParse->nErr || db->mallocFailed ) return;
3245   sqlite3SelectAddTypeInfo(pParse, p);
3246 }
3247 
3248 /*
3249 ** Reset the aggregate accumulator.
3250 **
3251 ** The aggregate accumulator is a set of memory cells that hold
3252 ** intermediate results while calculating an aggregate.  This
3253 ** routine simply stores NULLs in all of those memory cells.
3254 */
3255 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
3256   Vdbe *v = pParse->pVdbe;
3257   int i;
3258   struct AggInfo_func *pFunc;
3259   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
3260     return;
3261   }
3262   for(i=0; i<pAggInfo->nColumn; i++){
3263     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
3264   }
3265   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
3266     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
3267     if( pFunc->iDistinct>=0 ){
3268       Expr *pE = pFunc->pExpr;
3269       if( pE->pList==0 || pE->pList->nExpr!=1 ){
3270         sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
3271            "by an expression");
3272         pFunc->iDistinct = -1;
3273       }else{
3274         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
3275         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
3276                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
3277       }
3278     }
3279   }
3280 }
3281 
3282 /*
3283 ** Invoke the OP_AggFinalize opcode for every aggregate function
3284 ** in the AggInfo structure.
3285 */
3286 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
3287   Vdbe *v = pParse->pVdbe;
3288   int i;
3289   struct AggInfo_func *pF;
3290   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
3291     ExprList *pList = pF->pExpr->pList;
3292     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
3293                       (void*)pF->pFunc, P4_FUNCDEF);
3294   }
3295 }
3296 
3297 /*
3298 ** Update the accumulator memory cells for an aggregate based on
3299 ** the current cursor position.
3300 */
3301 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
3302   Vdbe *v = pParse->pVdbe;
3303   int i;
3304   struct AggInfo_func *pF;
3305   struct AggInfo_col *pC;
3306 
3307   pAggInfo->directMode = 1;
3308   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
3309     int nArg;
3310     int addrNext = 0;
3311     int regAgg;
3312     ExprList *pList = pF->pExpr->pList;
3313     if( pList ){
3314       nArg = pList->nExpr;
3315       regAgg = sqlite3GetTempRange(pParse, nArg);
3316       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
3317     }else{
3318       nArg = 0;
3319       regAgg = 0;
3320     }
3321     if( pF->iDistinct>=0 ){
3322       addrNext = sqlite3VdbeMakeLabel(v);
3323       assert( nArg==1 );
3324       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
3325     }
3326     if( pF->pFunc->needCollSeq ){
3327       CollSeq *pColl = 0;
3328       struct ExprList_item *pItem;
3329       int j;
3330       assert( pList!=0 );  /* pList!=0 if pF->pFunc->needCollSeq is true */
3331       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
3332         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
3333       }
3334       if( !pColl ){
3335         pColl = pParse->db->pDfltColl;
3336       }
3337       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
3338     }
3339     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
3340                       (void*)pF->pFunc, P4_FUNCDEF);
3341     sqlite3VdbeChangeP5(v, nArg);
3342     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
3343     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
3344     if( addrNext ){
3345       sqlite3VdbeResolveLabel(v, addrNext);
3346     }
3347   }
3348   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
3349     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
3350   }
3351   pAggInfo->directMode = 0;
3352 }
3353 
3354 /*
3355 ** Generate code for the SELECT statement given in the p argument.
3356 **
3357 ** The results are distributed in various ways depending on the
3358 ** contents of the SelectDest structure pointed to by argument pDest
3359 ** as follows:
3360 **
3361 **     pDest->eDest    Result
3362 **     ------------    -------------------------------------------
3363 **     SRT_Output      Generate a row of output (using the OP_ResultRow
3364 **                     opcode) for each row in the result set.
3365 **
3366 **     SRT_Mem         Only valid if the result is a single column.
3367 **                     Store the first column of the first result row
3368 **                     in register pDest->iParm then abandon the rest
3369 **                     of the query.  This destination implies "LIMIT 1".
3370 **
3371 **     SRT_Set         The result must be a single column.  Store each
3372 **                     row of result as the key in table pDest->iParm.
3373 **                     Apply the affinity pDest->affinity before storing
3374 **                     results.  Used to implement "IN (SELECT ...)".
3375 **
3376 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
3377 **
3378 **     SRT_Except      Remove results from the temporary table pDest->iParm.
3379 **
3380 **     SRT_Table       Store results in temporary table pDest->iParm.
3381 **                     This is like SRT_EphemTab except that the table
3382 **                     is assumed to already be open.
3383 **
3384 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
3385 **                     the result there. The cursor is left open after
3386 **                     returning.  This is like SRT_Table except that
3387 **                     this destination uses OP_OpenEphemeral to create
3388 **                     the table first.
3389 **
3390 **     SRT_Coroutine   Generate a co-routine that returns a new row of
3391 **                     results each time it is invoked.  The entry point
3392 **                     of the co-routine is stored in register pDest->iParm.
3393 **
3394 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
3395 **                     set is not empty.
3396 **
3397 **     SRT_Discard     Throw the results away.  This is used by SELECT
3398 **                     statements within triggers whose only purpose is
3399 **                     the side-effects of functions.
3400 **
3401 ** This routine returns the number of errors.  If any errors are
3402 ** encountered, then an appropriate error message is left in
3403 ** pParse->zErrMsg.
3404 **
3405 ** This routine does NOT free the Select structure passed in.  The
3406 ** calling function needs to do that.
3407 */
3408 int sqlite3Select(
3409   Parse *pParse,         /* The parser context */
3410   Select *p,             /* The SELECT statement being coded. */
3411   SelectDest *pDest      /* What to do with the query results */
3412 ){
3413   int i, j;              /* Loop counters */
3414   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
3415   Vdbe *v;               /* The virtual machine under construction */
3416   int isAgg;             /* True for select lists like "count(*)" */
3417   ExprList *pEList;      /* List of columns to extract. */
3418   SrcList *pTabList;     /* List of tables to select from */
3419   Expr *pWhere;          /* The WHERE clause.  May be NULL */
3420   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
3421   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
3422   Expr *pHaving;         /* The HAVING clause.  May be NULL */
3423   int isDistinct;        /* True if the DISTINCT keyword is present */
3424   int distinct;          /* Table to use for the distinct set */
3425   int rc = 1;            /* Value to return from this function */
3426   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
3427   AggInfo sAggInfo;      /* Information used by aggregate queries */
3428   int iEnd;              /* Address of the end of the query */
3429   sqlite3 *db;           /* The database connection */
3430 
3431   db = pParse->db;
3432   if( p==0 || db->mallocFailed || pParse->nErr ){
3433     return 1;
3434   }
3435   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
3436   memset(&sAggInfo, 0, sizeof(sAggInfo));
3437 
3438   pOrderBy = p->pOrderBy;
3439   if( IgnorableOrderby(pDest) ){
3440     p->pOrderBy = 0;
3441 
3442     /* In these cases the DISTINCT operator makes no difference to the
3443     ** results, so remove it if it were specified.
3444     */
3445     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
3446            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
3447     p->selFlags &= ~SF_Distinct;
3448   }
3449   sqlite3SelectPrep(pParse, p, 0);
3450   if( pParse->nErr ){
3451     goto select_end;
3452   }
3453   p->pOrderBy = pOrderBy;
3454 
3455 
3456   /* Make local copies of the parameters for this query.
3457   */
3458   pTabList = p->pSrc;
3459   isAgg = (p->selFlags & SF_Aggregate)!=0;
3460   pEList = p->pEList;
3461   if( pEList==0 ) goto select_end;
3462 
3463   /*
3464   ** Do not even attempt to generate any code if we have already seen
3465   ** errors before this routine starts.
3466   */
3467   if( pParse->nErr>0 ) goto select_end;
3468 
3469   /* ORDER BY is ignored for some destinations.
3470   */
3471   if( IgnorableOrderby(pDest) ){
3472     pOrderBy = 0;
3473   }
3474 
3475   /* Begin generating code.
3476   */
3477   v = sqlite3GetVdbe(pParse);
3478   if( v==0 ) goto select_end;
3479 
3480   /* Generate code for all sub-queries in the FROM clause
3481   */
3482 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3483   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
3484     struct SrcList_item *pItem = &pTabList->a[i];
3485     SelectDest dest;
3486     Select *pSub = pItem->pSelect;
3487     int isAggSub;
3488 
3489     if( pSub==0 || pItem->isPopulated ) continue;
3490 
3491     /* Increment Parse.nHeight by the height of the largest expression
3492     ** tree refered to by this, the parent select. The child select
3493     ** may contain expression trees of at most
3494     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
3495     ** more conservative than necessary, but much easier than enforcing
3496     ** an exact limit.
3497     */
3498     pParse->nHeight += sqlite3SelectExprHeight(p);
3499 
3500     /* Check to see if the subquery can be absorbed into the parent. */
3501     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
3502     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
3503       if( isAggSub ){
3504         isAgg = 1;
3505         p->selFlags |= SF_Aggregate;
3506       }
3507       i = -1;
3508     }else{
3509       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
3510       assert( pItem->isPopulated==0 );
3511       sqlite3Select(pParse, pSub, &dest);
3512       pItem->isPopulated = 1;
3513     }
3514     if( pParse->nErr || db->mallocFailed ){
3515       goto select_end;
3516     }
3517     pParse->nHeight -= sqlite3SelectExprHeight(p);
3518     pTabList = p->pSrc;
3519     if( !IgnorableOrderby(pDest) ){
3520       pOrderBy = p->pOrderBy;
3521     }
3522   }
3523   pEList = p->pEList;
3524 #endif
3525   pWhere = p->pWhere;
3526   pGroupBy = p->pGroupBy;
3527   pHaving = p->pHaving;
3528   isDistinct = (p->selFlags & SF_Distinct)!=0;
3529 
3530 #ifndef SQLITE_OMIT_COMPOUND_SELECT
3531   /* If there is are a sequence of queries, do the earlier ones first.
3532   */
3533   if( p->pPrior ){
3534     if( p->pRightmost==0 ){
3535       Select *pLoop, *pRight = 0;
3536       int cnt = 0;
3537       int mxSelect;
3538       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
3539         pLoop->pRightmost = p;
3540         pLoop->pNext = pRight;
3541         pRight = pLoop;
3542       }
3543       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
3544       if( mxSelect && cnt>mxSelect ){
3545         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
3546         return 1;
3547       }
3548     }
3549     return multiSelect(pParse, p, pDest);
3550   }
3551 #endif
3552 
3553   /* If writing to memory or generating a set
3554   ** only a single column may be output.
3555   */
3556 #ifndef SQLITE_OMIT_SUBQUERY
3557   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
3558     goto select_end;
3559   }
3560 #endif
3561 
3562   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
3563   ** GROUP BY might use an index, DISTINCT never does.
3564   */
3565   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct && !p->pGroupBy ){
3566     p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
3567     pGroupBy = p->pGroupBy;
3568     p->selFlags &= ~SF_Distinct;
3569     isDistinct = 0;
3570   }
3571 
3572   /* If there is an ORDER BY clause, then this sorting
3573   ** index might end up being unused if the data can be
3574   ** extracted in pre-sorted order.  If that is the case, then the
3575   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
3576   ** we figure out that the sorting index is not needed.  The addrSortIndex
3577   ** variable is used to facilitate that change.
3578   */
3579   if( pOrderBy ){
3580     KeyInfo *pKeyInfo;
3581     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
3582     pOrderBy->iECursor = pParse->nTab++;
3583     p->addrOpenEphm[2] = addrSortIndex =
3584       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
3585                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
3586                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
3587   }else{
3588     addrSortIndex = -1;
3589   }
3590 
3591   /* If the output is destined for a temporary table, open that table.
3592   */
3593   if( pDest->eDest==SRT_EphemTab ){
3594     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
3595   }
3596 
3597   /* Set the limiter.
3598   */
3599   iEnd = sqlite3VdbeMakeLabel(v);
3600   computeLimitRegisters(pParse, p, iEnd);
3601 
3602   /* Open a virtual index to use for the distinct set.
3603   */
3604   if( isDistinct ){
3605     KeyInfo *pKeyInfo;
3606     assert( isAgg || pGroupBy );
3607     distinct = pParse->nTab++;
3608     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
3609     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
3610                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
3611   }else{
3612     distinct = -1;
3613   }
3614 
3615   /* Aggregate and non-aggregate queries are handled differently */
3616   if( !isAgg && pGroupBy==0 ){
3617     /* This case is for non-aggregate queries
3618     ** Begin the database scan
3619     */
3620     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
3621     if( pWInfo==0 ) goto select_end;
3622 
3623     /* If sorting index that was created by a prior OP_OpenEphemeral
3624     ** instruction ended up not being needed, then change the OP_OpenEphemeral
3625     ** into an OP_Noop.
3626     */
3627     if( addrSortIndex>=0 && pOrderBy==0 ){
3628       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
3629       p->addrOpenEphm[2] = -1;
3630     }
3631 
3632     /* Use the standard inner loop
3633     */
3634     assert(!isDistinct);
3635     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
3636                     pWInfo->iContinue, pWInfo->iBreak);
3637 
3638     /* End the database scan loop.
3639     */
3640     sqlite3WhereEnd(pWInfo);
3641   }else{
3642     /* This is the processing for aggregate queries */
3643     NameContext sNC;    /* Name context for processing aggregate information */
3644     int iAMem;          /* First Mem address for storing current GROUP BY */
3645     int iBMem;          /* First Mem address for previous GROUP BY */
3646     int iUseFlag;       /* Mem address holding flag indicating that at least
3647                         ** one row of the input to the aggregator has been
3648                         ** processed */
3649     int iAbortFlag;     /* Mem address which causes query abort if positive */
3650     int groupBySort;    /* Rows come from source in GROUP BY order */
3651 
3652 
3653     /* The following variables hold addresses or labels for parts of the
3654     ** virtual machine program we are putting together */
3655     int addrOutputRow;      /* Start of subroutine that outputs a result row */
3656     int regOutputRow;       /* Return address register for output subroutine */
3657     int addrSetAbort;       /* Set the abort flag and return */
3658     int addrInitializeLoop; /* Start of code that initializes the input loop */
3659     int addrTopOfLoop;      /* Top of the input loop */
3660     int addrEnd;            /* End of all processing */
3661     int addrSortingIdx;     /* The OP_OpenEphemeral for the sorting index */
3662     int addrReset;          /* Subroutine for resetting the accumulator */
3663     int regReset;           /* Return address register for reset subroutine */
3664 
3665     addrEnd = sqlite3VdbeMakeLabel(v);
3666 
3667     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
3668     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
3669     ** SELECT statement.
3670     */
3671     memset(&sNC, 0, sizeof(sNC));
3672     sNC.pParse = pParse;
3673     sNC.pSrcList = pTabList;
3674     sNC.pAggInfo = &sAggInfo;
3675     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
3676     sAggInfo.pGroupBy = pGroupBy;
3677     sqlite3ExprAnalyzeAggList(&sNC, pEList);
3678     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
3679     if( pHaving ){
3680       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
3681     }
3682     sAggInfo.nAccumulator = sAggInfo.nColumn;
3683     for(i=0; i<sAggInfo.nFunc; i++){
3684       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList);
3685     }
3686     if( db->mallocFailed ) goto select_end;
3687 
3688     /* Processing for aggregates with GROUP BY is very different and
3689     ** much more complex than aggregates without a GROUP BY.
3690     */
3691     if( pGroupBy ){
3692       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
3693       int j1;
3694 
3695       /* Create labels that we will be needing
3696       */
3697       addrInitializeLoop = sqlite3VdbeMakeLabel(v);
3698 
3699       /* If there is a GROUP BY clause we might need a sorting index to
3700       ** implement it.  Allocate that sorting index now.  If it turns out
3701       ** that we do not need it after all, the OpenEphemeral instruction
3702       ** will be converted into a Noop.
3703       */
3704       sAggInfo.sortingIdx = pParse->nTab++;
3705       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
3706       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
3707           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
3708           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
3709 
3710       /* Initialize memory locations used by GROUP BY aggregate processing
3711       */
3712       iUseFlag = ++pParse->nMem;
3713       iAbortFlag = ++pParse->nMem;
3714       iAMem = pParse->nMem + 1;
3715       pParse->nMem += pGroupBy->nExpr;
3716       iBMem = pParse->nMem + 1;
3717       pParse->nMem += pGroupBy->nExpr;
3718       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
3719       VdbeComment((v, "clear abort flag"));
3720       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
3721       VdbeComment((v, "indicate accumulator empty"));
3722       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrInitializeLoop);
3723 
3724       /* Generate a subroutine that outputs a single row of the result
3725       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
3726       ** is less than or equal to zero, the subroutine is a no-op.  If
3727       ** the processing calls for the query to abort, this subroutine
3728       ** increments the iAbortFlag memory location before returning in
3729       ** order to signal the caller to abort.
3730       */
3731       addrSetAbort = sqlite3VdbeCurrentAddr(v);
3732       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
3733       VdbeComment((v, "set abort flag"));
3734       regOutputRow = ++pParse->nMem;
3735       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
3736       addrOutputRow = sqlite3VdbeCurrentAddr(v);
3737       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
3738       VdbeComment((v, "Groupby result generator entry point"));
3739       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
3740       finalizeAggFunctions(pParse, &sAggInfo);
3741       if( pHaving ){
3742         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
3743       }
3744       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
3745                       distinct, pDest,
3746                       addrOutputRow+1, addrSetAbort);
3747       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
3748       VdbeComment((v, "end groupby result generator"));
3749 
3750       /* Generate a subroutine that will reset the group-by accumulator
3751       */
3752       addrReset = sqlite3VdbeCurrentAddr(v);
3753       regReset = ++pParse->nMem;
3754       resetAccumulator(pParse, &sAggInfo);
3755       sqlite3VdbeAddOp1(v, OP_Return, regReset);
3756 
3757       /* Begin a loop that will extract all source rows in GROUP BY order.
3758       ** This might involve two separate loops with an OP_Sort in between, or
3759       ** it might be a single loop that uses an index to extract information
3760       ** in the right order to begin with.
3761       */
3762       sqlite3VdbeResolveLabel(v, addrInitializeLoop);
3763       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
3764       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
3765       if( pWInfo==0 ) goto select_end;
3766       if( pGroupBy==0 ){
3767         /* The optimizer is able to deliver rows in group by order so
3768         ** we do not have to sort.  The OP_OpenEphemeral table will be
3769         ** cancelled later because we still need to use the pKeyInfo
3770         */
3771         pGroupBy = p->pGroupBy;
3772         groupBySort = 0;
3773       }else{
3774         /* Rows are coming out in undetermined order.  We have to push
3775         ** each row into a sorting index, terminate the first loop,
3776         ** then loop over the sorting index in order to get the output
3777         ** in sorted order
3778         */
3779         int regBase;
3780         int regRecord;
3781         int nCol;
3782         int nGroupBy;
3783 
3784         groupBySort = 1;
3785         nGroupBy = pGroupBy->nExpr;
3786         nCol = nGroupBy + 1;
3787         j = nGroupBy+1;
3788         for(i=0; i<sAggInfo.nColumn; i++){
3789           if( sAggInfo.aCol[i].iSorterColumn>=j ){
3790             nCol++;
3791             j++;
3792           }
3793         }
3794         regBase = sqlite3GetTempRange(pParse, nCol);
3795         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
3796         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
3797         j = nGroupBy+1;
3798         for(i=0; i<sAggInfo.nColumn; i++){
3799           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
3800           if( pCol->iSorterColumn>=j ){
3801             int r1 = j + regBase;
3802             int r2;
3803 
3804             r2 = sqlite3ExprCodeGetColumn(pParse,
3805                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
3806             if( r1!=r2 ){
3807               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
3808             }
3809             j++;
3810           }
3811         }
3812         regRecord = sqlite3GetTempReg(pParse);
3813         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
3814         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
3815         sqlite3ReleaseTempReg(pParse, regRecord);
3816         sqlite3ReleaseTempRange(pParse, regBase, nCol);
3817         sqlite3WhereEnd(pWInfo);
3818         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
3819         VdbeComment((v, "GROUP BY sort"));
3820         sAggInfo.useSortingIdx = 1;
3821       }
3822 
3823       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
3824       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
3825       ** Then compare the current GROUP BY terms against the GROUP BY terms
3826       ** from the previous row currently stored in a0, a1, a2...
3827       */
3828       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
3829       for(j=0; j<pGroupBy->nExpr; j++){
3830         if( groupBySort ){
3831           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
3832         }else{
3833           sAggInfo.directMode = 1;
3834           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
3835         }
3836       }
3837       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
3838                           (char*)pKeyInfo, P4_KEYINFO);
3839       j1 = sqlite3VdbeCurrentAddr(v);
3840       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
3841 
3842       /* Generate code that runs whenever the GROUP BY changes.
3843       ** Changes in the GROUP BY are detected by the previous code
3844       ** block.  If there were no changes, this block is skipped.
3845       **
3846       ** This code copies current group by terms in b0,b1,b2,...
3847       ** over to a0,a1,a2.  It then calls the output subroutine
3848       ** and resets the aggregate accumulator registers in preparation
3849       ** for the next GROUP BY batch.
3850       */
3851       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
3852       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
3853       VdbeComment((v, "output one row"));
3854       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
3855       VdbeComment((v, "check abort flag"));
3856       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
3857       VdbeComment((v, "reset accumulator"));
3858 
3859       /* Update the aggregate accumulators based on the content of
3860       ** the current row
3861       */
3862       sqlite3VdbeJumpHere(v, j1);
3863       updateAccumulator(pParse, &sAggInfo);
3864       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
3865       VdbeComment((v, "indicate data in accumulator"));
3866 
3867       /* End of the loop
3868       */
3869       if( groupBySort ){
3870         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
3871       }else{
3872         sqlite3WhereEnd(pWInfo);
3873         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
3874       }
3875 
3876       /* Output the final row of result
3877       */
3878       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
3879       VdbeComment((v, "output final row"));
3880 
3881     } /* endif pGroupBy */
3882     else {
3883       ExprList *pMinMax = 0;
3884       ExprList *pDel = 0;
3885       u8 flag;
3886 
3887       /* Check if the query is of one of the following forms:
3888       **
3889       **   SELECT min(x) FROM ...
3890       **   SELECT max(x) FROM ...
3891       **
3892       ** If it is, then ask the code in where.c to attempt to sort results
3893       ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
3894       ** If where.c is able to produce results sorted in this order, then
3895       ** add vdbe code to break out of the processing loop after the
3896       ** first iteration (since the first iteration of the loop is
3897       ** guaranteed to operate on the row with the minimum or maximum
3898       ** value of x, the only row required).
3899       **
3900       ** A special flag must be passed to sqlite3WhereBegin() to slightly
3901       ** modify behaviour as follows:
3902       **
3903       **   + If the query is a "SELECT min(x)", then the loop coded by
3904       **     where.c should not iterate over any values with a NULL value
3905       **     for x.
3906       **
3907       **   + The optimizer code in where.c (the thing that decides which
3908       **     index or indices to use) should place a different priority on
3909       **     satisfying the 'ORDER BY' clause than it does in other cases.
3910       **     Refer to code and comments in where.c for details.
3911       */
3912       flag = minMaxQuery(pParse, p);
3913       if( flag ){
3914         pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList);
3915         if( pMinMax && !db->mallocFailed ){
3916           pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN;
3917           pMinMax->a[0].pExpr->op = TK_COLUMN;
3918         }
3919       }
3920 
3921       /* This case runs if the aggregate has no GROUP BY clause.  The
3922       ** processing is much simpler since there is only a single row
3923       ** of output.
3924       */
3925       resetAccumulator(pParse, &sAggInfo);
3926       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
3927       if( pWInfo==0 ){
3928         sqlite3ExprListDelete(db, pDel);
3929         goto select_end;
3930       }
3931       updateAccumulator(pParse, &sAggInfo);
3932       if( !pMinMax && flag ){
3933         sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
3934         VdbeComment((v, "%s() by index",(flag==WHERE_ORDERBY_MIN?"min":"max")));
3935       }
3936       sqlite3WhereEnd(pWInfo);
3937       finalizeAggFunctions(pParse, &sAggInfo);
3938       pOrderBy = 0;
3939       if( pHaving ){
3940         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
3941       }
3942       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
3943                       pDest, addrEnd, addrEnd);
3944 
3945       sqlite3ExprListDelete(db, pDel);
3946     }
3947     sqlite3VdbeResolveLabel(v, addrEnd);
3948 
3949   } /* endif aggregate query */
3950 
3951   /* If there is an ORDER BY clause, then we need to sort the results
3952   ** and send them to the callback one by one.
3953   */
3954   if( pOrderBy ){
3955     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
3956   }
3957 
3958   /* Jump here to skip this query
3959   */
3960   sqlite3VdbeResolveLabel(v, iEnd);
3961 
3962   /* The SELECT was successfully coded.   Set the return code to 0
3963   ** to indicate no errors.
3964   */
3965   rc = 0;
3966 
3967   /* Control jumps to here if an error is encountered above, or upon
3968   ** successful coding of the SELECT.
3969   */
3970 select_end:
3971 
3972   /* Identify column names if results of the SELECT are to be output.
3973   */
3974   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
3975     generateColumnNames(pParse, pTabList, pEList);
3976   }
3977 
3978   sqlite3DbFree(db, sAggInfo.aCol);
3979   sqlite3DbFree(db, sAggInfo.aFunc);
3980   return rc;
3981 }
3982 
3983 #if defined(SQLITE_DEBUG)
3984 /*
3985 *******************************************************************************
3986 ** The following code is used for testing and debugging only.  The code
3987 ** that follows does not appear in normal builds.
3988 **
3989 ** These routines are used to print out the content of all or part of a
3990 ** parse structures such as Select or Expr.  Such printouts are useful
3991 ** for helping to understand what is happening inside the code generator
3992 ** during the execution of complex SELECT statements.
3993 **
3994 ** These routine are not called anywhere from within the normal
3995 ** code base.  Then are intended to be called from within the debugger
3996 ** or from temporary "printf" statements inserted for debugging.
3997 */
3998 void sqlite3PrintExpr(Expr *p){
3999   if( p->token.z && p->token.n>0 ){
4000     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
4001   }else{
4002     sqlite3DebugPrintf("(%d", p->op);
4003   }
4004   if( p->pLeft ){
4005     sqlite3DebugPrintf(" ");
4006     sqlite3PrintExpr(p->pLeft);
4007   }
4008   if( p->pRight ){
4009     sqlite3DebugPrintf(" ");
4010     sqlite3PrintExpr(p->pRight);
4011   }
4012   sqlite3DebugPrintf(")");
4013 }
4014 void sqlite3PrintExprList(ExprList *pList){
4015   int i;
4016   for(i=0; i<pList->nExpr; i++){
4017     sqlite3PrintExpr(pList->a[i].pExpr);
4018     if( i<pList->nExpr-1 ){
4019       sqlite3DebugPrintf(", ");
4020     }
4021   }
4022 }
4023 void sqlite3PrintSelect(Select *p, int indent){
4024   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
4025   sqlite3PrintExprList(p->pEList);
4026   sqlite3DebugPrintf("\n");
4027   if( p->pSrc ){
4028     char *zPrefix;
4029     int i;
4030     zPrefix = "FROM";
4031     for(i=0; i<p->pSrc->nSrc; i++){
4032       struct SrcList_item *pItem = &p->pSrc->a[i];
4033       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
4034       zPrefix = "";
4035       if( pItem->pSelect ){
4036         sqlite3DebugPrintf("(\n");
4037         sqlite3PrintSelect(pItem->pSelect, indent+10);
4038         sqlite3DebugPrintf("%*s)", indent+8, "");
4039       }else if( pItem->zName ){
4040         sqlite3DebugPrintf("%s", pItem->zName);
4041       }
4042       if( pItem->pTab ){
4043         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
4044       }
4045       if( pItem->zAlias ){
4046         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
4047       }
4048       if( i<p->pSrc->nSrc-1 ){
4049         sqlite3DebugPrintf(",");
4050       }
4051       sqlite3DebugPrintf("\n");
4052     }
4053   }
4054   if( p->pWhere ){
4055     sqlite3DebugPrintf("%*s WHERE ", indent, "");
4056     sqlite3PrintExpr(p->pWhere);
4057     sqlite3DebugPrintf("\n");
4058   }
4059   if( p->pGroupBy ){
4060     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
4061     sqlite3PrintExprList(p->pGroupBy);
4062     sqlite3DebugPrintf("\n");
4063   }
4064   if( p->pHaving ){
4065     sqlite3DebugPrintf("%*s HAVING ", indent, "");
4066     sqlite3PrintExpr(p->pHaving);
4067     sqlite3DebugPrintf("\n");
4068   }
4069   if( p->pOrderBy ){
4070     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
4071     sqlite3PrintExprList(p->pOrderBy);
4072     sqlite3DebugPrintf("\n");
4073   }
4074 }
4075 /* End of the structure debug printing code
4076 *****************************************************************************/
4077 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
4078