xref: /sqlite-3.40.0/src/select.c (revision ae80ddea)
1cce7d176Sdrh /*
2b19a2bc6Sdrh ** 2001 September 15
3cce7d176Sdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
6cce7d176Sdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
10cce7d176Sdrh **
11cce7d176Sdrh *************************************************************************
12cce7d176Sdrh ** This file contains C code routines that are called by the parser
13b19a2bc6Sdrh ** to handle SELECT statements in SQLite.
14cce7d176Sdrh */
15cce7d176Sdrh #include "sqliteInt.h"
16cce7d176Sdrh 
17315555caSdrh 
18cce7d176Sdrh /*
19eda639e1Sdrh ** Delete all the content of a Select structure but do not deallocate
20eda639e1Sdrh ** the select structure itself.
21eda639e1Sdrh */
22633e6d57Sdrh static void clearSelect(sqlite3 *db, Select *p){
23633e6d57Sdrh   sqlite3ExprListDelete(db, p->pEList);
24633e6d57Sdrh   sqlite3SrcListDelete(db, p->pSrc);
25633e6d57Sdrh   sqlite3ExprDelete(db, p->pWhere);
26633e6d57Sdrh   sqlite3ExprListDelete(db, p->pGroupBy);
27633e6d57Sdrh   sqlite3ExprDelete(db, p->pHaving);
28633e6d57Sdrh   sqlite3ExprListDelete(db, p->pOrderBy);
29633e6d57Sdrh   sqlite3SelectDelete(db, p->pPrior);
30633e6d57Sdrh   sqlite3ExprDelete(db, p->pLimit);
31633e6d57Sdrh   sqlite3ExprDelete(db, p->pOffset);
32eda639e1Sdrh }
33eda639e1Sdrh 
341013c932Sdrh /*
351013c932Sdrh ** Initialize a SelectDest structure.
361013c932Sdrh */
371013c932Sdrh void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
38ea678832Sdrh   pDest->eDest = (u8)eDest;
392b596da8Sdrh   pDest->iSDParm = iParm;
402b596da8Sdrh   pDest->affSdst = 0;
412b596da8Sdrh   pDest->iSdst = 0;
422b596da8Sdrh   pDest->nSdst = 0;
431013c932Sdrh }
441013c932Sdrh 
45eda639e1Sdrh 
46eda639e1Sdrh /*
479bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that
489bb61fe7Sdrh ** structure.
49cce7d176Sdrh */
504adee20fSdanielk1977 Select *sqlite3SelectNew(
5117435752Sdrh   Parse *pParse,        /* Parsing context */
52daffd0e5Sdrh   ExprList *pEList,     /* which columns to include in the result */
53ad3cab52Sdrh   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
54daffd0e5Sdrh   Expr *pWhere,         /* the WHERE clause */
55daffd0e5Sdrh   ExprList *pGroupBy,   /* the GROUP BY clause */
56daffd0e5Sdrh   Expr *pHaving,        /* the HAVING clause */
57daffd0e5Sdrh   ExprList *pOrderBy,   /* the ORDER BY clause */
589bbca4c1Sdrh   int isDistinct,       /* true if the DISTINCT keyword is present */
59a2dc3b1aSdanielk1977   Expr *pLimit,         /* LIMIT value.  NULL means not used */
60a2dc3b1aSdanielk1977   Expr *pOffset         /* OFFSET value.  NULL means no offset */
619bb61fe7Sdrh ){
629bb61fe7Sdrh   Select *pNew;
63eda639e1Sdrh   Select standin;
6417435752Sdrh   sqlite3 *db = pParse->db;
6517435752Sdrh   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
66d72a276eSdrh   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
67daffd0e5Sdrh   if( pNew==0 ){
68338ec3e1Sdrh     assert( db->mallocFailed );
69eda639e1Sdrh     pNew = &standin;
70eda639e1Sdrh     memset(pNew, 0, sizeof(*pNew));
71eda639e1Sdrh   }
72b733d037Sdrh   if( pEList==0 ){
73b7916a78Sdrh     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
74b733d037Sdrh   }
759bb61fe7Sdrh   pNew->pEList = pEList;
767b113babSdrh   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
779bb61fe7Sdrh   pNew->pSrc = pSrc;
789bb61fe7Sdrh   pNew->pWhere = pWhere;
799bb61fe7Sdrh   pNew->pGroupBy = pGroupBy;
809bb61fe7Sdrh   pNew->pHaving = pHaving;
819bb61fe7Sdrh   pNew->pOrderBy = pOrderBy;
827d10d5a6Sdrh   pNew->selFlags = isDistinct ? SF_Distinct : 0;
8382c3d636Sdrh   pNew->op = TK_SELECT;
84a2dc3b1aSdanielk1977   pNew->pLimit = pLimit;
85a2dc3b1aSdanielk1977   pNew->pOffset = pOffset;
86373cc2ddSdrh   assert( pOffset==0 || pLimit!=0 );
87b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
88b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
89b9bb7c18Sdrh   pNew->addrOpenEphm[2] = -1;
900a846f96Sdrh   if( db->mallocFailed ) {
91633e6d57Sdrh     clearSelect(db, pNew);
920a846f96Sdrh     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
93eda639e1Sdrh     pNew = 0;
94a464c234Sdrh   }else{
95a464c234Sdrh     assert( pNew->pSrc!=0 || pParse->nErr>0 );
96daffd0e5Sdrh   }
97338ec3e1Sdrh   assert( pNew!=&standin );
989bb61fe7Sdrh   return pNew;
999bb61fe7Sdrh }
1009bb61fe7Sdrh 
1019bb61fe7Sdrh /*
102eda639e1Sdrh ** Delete the given Select structure and all of its substructures.
103eda639e1Sdrh */
104633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){
105eda639e1Sdrh   if( p ){
106633e6d57Sdrh     clearSelect(db, p);
107633e6d57Sdrh     sqlite3DbFree(db, p);
108eda639e1Sdrh   }
109eda639e1Sdrh }
110eda639e1Sdrh 
111eda639e1Sdrh /*
11201f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
11301f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
11401f3f253Sdrh ** in terms of the following bit values:
11501f3f253Sdrh **
11601f3f253Sdrh **     JT_INNER
1173dec223cSdrh **     JT_CROSS
11801f3f253Sdrh **     JT_OUTER
11901f3f253Sdrh **     JT_NATURAL
12001f3f253Sdrh **     JT_LEFT
12101f3f253Sdrh **     JT_RIGHT
12201f3f253Sdrh **
12301f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
12401f3f253Sdrh **
12501f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
12601f3f253Sdrh ** a join type, but put an error in the pParse structure.
12701f3f253Sdrh */
1284adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
12901f3f253Sdrh   int jointype = 0;
13001f3f253Sdrh   Token *apAll[3];
13101f3f253Sdrh   Token *p;
132373cc2ddSdrh                              /*   0123456789 123456789 123456789 123 */
133373cc2ddSdrh   static const char zKeyText[] = "naturaleftouterightfullinnercross";
1345719628aSdrh   static const struct {
135373cc2ddSdrh     u8 i;        /* Beginning of keyword text in zKeyText[] */
136373cc2ddSdrh     u8 nChar;    /* Length of the keyword in characters */
137373cc2ddSdrh     u8 code;     /* Join type mask */
138373cc2ddSdrh   } aKeyword[] = {
139373cc2ddSdrh     /* natural */ { 0,  7, JT_NATURAL                },
140373cc2ddSdrh     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
141373cc2ddSdrh     /* outer   */ { 10, 5, JT_OUTER                  },
142373cc2ddSdrh     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
143373cc2ddSdrh     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
144373cc2ddSdrh     /* inner   */ { 23, 5, JT_INNER                  },
145373cc2ddSdrh     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
14601f3f253Sdrh   };
14701f3f253Sdrh   int i, j;
14801f3f253Sdrh   apAll[0] = pA;
14901f3f253Sdrh   apAll[1] = pB;
15001f3f253Sdrh   apAll[2] = pC;
151195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
15201f3f253Sdrh     p = apAll[i];
153373cc2ddSdrh     for(j=0; j<ArraySize(aKeyword); j++){
154373cc2ddSdrh       if( p->n==aKeyword[j].nChar
155373cc2ddSdrh           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
156373cc2ddSdrh         jointype |= aKeyword[j].code;
15701f3f253Sdrh         break;
15801f3f253Sdrh       }
15901f3f253Sdrh     }
160373cc2ddSdrh     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
161373cc2ddSdrh     if( j>=ArraySize(aKeyword) ){
16201f3f253Sdrh       jointype |= JT_ERROR;
16301f3f253Sdrh       break;
16401f3f253Sdrh     }
16501f3f253Sdrh   }
166ad2d8307Sdrh   if(
167ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
168195e6967Sdrh      (jointype & JT_ERROR)!=0
169ad2d8307Sdrh   ){
170a9671a22Sdrh     const char *zSp = " ";
171a9671a22Sdrh     assert( pB!=0 );
172a9671a22Sdrh     if( pC==0 ){ zSp++; }
173ae29ffbeSdrh     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
174a9671a22Sdrh        "%T %T%s%T", pA, pB, zSp, pC);
17501f3f253Sdrh     jointype = JT_INNER;
176373cc2ddSdrh   }else if( (jointype & JT_OUTER)!=0
177373cc2ddSdrh          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
1784adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
179da93d238Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported");
180195e6967Sdrh     jointype = JT_INNER;
18101f3f253Sdrh   }
18201f3f253Sdrh   return jointype;
18301f3f253Sdrh }
18401f3f253Sdrh 
18501f3f253Sdrh /*
186ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
187ad2d8307Sdrh ** is not contained in the table.
188ad2d8307Sdrh */
189ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
190ad2d8307Sdrh   int i;
191ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
1924adee20fSdanielk1977     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
193ad2d8307Sdrh   }
194ad2d8307Sdrh   return -1;
195ad2d8307Sdrh }
196ad2d8307Sdrh 
197ad2d8307Sdrh /*
1982179b434Sdrh ** Search the first N tables in pSrc, from left to right, looking for a
1992179b434Sdrh ** table that has a column named zCol.
2002179b434Sdrh **
2012179b434Sdrh ** When found, set *piTab and *piCol to the table index and column index
2022179b434Sdrh ** of the matching column and return TRUE.
2032179b434Sdrh **
2042179b434Sdrh ** If not found, return FALSE.
2052179b434Sdrh */
2062179b434Sdrh static int tableAndColumnIndex(
2072179b434Sdrh   SrcList *pSrc,       /* Array of tables to search */
2082179b434Sdrh   int N,               /* Number of tables in pSrc->a[] to search */
2092179b434Sdrh   const char *zCol,    /* Name of the column we are looking for */
2102179b434Sdrh   int *piTab,          /* Write index of pSrc->a[] here */
2112179b434Sdrh   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
2122179b434Sdrh ){
2132179b434Sdrh   int i;               /* For looping over tables in pSrc */
2142179b434Sdrh   int iCol;            /* Index of column matching zCol */
2152179b434Sdrh 
2162179b434Sdrh   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
2172179b434Sdrh   for(i=0; i<N; i++){
2182179b434Sdrh     iCol = columnIndex(pSrc->a[i].pTab, zCol);
2192179b434Sdrh     if( iCol>=0 ){
2202179b434Sdrh       if( piTab ){
2212179b434Sdrh         *piTab = i;
2222179b434Sdrh         *piCol = iCol;
2232179b434Sdrh       }
2242179b434Sdrh       return 1;
2252179b434Sdrh     }
2262179b434Sdrh   }
2272179b434Sdrh   return 0;
2282179b434Sdrh }
2292179b434Sdrh 
2302179b434Sdrh /*
231f7b0b0adSdan ** This function is used to add terms implied by JOIN syntax to the
232f7b0b0adSdan ** WHERE clause expression of a SELECT statement. The new term, which
233f7b0b0adSdan ** is ANDed with the existing WHERE clause, is of the form:
234f7b0b0adSdan **
235f7b0b0adSdan **    (tab1.col1 = tab2.col2)
236f7b0b0adSdan **
237f7b0b0adSdan ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
238f7b0b0adSdan ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
239f7b0b0adSdan ** column iColRight of tab2.
240ad2d8307Sdrh */
241ad2d8307Sdrh static void addWhereTerm(
24217435752Sdrh   Parse *pParse,                  /* Parsing context */
243f7b0b0adSdan   SrcList *pSrc,                  /* List of tables in FROM clause */
2442179b434Sdrh   int iLeft,                      /* Index of first table to join in pSrc */
245f7b0b0adSdan   int iColLeft,                   /* Index of column in first table */
2462179b434Sdrh   int iRight,                     /* Index of second table in pSrc */
247f7b0b0adSdan   int iColRight,                  /* Index of column in second table */
248f7b0b0adSdan   int isOuterJoin,                /* True if this is an OUTER join */
249f7b0b0adSdan   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
250ad2d8307Sdrh ){
251f7b0b0adSdan   sqlite3 *db = pParse->db;
252f7b0b0adSdan   Expr *pE1;
253f7b0b0adSdan   Expr *pE2;
254f7b0b0adSdan   Expr *pEq;
255ad2d8307Sdrh 
2562179b434Sdrh   assert( iLeft<iRight );
2572179b434Sdrh   assert( pSrc->nSrc>iRight );
2582179b434Sdrh   assert( pSrc->a[iLeft].pTab );
2592179b434Sdrh   assert( pSrc->a[iRight].pTab );
260f7b0b0adSdan 
2612179b434Sdrh   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
2622179b434Sdrh   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
263f7b0b0adSdan 
264f7b0b0adSdan   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
265f7b0b0adSdan   if( pEq && isOuterJoin ){
266f7b0b0adSdan     ExprSetProperty(pEq, EP_FromJoin);
267f7b0b0adSdan     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
268f7b0b0adSdan     ExprSetIrreducible(pEq);
269f7b0b0adSdan     pEq->iRightJoinTable = (i16)pE2->iTable;
270030530deSdrh   }
271f7b0b0adSdan   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
272ad2d8307Sdrh }
273ad2d8307Sdrh 
274ad2d8307Sdrh /*
2751f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
27622d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the
27722d6a53aSdrh ** expression.
2781cc093c2Sdrh **
279e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
2801cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
2811f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
2821f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
2831f16230bSdrh ** WHERE clause during join processing but we need to remember that they
2841f16230bSdrh ** originated in the ON or USING clause.
28522d6a53aSdrh **
28622d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the
28722d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not
28822d6a53aSdrh ** explicitly mentioned in the expression.  That information is needed
28922d6a53aSdrh ** for cases like this:
29022d6a53aSdrh **
29122d6a53aSdrh **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
29222d6a53aSdrh **
29322d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5
29422d6a53aSdrh ** term until after the t2 loop of the join.  In that way, a
29522d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
29622d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately
29722d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in
29822d6a53aSdrh ** the output, which is incorrect.
2991cc093c2Sdrh */
30022d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){
3011cc093c2Sdrh   while( p ){
3021f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
30333e619fcSdrh     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
30433e619fcSdrh     ExprSetIrreducible(p);
305cf697396Sshane     p->iRightJoinTable = (i16)iTable;
30622d6a53aSdrh     setJoinExpr(p->pLeft, iTable);
3071cc093c2Sdrh     p = p->pRight;
3081cc093c2Sdrh   }
3091cc093c2Sdrh }
3101cc093c2Sdrh 
3111cc093c2Sdrh /*
312ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
313ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
314ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
315ad2d8307Sdrh **
31691bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure.
31791bb0eedSdrh ** The left most table is the first entry in Select.pSrc.  The right-most
31891bb0eedSdrh ** table is the last entry.  The join operator is held in the entry to
31991bb0eedSdrh ** the left.  Thus entry 0 contains the join operator for the join between
32091bb0eedSdrh ** entries 0 and 1.  Any ON or USING clauses associated with the join are
32191bb0eedSdrh ** also attached to the left entry.
32291bb0eedSdrh **
323ad2d8307Sdrh ** This routine returns the number of errors encountered.
324ad2d8307Sdrh */
325ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
32691bb0eedSdrh   SrcList *pSrc;                  /* All tables in the FROM clause */
32791bb0eedSdrh   int i, j;                       /* Loop counters */
32891bb0eedSdrh   struct SrcList_item *pLeft;     /* Left table being joined */
32991bb0eedSdrh   struct SrcList_item *pRight;    /* Right table being joined */
330ad2d8307Sdrh 
33191bb0eedSdrh   pSrc = p->pSrc;
33291bb0eedSdrh   pLeft = &pSrc->a[0];
33391bb0eedSdrh   pRight = &pLeft[1];
33491bb0eedSdrh   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
33591bb0eedSdrh     Table *pLeftTab = pLeft->pTab;
33691bb0eedSdrh     Table *pRightTab = pRight->pTab;
337ad27e761Sdrh     int isOuter;
33891bb0eedSdrh 
3391c767f0dSdrh     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
340ad27e761Sdrh     isOuter = (pRight->jointype & JT_OUTER)!=0;
341ad2d8307Sdrh 
342ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
343ad2d8307Sdrh     ** every column that the two tables have in common.
344ad2d8307Sdrh     */
34561dfc31dSdrh     if( pRight->jointype & JT_NATURAL ){
34661dfc31dSdrh       if( pRight->pOn || pRight->pUsing ){
3474adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
348ad2d8307Sdrh            "an ON or USING clause", 0);
349ad2d8307Sdrh         return 1;
350ad2d8307Sdrh       }
3512179b434Sdrh       for(j=0; j<pRightTab->nCol; j++){
3522179b434Sdrh         char *zName;   /* Name of column in the right table */
3532179b434Sdrh         int iLeft;     /* Matching left table */
3542179b434Sdrh         int iLeftCol;  /* Matching column in the left table */
3552179b434Sdrh 
3562179b434Sdrh         zName = pRightTab->aCol[j].zName;
3572179b434Sdrh         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
3582179b434Sdrh           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
3592179b434Sdrh                        isOuter, &p->pWhere);
360ad2d8307Sdrh         }
361ad2d8307Sdrh       }
362ad2d8307Sdrh     }
363ad2d8307Sdrh 
364ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
365ad2d8307Sdrh     */
36661dfc31dSdrh     if( pRight->pOn && pRight->pUsing ){
3674adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
368da93d238Sdrh         "clauses in the same join");
369ad2d8307Sdrh       return 1;
370ad2d8307Sdrh     }
371ad2d8307Sdrh 
372ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
37391bb0eedSdrh     ** an AND operator.
374ad2d8307Sdrh     */
37561dfc31dSdrh     if( pRight->pOn ){
376ad27e761Sdrh       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
37717435752Sdrh       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
37861dfc31dSdrh       pRight->pOn = 0;
379ad2d8307Sdrh     }
380ad2d8307Sdrh 
381ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
382ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
383ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
384ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
385ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
386ad2d8307Sdrh     ** not contained in both tables to be joined.
387ad2d8307Sdrh     */
38861dfc31dSdrh     if( pRight->pUsing ){
38961dfc31dSdrh       IdList *pList = pRight->pUsing;
390ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
3912179b434Sdrh         char *zName;     /* Name of the term in the USING clause */
3922179b434Sdrh         int iLeft;       /* Table on the left with matching column name */
3932179b434Sdrh         int iLeftCol;    /* Column number of matching column on the left */
3942179b434Sdrh         int iRightCol;   /* Column number of matching column on the right */
3952179b434Sdrh 
3962179b434Sdrh         zName = pList->a[j].zName;
3972179b434Sdrh         iRightCol = columnIndex(pRightTab, zName);
3982179b434Sdrh         if( iRightCol<0
3992179b434Sdrh          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
4002179b434Sdrh         ){
4014adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
40291bb0eedSdrh             "not present in both tables", zName);
403ad2d8307Sdrh           return 1;
404ad2d8307Sdrh         }
4052179b434Sdrh         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
4062179b434Sdrh                      isOuter, &p->pWhere);
407ad2d8307Sdrh       }
408ad2d8307Sdrh     }
409ad2d8307Sdrh   }
410ad2d8307Sdrh   return 0;
411ad2d8307Sdrh }
412ad2d8307Sdrh 
413ad2d8307Sdrh /*
414c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
415c926afbcSdrh ** stack into the sorter.
416c926afbcSdrh */
417d59ba6ceSdrh static void pushOntoSorter(
418d59ba6ceSdrh   Parse *pParse,         /* Parser context */
419d59ba6ceSdrh   ExprList *pOrderBy,    /* The ORDER BY clause */
420b7654111Sdrh   Select *pSelect,       /* The whole SELECT statement */
421b7654111Sdrh   int regData            /* Register holding data to be sorted */
422d59ba6ceSdrh ){
423d59ba6ceSdrh   Vdbe *v = pParse->pVdbe;
424892d3179Sdrh   int nExpr = pOrderBy->nExpr;
425892d3179Sdrh   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
426892d3179Sdrh   int regRecord = sqlite3GetTempReg(pParse);
427c6aff30cSdrh   int op;
428ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
429191b54cbSdrh   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
430892d3179Sdrh   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
431b21e7c70Sdrh   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
4321db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
433c6aff30cSdrh   if( pSelect->selFlags & SF_UseSorter ){
434c6aff30cSdrh     op = OP_SorterInsert;
435c6aff30cSdrh   }else{
436c6aff30cSdrh     op = OP_IdxInsert;
437c6aff30cSdrh   }
438c6aff30cSdrh   sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
439892d3179Sdrh   sqlite3ReleaseTempReg(pParse, regRecord);
440892d3179Sdrh   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
44192b01d53Sdrh   if( pSelect->iLimit ){
44215007a99Sdrh     int addr1, addr2;
443b7654111Sdrh     int iLimit;
4440acb7e48Sdrh     if( pSelect->iOffset ){
445b7654111Sdrh       iLimit = pSelect->iOffset+1;
446b7654111Sdrh     }else{
447b7654111Sdrh       iLimit = pSelect->iLimit;
448b7654111Sdrh     }
449b7654111Sdrh     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
450b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
4513c84ddffSdrh     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
452d59ba6ceSdrh     sqlite3VdbeJumpHere(v, addr1);
4533c84ddffSdrh     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
4543c84ddffSdrh     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
45515007a99Sdrh     sqlite3VdbeJumpHere(v, addr2);
456d59ba6ceSdrh   }
457c926afbcSdrh }
458c926afbcSdrh 
459c926afbcSdrh /*
460ec7429aeSdrh ** Add code to implement the OFFSET
461ea48eb2eSdrh */
462ec7429aeSdrh static void codeOffset(
463bab39e13Sdrh   Vdbe *v,          /* Generate code into this VM */
464ea48eb2eSdrh   Select *p,        /* The SELECT statement being coded */
465b7654111Sdrh   int iContinue     /* Jump here to skip the current record */
466ea48eb2eSdrh ){
46792b01d53Sdrh   if( p->iOffset && iContinue!=0 ){
46815007a99Sdrh     int addr;
4698558cde1Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
4703c84ddffSdrh     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
47166a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
472d4e70ebdSdrh     VdbeComment((v, "skip OFFSET records"));
47315007a99Sdrh     sqlite3VdbeJumpHere(v, addr);
474ea48eb2eSdrh   }
475ea48eb2eSdrh }
476ea48eb2eSdrh 
477ea48eb2eSdrh /*
47898757157Sdrh ** Add code that will check to make sure the N registers starting at iMem
47998757157Sdrh ** form a distinct entry.  iTab is a sorting index that holds previously
480a2a49dc9Sdrh ** seen combinations of the N values.  A new entry is made in iTab
481a2a49dc9Sdrh ** if the current N values are new.
482a2a49dc9Sdrh **
483a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the
484a2a49dc9Sdrh ** stack if the top N elements are not distinct.
485a2a49dc9Sdrh */
486a2a49dc9Sdrh static void codeDistinct(
4872dcef11bSdrh   Parse *pParse,     /* Parsing and code generating context */
488a2a49dc9Sdrh   int iTab,          /* A sorting index used to test for distinctness */
489a2a49dc9Sdrh   int addrRepeat,    /* Jump to here if not distinct */
490477df4b3Sdrh   int N,             /* Number of elements */
491a2a49dc9Sdrh   int iMem           /* First element */
492a2a49dc9Sdrh ){
4932dcef11bSdrh   Vdbe *v;
4942dcef11bSdrh   int r1;
4952dcef11bSdrh 
4962dcef11bSdrh   v = pParse->pVdbe;
4972dcef11bSdrh   r1 = sqlite3GetTempReg(pParse);
49891fc4a0cSdrh   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
4991db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
5002dcef11bSdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
5012dcef11bSdrh   sqlite3ReleaseTempReg(pParse, r1);
502a2a49dc9Sdrh }
503a2a49dc9Sdrh 
504bb7dd683Sdrh #ifndef SQLITE_OMIT_SUBQUERY
505a2a49dc9Sdrh /*
506e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression
507e305f43fSdrh ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
508bb7dd683Sdrh ** column.  We do this in a subroutine because the error used to occur
509bb7dd683Sdrh ** in multiple places.  (The error only occurs in one place now, but we
510bb7dd683Sdrh ** retain the subroutine to minimize code disruption.)
511e305f43fSdrh */
5126c8c8ce0Sdanielk1977 static int checkForMultiColumnSelectError(
5136c8c8ce0Sdanielk1977   Parse *pParse,       /* Parse context. */
5146c8c8ce0Sdanielk1977   SelectDest *pDest,   /* Destination of SELECT results */
5156c8c8ce0Sdanielk1977   int nExpr            /* Number of result columns returned by SELECT */
5166c8c8ce0Sdanielk1977 ){
5176c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
518e305f43fSdrh   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
519e305f43fSdrh     sqlite3ErrorMsg(pParse, "only a single result allowed for "
520e305f43fSdrh        "a SELECT that is part of an expression");
521e305f43fSdrh     return 1;
522e305f43fSdrh   }else{
523e305f43fSdrh     return 0;
524e305f43fSdrh   }
525e305f43fSdrh }
526bb7dd683Sdrh #endif
527c99130fdSdrh 
528c99130fdSdrh /*
529e8e4af76Sdrh ** An instance of the following object is used to record information about
530e8e4af76Sdrh ** how to process the DISTINCT keyword, to simplify passing that information
531e8e4af76Sdrh ** into the selectInnerLoop() routine.
532e8e4af76Sdrh */
533e8e4af76Sdrh typedef struct DistinctCtx DistinctCtx;
534e8e4af76Sdrh struct DistinctCtx {
535e8e4af76Sdrh   u8 isTnct;      /* True if the DISTINCT keyword is present */
536e8e4af76Sdrh   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
537e8e4af76Sdrh   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
538e8e4af76Sdrh   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
539e8e4af76Sdrh };
540e8e4af76Sdrh 
541e8e4af76Sdrh /*
5422282792aSdrh ** This routine generates the code for the inside of the inner loop
5432282792aSdrh ** of a SELECT.
54482c3d636Sdrh **
54538640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
54638640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
54738640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
54838640e15Sdrh ** datatypes for each column.
5492282792aSdrh */
550d2b3e23bSdrh static void selectInnerLoop(
5512282792aSdrh   Parse *pParse,          /* The parser context */
552df199a25Sdrh   Select *p,              /* The complete select statement being coded */
5532282792aSdrh   ExprList *pEList,       /* List of values being extracted */
55482c3d636Sdrh   int srcTab,             /* Pull data from this table */
555967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
5562282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
557e8e4af76Sdrh   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
5586c8c8ce0Sdanielk1977   SelectDest *pDest,      /* How to dispose of the results */
5592282792aSdrh   int iContinue,          /* Jump here to continue with next row */
560a9671a22Sdrh   int iBreak              /* Jump here to break out of the inner loop */
5612282792aSdrh ){
5622282792aSdrh   Vdbe *v = pParse->pVdbe;
563d847eaadSdrh   int i;
564ea48eb2eSdrh   int hasDistinct;        /* True if the DISTINCT keyword is present */
565d847eaadSdrh   int regResult;              /* Start of memory holding result set */
566d847eaadSdrh   int eDest = pDest->eDest;   /* How to dispose of results */
5672b596da8Sdrh   int iParm = pDest->iSDParm; /* First argument to disposal method */
568d847eaadSdrh   int nResultCol;             /* Number of result columns */
56938640e15Sdrh 
5701c767f0dSdrh   assert( v );
5711c767f0dSdrh   if( NEVER(v==0) ) return;
57238640e15Sdrh   assert( pEList!=0 );
573e8e4af76Sdrh   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
574ea48eb2eSdrh   if( pOrderBy==0 && !hasDistinct ){
575b7654111Sdrh     codeOffset(v, p, iContinue);
576df199a25Sdrh   }
577df199a25Sdrh 
578967e8b73Sdrh   /* Pull the requested columns.
5792282792aSdrh   */
58038640e15Sdrh   if( nColumn>0 ){
581d847eaadSdrh     nResultCol = nColumn;
582a2a49dc9Sdrh   }else{
583d847eaadSdrh     nResultCol = pEList->nExpr;
584a2a49dc9Sdrh   }
5852b596da8Sdrh   if( pDest->iSdst==0 ){
5862b596da8Sdrh     pDest->iSdst = pParse->nMem+1;
5872b596da8Sdrh     pDest->nSdst = nResultCol;
5880acb7e48Sdrh     pParse->nMem += nResultCol;
5891c767f0dSdrh   }else{
5902b596da8Sdrh     assert( pDest->nSdst==nResultCol );
5911013c932Sdrh   }
5922b596da8Sdrh   regResult = pDest->iSdst;
593a2a49dc9Sdrh   if( nColumn>0 ){
594967e8b73Sdrh     for(i=0; i<nColumn; i++){
595d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
59682c3d636Sdrh     }
5979ed1dfa8Sdanielk1977   }else if( eDest!=SRT_Exists ){
5989ed1dfa8Sdanielk1977     /* If the destination is an EXISTS(...) expression, the actual
5999ed1dfa8Sdanielk1977     ** values returned by the SELECT are not required.
6009ed1dfa8Sdanielk1977     */
601ceea3321Sdrh     sqlite3ExprCacheClear(pParse);
6027d10d5a6Sdrh     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
603a2a49dc9Sdrh   }
604d847eaadSdrh   nColumn = nResultCol;
6052282792aSdrh 
606daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
607daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
608daffd0e5Sdrh   ** part of the result.
6092282792aSdrh   */
610ea48eb2eSdrh   if( hasDistinct ){
611f8875400Sdrh     assert( pEList!=0 );
612f8875400Sdrh     assert( pEList->nExpr==nColumn );
613e8e4af76Sdrh     switch( pDistinct->eTnctType ){
614e8e4af76Sdrh       case WHERE_DISTINCT_ORDERED: {
615e8e4af76Sdrh         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
616e8e4af76Sdrh         int iJump;              /* Jump destination */
617e8e4af76Sdrh         int regPrev;            /* Previous row content */
618e8e4af76Sdrh 
619e8e4af76Sdrh         /* Allocate space for the previous row */
620e8e4af76Sdrh         regPrev = pParse->nMem+1;
621e8e4af76Sdrh         pParse->nMem += nColumn;
622e8e4af76Sdrh 
623e8e4af76Sdrh         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
624e8e4af76Sdrh         ** sets the MEM_Cleared bit on the first register of the
625e8e4af76Sdrh         ** previous value.  This will cause the OP_Ne below to always
626e8e4af76Sdrh         ** fail on the first iteration of the loop even if the first
627e8e4af76Sdrh         ** row is all NULLs.
628e8e4af76Sdrh         */
629e8e4af76Sdrh         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
630e8e4af76Sdrh         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
631e8e4af76Sdrh         pOp->opcode = OP_Null;
632e8e4af76Sdrh         pOp->p1 = 1;
633e8e4af76Sdrh         pOp->p2 = regPrev;
634e8e4af76Sdrh 
635e8e4af76Sdrh         iJump = sqlite3VdbeCurrentAddr(v) + nColumn;
636e8e4af76Sdrh         for(i=0; i<nColumn; i++){
637e8e4af76Sdrh           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
638e8e4af76Sdrh           if( i<nColumn-1 ){
639e8e4af76Sdrh             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
640e8e4af76Sdrh           }else{
641e8e4af76Sdrh             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
642e8e4af76Sdrh           }
643e8e4af76Sdrh           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
644e8e4af76Sdrh           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
645e8e4af76Sdrh         }
646e8e4af76Sdrh         assert( sqlite3VdbeCurrentAddr(v)==iJump );
647e8e4af76Sdrh         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nColumn-1);
648e8e4af76Sdrh         break;
649e8e4af76Sdrh       }
650e8e4af76Sdrh 
651e8e4af76Sdrh       case WHERE_DISTINCT_UNIQUE: {
652e8e4af76Sdrh         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
653e8e4af76Sdrh         break;
654e8e4af76Sdrh       }
655e8e4af76Sdrh 
656e8e4af76Sdrh       default: {
657e8e4af76Sdrh         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
658e8e4af76Sdrh         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult);
659e8e4af76Sdrh         break;
660e8e4af76Sdrh       }
661e8e4af76Sdrh     }
662ea48eb2eSdrh     if( pOrderBy==0 ){
663b7654111Sdrh       codeOffset(v, p, iContinue);
664ea48eb2eSdrh     }
6652282792aSdrh   }
66682c3d636Sdrh 
667c926afbcSdrh   switch( eDest ){
66882c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
66982c3d636Sdrh     ** table iParm.
6702282792aSdrh     */
67113449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
672c926afbcSdrh     case SRT_Union: {
6739cbf3425Sdrh       int r1;
6749cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
675d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
6769cbf3425Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
6779cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
678c926afbcSdrh       break;
679c926afbcSdrh     }
68082c3d636Sdrh 
68182c3d636Sdrh     /* Construct a record from the query result, but instead of
68282c3d636Sdrh     ** saving that record, use it as a key to delete elements from
68382c3d636Sdrh     ** the temporary table iParm.
68482c3d636Sdrh     */
685c926afbcSdrh     case SRT_Except: {
686e14006d0Sdrh       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
687c926afbcSdrh       break;
688c926afbcSdrh     }
6895338a5f7Sdanielk1977 #endif
6905338a5f7Sdanielk1977 
6915338a5f7Sdanielk1977     /* Store the result as data using a unique key.
6925338a5f7Sdanielk1977     */
6935338a5f7Sdanielk1977     case SRT_Table:
694b9bb7c18Sdrh     case SRT_EphemTab: {
695b7654111Sdrh       int r1 = sqlite3GetTempReg(pParse);
696373cc2ddSdrh       testcase( eDest==SRT_Table );
697373cc2ddSdrh       testcase( eDest==SRT_EphemTab );
698d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
6995338a5f7Sdanielk1977       if( pOrderBy ){
700b7654111Sdrh         pushOntoSorter(pParse, pOrderBy, p, r1);
7015338a5f7Sdanielk1977       }else{
702b7654111Sdrh         int r2 = sqlite3GetTempReg(pParse);
703b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
704b7654111Sdrh         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
705b7654111Sdrh         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
706b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r2);
7075338a5f7Sdanielk1977       }
708b7654111Sdrh       sqlite3ReleaseTempReg(pParse, r1);
7095338a5f7Sdanielk1977       break;
7105338a5f7Sdanielk1977     }
7112282792aSdrh 
71293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
7132282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
7142282792aSdrh     ** then there should be a single item on the stack.  Write this
7152282792aSdrh     ** item into the set table with bogus data.
7162282792aSdrh     */
717c926afbcSdrh     case SRT_Set: {
718967e8b73Sdrh       assert( nColumn==1 );
719634d81deSdrh       pDest->affSdst =
720634d81deSdrh                   sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
721c926afbcSdrh       if( pOrderBy ){
722de941c60Sdrh         /* At first glance you would think we could optimize out the
723de941c60Sdrh         ** ORDER BY in this case since the order of entries in the set
724de941c60Sdrh         ** does not matter.  But there might be a LIMIT clause, in which
725de941c60Sdrh         ** case the order does matter */
726d847eaadSdrh         pushOntoSorter(pParse, pOrderBy, p, regResult);
727c926afbcSdrh       }else{
728b7654111Sdrh         int r1 = sqlite3GetTempReg(pParse);
729634d81deSdrh         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
730da250ea5Sdrh         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
731b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
732b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r1);
733c926afbcSdrh       }
734c926afbcSdrh       break;
735c926afbcSdrh     }
73682c3d636Sdrh 
737504b6989Sdrh     /* If any row exist in the result set, record that fact and abort.
738ec7429aeSdrh     */
739ec7429aeSdrh     case SRT_Exists: {
7404c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
741ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
742ec7429aeSdrh       break;
743ec7429aeSdrh     }
744ec7429aeSdrh 
7452282792aSdrh     /* If this is a scalar select that is part of an expression, then
7462282792aSdrh     ** store the results in the appropriate memory cell and break out
7472282792aSdrh     ** of the scan loop.
7482282792aSdrh     */
749c926afbcSdrh     case SRT_Mem: {
750967e8b73Sdrh       assert( nColumn==1 );
751c926afbcSdrh       if( pOrderBy ){
752d847eaadSdrh         pushOntoSorter(pParse, pOrderBy, p, regResult);
753c926afbcSdrh       }else{
754b21e7c70Sdrh         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
755ec7429aeSdrh         /* The LIMIT clause will jump out of the loop for us */
756c926afbcSdrh       }
757c926afbcSdrh       break;
758c926afbcSdrh     }
75993758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
7602282792aSdrh 
761c182d163Sdrh     /* Send the data to the callback function or to a subroutine.  In the
762c182d163Sdrh     ** case of a subroutine, the subroutine itself is responsible for
763c182d163Sdrh     ** popping the data from the stack.
764f46f905aSdrh     */
765e00ee6ebSdrh     case SRT_Coroutine:
7667d10d5a6Sdrh     case SRT_Output: {
767373cc2ddSdrh       testcase( eDest==SRT_Coroutine );
768373cc2ddSdrh       testcase( eDest==SRT_Output );
769f46f905aSdrh       if( pOrderBy ){
770b7654111Sdrh         int r1 = sqlite3GetTempReg(pParse);
771d847eaadSdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
772b7654111Sdrh         pushOntoSorter(pParse, pOrderBy, p, r1);
773b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r1);
774e00ee6ebSdrh       }else if( eDest==SRT_Coroutine ){
7752b596da8Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
776c182d163Sdrh       }else{
777d847eaadSdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
778da250ea5Sdrh         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
779ac82fcf5Sdrh       }
780142e30dfSdrh       break;
781142e30dfSdrh     }
782142e30dfSdrh 
7836a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER)
784d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
785d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
786d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
787d7489c39Sdrh     ** about the actual results of the select.
788d7489c39Sdrh     */
789c926afbcSdrh     default: {
790f46f905aSdrh       assert( eDest==SRT_Discard );
791c926afbcSdrh       break;
792c926afbcSdrh     }
79393758c8dSdanielk1977 #endif
794c926afbcSdrh   }
795ec7429aeSdrh 
7965e87be87Sdrh   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
7975e87be87Sdrh   ** there is a sorter, in which case the sorter has already limited
7985e87be87Sdrh   ** the output for us.
799ec7429aeSdrh   */
8005e87be87Sdrh   if( pOrderBy==0 && p->iLimit ){
8019b918ed1Sdrh     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
802ec7429aeSdrh   }
80382c3d636Sdrh }
80482c3d636Sdrh 
80582c3d636Sdrh /*
806dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records
807dece1a84Sdrh ** the collating sequence for each expression in that expression list.
808dece1a84Sdrh **
8090342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
8100342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to
8110342b1f5Sdrh ** implement that clause.  If the ExprList is the result set of a SELECT
8120342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual
8130342b1f5Sdrh ** index to implement a DISTINCT test.
8140342b1f5Sdrh **
815dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
816dece1a84Sdrh ** function is responsible for seeing that this structure is eventually
81766a5167bSdrh ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
81866a5167bSdrh ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
819dece1a84Sdrh */
820dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
821dece1a84Sdrh   sqlite3 *db = pParse->db;
822dece1a84Sdrh   int nExpr;
823dece1a84Sdrh   KeyInfo *pInfo;
824dece1a84Sdrh   struct ExprList_item *pItem;
825dece1a84Sdrh   int i;
826dece1a84Sdrh 
827dece1a84Sdrh   nExpr = pList->nExpr;
82817435752Sdrh   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
829dece1a84Sdrh   if( pInfo ){
8302646da7eSdrh     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
831ea678832Sdrh     pInfo->nField = (u16)nExpr;
83214db2665Sdanielk1977     pInfo->enc = ENC(db);
8332aca5846Sdrh     pInfo->db = db;
834dece1a84Sdrh     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
835dece1a84Sdrh       CollSeq *pColl;
836dece1a84Sdrh       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
837dece1a84Sdrh       if( !pColl ){
838dece1a84Sdrh         pColl = db->pDfltColl;
839dece1a84Sdrh       }
840dece1a84Sdrh       pInfo->aColl[i] = pColl;
841dece1a84Sdrh       pInfo->aSortOrder[i] = pItem->sortOrder;
842dece1a84Sdrh     }
843dece1a84Sdrh   }
844dece1a84Sdrh   return pInfo;
845dece1a84Sdrh }
846dece1a84Sdrh 
8477f61e92cSdan #ifndef SQLITE_OMIT_COMPOUND_SELECT
8487f61e92cSdan /*
8497f61e92cSdan ** Name of the connection operator, used for error messages.
8507f61e92cSdan */
8517f61e92cSdan static const char *selectOpName(int id){
8527f61e92cSdan   char *z;
8537f61e92cSdan   switch( id ){
8547f61e92cSdan     case TK_ALL:       z = "UNION ALL";   break;
8557f61e92cSdan     case TK_INTERSECT: z = "INTERSECT";   break;
8567f61e92cSdan     case TK_EXCEPT:    z = "EXCEPT";      break;
8577f61e92cSdan     default:           z = "UNION";       break;
8587f61e92cSdan   }
8597f61e92cSdan   return z;
8607f61e92cSdan }
8617f61e92cSdan #endif /* SQLITE_OMIT_COMPOUND_SELECT */
8627f61e92cSdan 
8632ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN
86417c0bc0cSdan /*
86517c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
86617c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
86717c0bc0cSdan ** where the caption is of the form:
86817c0bc0cSdan **
86917c0bc0cSdan **   "USE TEMP B-TREE FOR xxx"
87017c0bc0cSdan **
87117c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
87217c0bc0cSdan ** is determined by the zUsage argument.
87317c0bc0cSdan */
8742ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){
8752ce22453Sdan   if( pParse->explain==2 ){
8762ce22453Sdan     Vdbe *v = pParse->pVdbe;
8772ce22453Sdan     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
8782ce22453Sdan     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
8792ce22453Sdan   }
8802ce22453Sdan }
88117c0bc0cSdan 
88217c0bc0cSdan /*
883bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro
884bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
885bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that
886bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
887bb2b4418Sdan ** code with #ifndef directives.
888bb2b4418Sdan */
889bb2b4418Sdan # define explainSetInteger(a, b) a = b
890bb2b4418Sdan 
891bb2b4418Sdan #else
892bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */
893bb2b4418Sdan # define explainTempTable(y,z)
894bb2b4418Sdan # define explainSetInteger(y,z)
895bb2b4418Sdan #endif
896bb2b4418Sdan 
897bb2b4418Sdan #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
898bb2b4418Sdan /*
8997f61e92cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
9007f61e92cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
9017f61e92cSdan ** where the caption is of one of the two forms:
9027f61e92cSdan **
9037f61e92cSdan **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
9047f61e92cSdan **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
9057f61e92cSdan **
9067f61e92cSdan ** where iSub1 and iSub2 are the integers passed as the corresponding
9077f61e92cSdan ** function parameters, and op is the text representation of the parameter
9087f61e92cSdan ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
9097f61e92cSdan ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
9107f61e92cSdan ** false, or the second form if it is true.
9117f61e92cSdan */
9127f61e92cSdan static void explainComposite(
9137f61e92cSdan   Parse *pParse,                  /* Parse context */
9147f61e92cSdan   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
9157f61e92cSdan   int iSub1,                      /* Subquery id 1 */
9167f61e92cSdan   int iSub2,                      /* Subquery id 2 */
9177f61e92cSdan   int bUseTmp                     /* True if a temp table was used */
9187f61e92cSdan ){
9197f61e92cSdan   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
9207f61e92cSdan   if( pParse->explain==2 ){
9217f61e92cSdan     Vdbe *v = pParse->pVdbe;
9227f61e92cSdan     char *zMsg = sqlite3MPrintf(
92330969d3fSdan         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
9247f61e92cSdan         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
9257f61e92cSdan     );
9267f61e92cSdan     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
9277f61e92cSdan   }
9287f61e92cSdan }
9292ce22453Sdan #else
93017c0bc0cSdan /* No-op versions of the explainXXX() functions and macros. */
9317f61e92cSdan # define explainComposite(v,w,x,y,z)
9322ce22453Sdan #endif
933dece1a84Sdrh 
934dece1a84Sdrh /*
935d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
936d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
937d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
938d8bc7086Sdrh ** routine generates the code needed to do that.
939d8bc7086Sdrh */
940c926afbcSdrh static void generateSortTail(
941cdd536f0Sdrh   Parse *pParse,    /* Parsing context */
942c926afbcSdrh   Select *p,        /* The SELECT statement */
943c926afbcSdrh   Vdbe *v,          /* Generate code into this VDBE */
944c926afbcSdrh   int nColumn,      /* Number of columns of data */
9456c8c8ce0Sdanielk1977   SelectDest *pDest /* Write the sorted results here */
946c926afbcSdrh ){
947dc5ea5c7Sdrh   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
948dc5ea5c7Sdrh   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
949d8bc7086Sdrh   int addr;
9500342b1f5Sdrh   int iTab;
95161fc595fSdrh   int pseudoTab = 0;
9520342b1f5Sdrh   ExprList *pOrderBy = p->pOrderBy;
953ffbc3088Sdrh 
9546c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
9552b596da8Sdrh   int iParm = pDest->iSDParm;
9566c8c8ce0Sdanielk1977 
9572d401ab8Sdrh   int regRow;
9582d401ab8Sdrh   int regRowid;
9592d401ab8Sdrh 
9609d2985c7Sdrh   iTab = pOrderBy->iECursor;
9613e9ca094Sdrh   regRow = sqlite3GetTempReg(pParse);
9627d10d5a6Sdrh   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
963cdd536f0Sdrh     pseudoTab = pParse->nTab++;
9643e9ca094Sdrh     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
9653e9ca094Sdrh     regRowid = 0;
9663e9ca094Sdrh   }else{
9673e9ca094Sdrh     regRowid = sqlite3GetTempReg(pParse);
968cdd536f0Sdrh   }
969c6aff30cSdrh   if( p->selFlags & SF_UseSorter ){
970c2bb3282Sdrh     int regSortOut = ++pParse->nMem;
971c6aff30cSdrh     int ptab2 = pParse->nTab++;
972c6aff30cSdrh     sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
973c6aff30cSdrh     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
974c6aff30cSdrh     codeOffset(v, p, addrContinue);
975c6aff30cSdrh     sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
976c6aff30cSdrh     sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
977c6aff30cSdrh     sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
978c6aff30cSdrh   }else{
979dc5ea5c7Sdrh     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
980dc5ea5c7Sdrh     codeOffset(v, p, addrContinue);
9812d401ab8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
982c6aff30cSdrh   }
983c926afbcSdrh   switch( eDest ){
984c926afbcSdrh     case SRT_Table:
985b9bb7c18Sdrh     case SRT_EphemTab: {
9861c767f0dSdrh       testcase( eDest==SRT_Table );
9871c767f0dSdrh       testcase( eDest==SRT_EphemTab );
9882d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
9892d401ab8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
9902d401ab8Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
991c926afbcSdrh       break;
992c926afbcSdrh     }
99393758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
994c926afbcSdrh     case SRT_Set: {
995c926afbcSdrh       assert( nColumn==1 );
996634d81deSdrh       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
997634d81deSdrh                         &pDest->affSdst, 1);
998da250ea5Sdrh       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
999a7a8e14bSdanielk1977       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
1000c926afbcSdrh       break;
1001c926afbcSdrh     }
1002c926afbcSdrh     case SRT_Mem: {
1003c926afbcSdrh       assert( nColumn==1 );
1004b21e7c70Sdrh       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
1005ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
1006c926afbcSdrh       break;
1007c926afbcSdrh     }
100893758c8dSdanielk1977 #endif
1009373cc2ddSdrh     default: {
1010ac82fcf5Sdrh       int i;
1011373cc2ddSdrh       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
10121c767f0dSdrh       testcase( eDest==SRT_Output );
10131c767f0dSdrh       testcase( eDest==SRT_Coroutine );
1014ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
10152b596da8Sdrh         assert( regRow!=pDest->iSdst+i );
10162b596da8Sdrh         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
10173e9ca094Sdrh         if( i==0 ){
10183e9ca094Sdrh           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
10193e9ca094Sdrh         }
1020ac82fcf5Sdrh       }
10217d10d5a6Sdrh       if( eDest==SRT_Output ){
10222b596da8Sdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
10232b596da8Sdrh         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
1024a9671a22Sdrh       }else{
10252b596da8Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1026ce665cf6Sdrh       }
1027ac82fcf5Sdrh       break;
1028ac82fcf5Sdrh     }
1029c926afbcSdrh   }
10302d401ab8Sdrh   sqlite3ReleaseTempReg(pParse, regRow);
10312d401ab8Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
1032ec7429aeSdrh 
1033ec7429aeSdrh   /* The bottom of the loop
1034ec7429aeSdrh   */
1035dc5ea5c7Sdrh   sqlite3VdbeResolveLabel(v, addrContinue);
1036c6aff30cSdrh   if( p->selFlags & SF_UseSorter ){
1037c6aff30cSdrh     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
1038c6aff30cSdrh   }else{
103966a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
1040c6aff30cSdrh   }
1041dc5ea5c7Sdrh   sqlite3VdbeResolveLabel(v, addrBreak);
10427d10d5a6Sdrh   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
104366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
1044cdd536f0Sdrh   }
1045d8bc7086Sdrh }
1046d8bc7086Sdrh 
1047d8bc7086Sdrh /*
1048517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
1049517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
1050e78e8284Sdrh **
1051955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the
1052955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The
1053955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
1054955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The
1055955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is
1056955de52cSdanielk1977 ** considered a column by this function.
1057e78e8284Sdrh **
1058955de52cSdanielk1977 **   SELECT col FROM tbl;
1059955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl;
1060955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl);
1061955de52cSdanielk1977 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
1062955de52cSdanielk1977 **
1063955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL.
1064fcb78a49Sdrh */
1065955de52cSdanielk1977 static const char *columnType(
1066955de52cSdanielk1977   NameContext *pNC,
1067955de52cSdanielk1977   Expr *pExpr,
1068955de52cSdanielk1977   const char **pzOriginDb,
1069955de52cSdanielk1977   const char **pzOriginTab,
1070955de52cSdanielk1977   const char **pzOriginCol
1071955de52cSdanielk1977 ){
1072955de52cSdanielk1977   char const *zType = 0;
1073955de52cSdanielk1977   char const *zOriginDb = 0;
1074955de52cSdanielk1977   char const *zOriginTab = 0;
1075955de52cSdanielk1977   char const *zOriginCol = 0;
1076517eb646Sdanielk1977   int j;
1077373cc2ddSdrh   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
10785338a5f7Sdanielk1977 
107900e279d9Sdanielk1977   switch( pExpr->op ){
108030bcf5dbSdrh     case TK_AGG_COLUMN:
108100e279d9Sdanielk1977     case TK_COLUMN: {
1082955de52cSdanielk1977       /* The expression is a column. Locate the table the column is being
1083955de52cSdanielk1977       ** extracted from in NameContext.pSrcList. This table may be real
1084955de52cSdanielk1977       ** database table or a subquery.
1085955de52cSdanielk1977       */
1086955de52cSdanielk1977       Table *pTab = 0;            /* Table structure column is extracted from */
1087955de52cSdanielk1977       Select *pS = 0;             /* Select the column is extracted from */
1088955de52cSdanielk1977       int iCol = pExpr->iColumn;  /* Index of column in pTab */
1089373cc2ddSdrh       testcase( pExpr->op==TK_AGG_COLUMN );
1090373cc2ddSdrh       testcase( pExpr->op==TK_COLUMN );
109143bc88bbSdan       while( pNC && !pTab ){
1092b3bce662Sdanielk1977         SrcList *pTabList = pNC->pSrcList;
1093b3bce662Sdanielk1977         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
1094b3bce662Sdanielk1977         if( j<pTabList->nSrc ){
10956a3ea0e6Sdrh           pTab = pTabList->a[j].pTab;
1096955de52cSdanielk1977           pS = pTabList->a[j].pSelect;
1097b3bce662Sdanielk1977         }else{
1098b3bce662Sdanielk1977           pNC = pNC->pNext;
1099b3bce662Sdanielk1977         }
1100b3bce662Sdanielk1977       }
1101955de52cSdanielk1977 
110243bc88bbSdan       if( pTab==0 ){
1103417168adSdrh         /* At one time, code such as "SELECT new.x" within a trigger would
1104417168adSdrh         ** cause this condition to run.  Since then, we have restructured how
1105417168adSdrh         ** trigger code is generated and so this condition is no longer
110643bc88bbSdan         ** possible. However, it can still be true for statements like
110743bc88bbSdan         ** the following:
110843bc88bbSdan         **
110943bc88bbSdan         **   CREATE TABLE t1(col INTEGER);
111043bc88bbSdan         **   SELECT (SELECT t1.col) FROM FROM t1;
111143bc88bbSdan         **
111243bc88bbSdan         ** when columnType() is called on the expression "t1.col" in the
111343bc88bbSdan         ** sub-select. In this case, set the column type to NULL, even
111443bc88bbSdan         ** though it should really be "INTEGER".
111543bc88bbSdan         **
111643bc88bbSdan         ** This is not a problem, as the column type of "t1.col" is never
111743bc88bbSdan         ** used. When columnType() is called on the expression
111843bc88bbSdan         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
111943bc88bbSdan         ** branch below.  */
11207e62779aSdrh         break;
11217e62779aSdrh       }
1122955de52cSdanielk1977 
112343bc88bbSdan       assert( pTab && pExpr->pTab==pTab );
1124955de52cSdanielk1977       if( pS ){
1125955de52cSdanielk1977         /* The "table" is actually a sub-select or a view in the FROM clause
1126955de52cSdanielk1977         ** of the SELECT statement. Return the declaration type and origin
1127955de52cSdanielk1977         ** data for the result-set column of the sub-select.
1128955de52cSdanielk1977         */
11297b688edeSdrh         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
1130955de52cSdanielk1977           /* If iCol is less than zero, then the expression requests the
1131955de52cSdanielk1977           ** rowid of the sub-select or view. This expression is legal (see
1132955de52cSdanielk1977           ** test case misc2.2.2) - it always evaluates to NULL.
1133955de52cSdanielk1977           */
1134955de52cSdanielk1977           NameContext sNC;
1135955de52cSdanielk1977           Expr *p = pS->pEList->a[iCol].pExpr;
1136955de52cSdanielk1977           sNC.pSrcList = pS->pSrc;
113743bc88bbSdan           sNC.pNext = pNC;
1138955de52cSdanielk1977           sNC.pParse = pNC->pParse;
1139955de52cSdanielk1977           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
1140955de52cSdanielk1977         }
11411c767f0dSdrh       }else if( ALWAYS(pTab->pSchema) ){
1142955de52cSdanielk1977         /* A real table */
1143955de52cSdanielk1977         assert( !pS );
1144fcb78a49Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
1145fcb78a49Sdrh         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1146fcb78a49Sdrh         if( iCol<0 ){
1147fcb78a49Sdrh           zType = "INTEGER";
1148955de52cSdanielk1977           zOriginCol = "rowid";
1149fcb78a49Sdrh         }else{
1150fcb78a49Sdrh           zType = pTab->aCol[iCol].zType;
1151955de52cSdanielk1977           zOriginCol = pTab->aCol[iCol].zName;
1152955de52cSdanielk1977         }
1153955de52cSdanielk1977         zOriginTab = pTab->zName;
1154955de52cSdanielk1977         if( pNC->pParse ){
1155955de52cSdanielk1977           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
1156955de52cSdanielk1977           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
1157955de52cSdanielk1977         }
1158fcb78a49Sdrh       }
115900e279d9Sdanielk1977       break;
1160736c22b8Sdrh     }
116193758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
116200e279d9Sdanielk1977     case TK_SELECT: {
1163955de52cSdanielk1977       /* The expression is a sub-select. Return the declaration type and
1164955de52cSdanielk1977       ** origin info for the single column in the result set of the SELECT
1165955de52cSdanielk1977       ** statement.
1166955de52cSdanielk1977       */
1167b3bce662Sdanielk1977       NameContext sNC;
11686ab3a2ecSdanielk1977       Select *pS = pExpr->x.pSelect;
1169955de52cSdanielk1977       Expr *p = pS->pEList->a[0].pExpr;
11706ab3a2ecSdanielk1977       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
1171955de52cSdanielk1977       sNC.pSrcList = pS->pSrc;
1172b3bce662Sdanielk1977       sNC.pNext = pNC;
1173955de52cSdanielk1977       sNC.pParse = pNC->pParse;
1174955de52cSdanielk1977       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
117500e279d9Sdanielk1977       break;
1176fcb78a49Sdrh     }
117793758c8dSdanielk1977 #endif
117800e279d9Sdanielk1977   }
117900e279d9Sdanielk1977 
1180955de52cSdanielk1977   if( pzOriginDb ){
1181955de52cSdanielk1977     assert( pzOriginTab && pzOriginCol );
1182955de52cSdanielk1977     *pzOriginDb = zOriginDb;
1183955de52cSdanielk1977     *pzOriginTab = zOriginTab;
1184955de52cSdanielk1977     *pzOriginCol = zOriginCol;
1185955de52cSdanielk1977   }
1186517eb646Sdanielk1977   return zType;
1187517eb646Sdanielk1977 }
1188517eb646Sdanielk1977 
1189517eb646Sdanielk1977 /*
1190517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
1191517eb646Sdanielk1977 ** in the result set.
1192517eb646Sdanielk1977 */
1193517eb646Sdanielk1977 static void generateColumnTypes(
1194517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
1195517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
1196517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
1197517eb646Sdanielk1977 ){
11983f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE
1199517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
1200517eb646Sdanielk1977   int i;
1201b3bce662Sdanielk1977   NameContext sNC;
1202b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
1203955de52cSdanielk1977   sNC.pParse = pParse;
1204517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
1205517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
12063f913576Sdrh     const char *zType;
12073f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1208955de52cSdanielk1977     const char *zOrigDb = 0;
1209955de52cSdanielk1977     const char *zOrigTab = 0;
1210955de52cSdanielk1977     const char *zOrigCol = 0;
12113f913576Sdrh     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
1212955de52cSdanielk1977 
121385b623f2Sdrh     /* The vdbe must make its own copy of the column-type and other
12144b1ae99dSdanielk1977     ** column specific strings, in case the schema is reset before this
12154b1ae99dSdanielk1977     ** virtual machine is deleted.
1216fbcd585fSdanielk1977     */
121710fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
121810fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
121910fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
12203f913576Sdrh #else
12213f913576Sdrh     zType = columnType(&sNC, p, 0, 0, 0);
12223f913576Sdrh #endif
122310fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
1224fcb78a49Sdrh   }
12253f913576Sdrh #endif /* SQLITE_OMIT_DECLTYPE */
1226fcb78a49Sdrh }
1227fcb78a49Sdrh 
1228fcb78a49Sdrh /*
1229fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
1230fcb78a49Sdrh ** in the result set.  This information is used to provide the
1231fcabd464Sdrh ** azCol[] values in the callback.
123282c3d636Sdrh */
1233832508b7Sdrh static void generateColumnNames(
1234832508b7Sdrh   Parse *pParse,      /* Parser context */
1235ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
1236832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
1237832508b7Sdrh ){
1238d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
12396a3ea0e6Sdrh   int i, j;
12409bb575fdSdrh   sqlite3 *db = pParse->db;
1241fcabd464Sdrh   int fullNames, shortNames;
1242fcabd464Sdrh 
1243fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN
12443cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
12453cf86063Sdanielk1977   if( pParse->explain ){
124661de0d1bSdanielk1977     return;
12473cf86063Sdanielk1977   }
12485338a5f7Sdanielk1977 #endif
12493cf86063Sdanielk1977 
1250e2f02bacSdrh   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
1251d8bc7086Sdrh   pParse->colNamesSet = 1;
1252fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
1253fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
125422322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
125582c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
125682c3d636Sdrh     Expr *p;
12575a38705eSdrh     p = pEList->a[i].pExpr;
1258373cc2ddSdrh     if( NEVER(p==0) ) continue;
125982c3d636Sdrh     if( pEList->a[i].zName ){
126082c3d636Sdrh       char *zName = pEList->a[i].zName;
126110fb749bSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
1262f018cc2eSdrh     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
12636a3ea0e6Sdrh       Table *pTab;
126497665873Sdrh       char *zCol;
12658aff1015Sdrh       int iCol = p->iColumn;
1266e2f02bacSdrh       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
1267e2f02bacSdrh         if( pTabList->a[j].iCursor==p->iTable ) break;
1268e2f02bacSdrh       }
12696a3ea0e6Sdrh       assert( j<pTabList->nSrc );
12706a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
12718aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
127297665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1273b1363206Sdrh       if( iCol<0 ){
127447a6db2bSdrh         zCol = "rowid";
1275b1363206Sdrh       }else{
1276b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
1277b1363206Sdrh       }
1278e49b146fSdrh       if( !shortNames && !fullNames ){
127910fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
1280b7916a78Sdrh             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
12811c767f0dSdrh       }else if( fullNames ){
128282c3d636Sdrh         char *zName = 0;
12831c767f0dSdrh         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
128410fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
128582c3d636Sdrh       }else{
128610fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
128782c3d636Sdrh       }
12881bee3d7bSdrh     }else{
128910fb749bSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME,
1290b7916a78Sdrh           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
129182c3d636Sdrh     }
129282c3d636Sdrh   }
129376d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
12945080aaa7Sdrh }
129582c3d636Sdrh 
1296d8bc7086Sdrh /*
12977d10d5a6Sdrh ** Given a an expression list (which is really the list of expressions
12987d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate
12997d10d5a6Sdrh ** column names for a table that would hold the expression list.
13007d10d5a6Sdrh **
13017d10d5a6Sdrh ** All column names will be unique.
13027d10d5a6Sdrh **
13037d10d5a6Sdrh ** Only the column names are computed.  Column.zType, Column.zColl,
13047d10d5a6Sdrh ** and other fields of Column are zeroed.
13057d10d5a6Sdrh **
13067d10d5a6Sdrh ** Return SQLITE_OK on success.  If a memory allocation error occurs,
13077d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
1308315555caSdrh */
13097d10d5a6Sdrh static int selectColumnsFromExprList(
13107d10d5a6Sdrh   Parse *pParse,          /* Parsing context */
13117d10d5a6Sdrh   ExprList *pEList,       /* Expr list from which to derive column names */
1312d815f17dSdrh   i16 *pnCol,             /* Write the number of columns here */
13137d10d5a6Sdrh   Column **paCol          /* Write the new column list here */
13147d10d5a6Sdrh ){
1315dc5ea5c7Sdrh   sqlite3 *db = pParse->db;   /* Database connection */
1316dc5ea5c7Sdrh   int i, j;                   /* Loop counters */
1317dc5ea5c7Sdrh   int cnt;                    /* Index added to make the name unique */
1318dc5ea5c7Sdrh   Column *aCol, *pCol;        /* For looping over result columns */
1319dc5ea5c7Sdrh   int nCol;                   /* Number of columns in the result set */
1320dc5ea5c7Sdrh   Expr *p;                    /* Expression for a single result column */
1321dc5ea5c7Sdrh   char *zName;                /* Column name */
1322dc5ea5c7Sdrh   int nName;                  /* Size of name in zName[] */
132379d5f63fSdrh 
13248c2e0f02Sdan   if( pEList ){
13258c2e0f02Sdan     nCol = pEList->nExpr;
13268c2e0f02Sdan     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
13278c2e0f02Sdan     testcase( aCol==0 );
13288c2e0f02Sdan   }else{
13298c2e0f02Sdan     nCol = 0;
13308c2e0f02Sdan     aCol = 0;
13318c2e0f02Sdan   }
13328c2e0f02Sdan   *pnCol = nCol;
13338c2e0f02Sdan   *paCol = aCol;
13348c2e0f02Sdan 
13357d10d5a6Sdrh   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
133679d5f63fSdrh     /* Get an appropriate name for the column
133779d5f63fSdrh     */
133879d5f63fSdrh     p = pEList->a[i].pExpr;
133933e619fcSdrh     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
134033e619fcSdrh                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
134191bb0eedSdrh     if( (zName = pEList->a[i].zName)!=0 ){
134279d5f63fSdrh       /* If the column contains an "AS <name>" phrase, use <name> as the name */
134317435752Sdrh       zName = sqlite3DbStrDup(db, zName);
13447d10d5a6Sdrh     }else{
1345dc5ea5c7Sdrh       Expr *pColExpr = p;  /* The expression that is the result column name */
1346dc5ea5c7Sdrh       Table *pTab;         /* Table associated with this expression */
1347b07028f7Sdrh       while( pColExpr->op==TK_DOT ){
1348b07028f7Sdrh         pColExpr = pColExpr->pRight;
1349b07028f7Sdrh         assert( pColExpr!=0 );
1350b07028f7Sdrh       }
1351373cc2ddSdrh       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
135293a960a0Sdrh         /* For columns use the column name name */
1353dc5ea5c7Sdrh         int iCol = pColExpr->iColumn;
1354373cc2ddSdrh         pTab = pColExpr->pTab;
1355f0209f74Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
1356f0209f74Sdrh         zName = sqlite3MPrintf(db, "%s",
1357f0209f74Sdrh                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
1358b7916a78Sdrh       }else if( pColExpr->op==TK_ID ){
135933e619fcSdrh         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
136033e619fcSdrh         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
136193a960a0Sdrh       }else{
136279d5f63fSdrh         /* Use the original text of the column expression as its name */
1363b7916a78Sdrh         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
13647d10d5a6Sdrh       }
136522f70c32Sdrh     }
13667ce72f69Sdrh     if( db->mallocFailed ){
1367633e6d57Sdrh       sqlite3DbFree(db, zName);
13687ce72f69Sdrh       break;
1369dd5b2fa5Sdrh     }
137079d5f63fSdrh 
137179d5f63fSdrh     /* Make sure the column name is unique.  If the name is not unique,
137279d5f63fSdrh     ** append a integer to the name so that it becomes unique.
137379d5f63fSdrh     */
1374ea678832Sdrh     nName = sqlite3Strlen30(zName);
137579d5f63fSdrh     for(j=cnt=0; j<i; j++){
137679d5f63fSdrh       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
1377633e6d57Sdrh         char *zNewName;
13782564ef97Sdrh         zName[nName] = 0;
1379633e6d57Sdrh         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
1380633e6d57Sdrh         sqlite3DbFree(db, zName);
1381633e6d57Sdrh         zName = zNewName;
138279d5f63fSdrh         j = -1;
1383dd5b2fa5Sdrh         if( zName==0 ) break;
138479d5f63fSdrh       }
138579d5f63fSdrh     }
138691bb0eedSdrh     pCol->zName = zName;
13877d10d5a6Sdrh   }
13887d10d5a6Sdrh   if( db->mallocFailed ){
13897d10d5a6Sdrh     for(j=0; j<i; j++){
13907d10d5a6Sdrh       sqlite3DbFree(db, aCol[j].zName);
13917d10d5a6Sdrh     }
13927d10d5a6Sdrh     sqlite3DbFree(db, aCol);
13937d10d5a6Sdrh     *paCol = 0;
13947d10d5a6Sdrh     *pnCol = 0;
13957d10d5a6Sdrh     return SQLITE_NOMEM;
13967d10d5a6Sdrh   }
13977d10d5a6Sdrh   return SQLITE_OK;
13987d10d5a6Sdrh }
1399e014a838Sdanielk1977 
14007d10d5a6Sdrh /*
14017d10d5a6Sdrh ** Add type and collation information to a column list based on
14027d10d5a6Sdrh ** a SELECT statement.
14037d10d5a6Sdrh **
14047d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList().
14057d10d5a6Sdrh ** The column list has only names, not types or collations.  This
14067d10d5a6Sdrh ** routine goes through and adds the types and collations.
14077d10d5a6Sdrh **
1408b08a67a7Sshane ** This routine requires that all identifiers in the SELECT
14097d10d5a6Sdrh ** statement be resolved.
141079d5f63fSdrh */
14117d10d5a6Sdrh static void selectAddColumnTypeAndCollation(
14127d10d5a6Sdrh   Parse *pParse,        /* Parsing contexts */
14137d10d5a6Sdrh   int nCol,             /* Number of columns */
14147d10d5a6Sdrh   Column *aCol,         /* List of columns */
14157d10d5a6Sdrh   Select *pSelect       /* SELECT used to determine types and collations */
14167d10d5a6Sdrh ){
14177d10d5a6Sdrh   sqlite3 *db = pParse->db;
14187d10d5a6Sdrh   NameContext sNC;
14197d10d5a6Sdrh   Column *pCol;
14207d10d5a6Sdrh   CollSeq *pColl;
14217d10d5a6Sdrh   int i;
14227d10d5a6Sdrh   Expr *p;
14237d10d5a6Sdrh   struct ExprList_item *a;
14247d10d5a6Sdrh 
14257d10d5a6Sdrh   assert( pSelect!=0 );
14267d10d5a6Sdrh   assert( (pSelect->selFlags & SF_Resolved)!=0 );
14277d10d5a6Sdrh   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
14287d10d5a6Sdrh   if( db->mallocFailed ) return;
1429c43e8be8Sdrh   memset(&sNC, 0, sizeof(sNC));
1430b3bce662Sdanielk1977   sNC.pSrcList = pSelect->pSrc;
14317d10d5a6Sdrh   a = pSelect->pEList->a;
14327d10d5a6Sdrh   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
14337d10d5a6Sdrh     p = a[i].pExpr;
14347d10d5a6Sdrh     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
1435c60e9b82Sdanielk1977     pCol->affinity = sqlite3ExprAffinity(p);
1436c4a64facSdrh     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
1437b3bf556eSdanielk1977     pColl = sqlite3ExprCollSeq(pParse, p);
1438b3bf556eSdanielk1977     if( pColl ){
143917435752Sdrh       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
14400202b29eSdanielk1977     }
144122f70c32Sdrh   }
14427d10d5a6Sdrh }
14437d10d5a6Sdrh 
14447d10d5a6Sdrh /*
14457d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes
14467d10d5a6Sdrh ** the result set of that SELECT.
14477d10d5a6Sdrh */
14487d10d5a6Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
14497d10d5a6Sdrh   Table *pTab;
14507d10d5a6Sdrh   sqlite3 *db = pParse->db;
14517d10d5a6Sdrh   int savedFlags;
14527d10d5a6Sdrh 
14537d10d5a6Sdrh   savedFlags = db->flags;
14547d10d5a6Sdrh   db->flags &= ~SQLITE_FullColNames;
14557d10d5a6Sdrh   db->flags |= SQLITE_ShortColNames;
14567d10d5a6Sdrh   sqlite3SelectPrep(pParse, pSelect, 0);
14577d10d5a6Sdrh   if( pParse->nErr ) return 0;
14587d10d5a6Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
14597d10d5a6Sdrh   db->flags = savedFlags;
14607d10d5a6Sdrh   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
14617d10d5a6Sdrh   if( pTab==0 ){
14627d10d5a6Sdrh     return 0;
14637d10d5a6Sdrh   }
1464373cc2ddSdrh   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
1465b2468954Sdrh   ** is disabled */
1466373cc2ddSdrh   assert( db->lookaside.bEnabled==0 );
14677d10d5a6Sdrh   pTab->nRef = 1;
14687d10d5a6Sdrh   pTab->zName = 0;
14691ea87012Sdrh   pTab->nRowEst = 1000000;
14707d10d5a6Sdrh   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
14717d10d5a6Sdrh   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
147222f70c32Sdrh   pTab->iPKey = -1;
14737ce72f69Sdrh   if( db->mallocFailed ){
14741feeaed2Sdan     sqlite3DeleteTable(db, pTab);
14757ce72f69Sdrh     return 0;
14767ce72f69Sdrh   }
147722f70c32Sdrh   return pTab;
147822f70c32Sdrh }
147922f70c32Sdrh 
148022f70c32Sdrh /*
1481d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1482d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1483d8bc7086Sdrh */
14844adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1485d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1486d8bc7086Sdrh   if( v==0 ){
14874adee20fSdanielk1977     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1488949f9cd5Sdrh #ifndef SQLITE_OMIT_TRACE
1489949f9cd5Sdrh     if( v ){
1490949f9cd5Sdrh       sqlite3VdbeAddOp0(v, OP_Trace);
1491949f9cd5Sdrh     }
1492949f9cd5Sdrh #endif
1493d8bc7086Sdrh   }
1494d8bc7086Sdrh   return v;
1495d8bc7086Sdrh }
1496d8bc7086Sdrh 
149715007a99Sdrh 
1498d8bc7086Sdrh /*
14997b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
1500ec7429aeSdrh ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
15017b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
1502a2dc3b1aSdanielk1977 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1503a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute
1504a2dc3b1aSdanielk1977 ** the limit and offset.  If there is no limit and/or offset, then
1505a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative.
15067b58daeaSdrh **
1507d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if
1508ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset.  iLimit and
15097b58daeaSdrh ** iOffset should have been preset to appropriate default values
15107b58daeaSdrh ** (usually but not always -1) prior to calling this routine.
1511ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
15127b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
15137b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
15147b58daeaSdrh ** SELECT statements.
15157b58daeaSdrh */
1516ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
151702afc861Sdrh   Vdbe *v = 0;
151802afc861Sdrh   int iLimit = 0;
151915007a99Sdrh   int iOffset;
15209b918ed1Sdrh   int addr1, n;
15210acb7e48Sdrh   if( p->iLimit ) return;
152215007a99Sdrh 
15237b58daeaSdrh   /*
15247b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
15257b58daeaSdrh   ** contraversy about what the correct behavior should be.
15267b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
15277b58daeaSdrh   ** no rows.
15287b58daeaSdrh   */
1529ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
1530373cc2ddSdrh   assert( p->pOffset==0 || p->pLimit!=0 );
1531a2dc3b1aSdanielk1977   if( p->pLimit ){
15320a07c107Sdrh     p->iLimit = iLimit = ++pParse->nMem;
153315007a99Sdrh     v = sqlite3GetVdbe(pParse);
1534373cc2ddSdrh     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
15359b918ed1Sdrh     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
15369b918ed1Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
15379b918ed1Sdrh       VdbeComment((v, "LIMIT counter"));
1538456e4e4fSdrh       if( n==0 ){
1539456e4e4fSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
154095aa47b1Sdrh       }else{
154195aa47b1Sdrh         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
15429b918ed1Sdrh       }
15439b918ed1Sdrh     }else{
1544b7654111Sdrh       sqlite3ExprCode(pParse, p->pLimit, iLimit);
1545b7654111Sdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
1546d4e70ebdSdrh       VdbeComment((v, "LIMIT counter"));
15473c84ddffSdrh       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
15489b918ed1Sdrh     }
1549a2dc3b1aSdanielk1977     if( p->pOffset ){
15500a07c107Sdrh       p->iOffset = iOffset = ++pParse->nMem;
1551b7654111Sdrh       pParse->nMem++;   /* Allocate an extra register for limit+offset */
1552b7654111Sdrh       sqlite3ExprCode(pParse, p->pOffset, iOffset);
1553b7654111Sdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
1554d4e70ebdSdrh       VdbeComment((v, "OFFSET counter"));
15553c84ddffSdrh       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
1556b7654111Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
155715007a99Sdrh       sqlite3VdbeJumpHere(v, addr1);
1558b7654111Sdrh       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
1559d4e70ebdSdrh       VdbeComment((v, "LIMIT+OFFSET"));
1560b7654111Sdrh       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
1561b7654111Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
1562b7654111Sdrh       sqlite3VdbeJumpHere(v, addr1);
1563b7654111Sdrh     }
1564d59ba6ceSdrh   }
15657b58daeaSdrh }
15667b58daeaSdrh 
1567b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1568fbc4ee7bSdrh /*
1569fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
1570fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
1571fbc4ee7bSdrh ** the column has no default collating sequence.
1572fbc4ee7bSdrh **
1573fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
1574fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
1575fbc4ee7bSdrh */
1576dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1577fbc4ee7bSdrh   CollSeq *pRet;
1578dc1bdc4fSdanielk1977   if( p->pPrior ){
1579dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1580fbc4ee7bSdrh   }else{
1581fbc4ee7bSdrh     pRet = 0;
1582dc1bdc4fSdanielk1977   }
158310c081adSdrh   assert( iCol>=0 );
158410c081adSdrh   if( pRet==0 && iCol<p->pEList->nExpr ){
1585dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1586dc1bdc4fSdanielk1977   }
1587dc1bdc4fSdanielk1977   return pRet;
1588d3d39e93Sdrh }
1589b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1590d3d39e93Sdrh 
1591b21e7c70Sdrh /* Forward reference */
1592b21e7c70Sdrh static int multiSelectOrderBy(
1593b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
1594b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
1595a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
1596b21e7c70Sdrh );
1597b21e7c70Sdrh 
1598b21e7c70Sdrh 
1599b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1600d3d39e93Sdrh /*
160116ee60ffSdrh ** This routine is called to process a compound query form from
160216ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
160316ee60ffSdrh ** INTERSECT
1604c926afbcSdrh **
1605e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1606e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1607e78e8284Sdrh ** in which case this routine will be called recursively.
1608e78e8284Sdrh **
1609e78e8284Sdrh ** The results of the total query are to be written into a destination
1610e78e8284Sdrh ** of type eDest with parameter iParm.
1611e78e8284Sdrh **
1612e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1613e78e8284Sdrh **
1614e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1615e78e8284Sdrh **
1616e78e8284Sdrh ** This statement is parsed up as follows:
1617e78e8284Sdrh **
1618e78e8284Sdrh **     SELECT c FROM t3
1619e78e8284Sdrh **      |
1620e78e8284Sdrh **      `----->  SELECT b FROM t2
1621e78e8284Sdrh **                |
16224b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1623e78e8284Sdrh **
1624e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1625e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1626e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1627e78e8284Sdrh **
1628e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1629e78e8284Sdrh ** individual selects always group from left to right.
163082c3d636Sdrh */
163184ac9d02Sdanielk1977 static int multiSelect(
1632fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
1633fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
1634a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
163584ac9d02Sdanielk1977 ){
163684ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
163710e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
163810e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
16391013c932Sdrh   SelectDest dest;      /* Alternative data destination */
1640eca7e01aSdanielk1977   Select *pDelete = 0;  /* Chain of simple selects to delete */
1641633e6d57Sdrh   sqlite3 *db;          /* Database connection */
16427f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN
16437f61e92cSdan   int iSub1;            /* EQP id of left-hand query */
16447f61e92cSdan   int iSub2;            /* EQP id of right-hand query */
16457f61e92cSdan #endif
164682c3d636Sdrh 
16477b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1648fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
164982c3d636Sdrh   */
1650701bb3b4Sdrh   assert( p && p->pPrior );  /* Calling function guarantees this much */
1651633e6d57Sdrh   db = pParse->db;
1652d8bc7086Sdrh   pPrior = p->pPrior;
16530342b1f5Sdrh   assert( pPrior->pRightmost!=pPrior );
16540342b1f5Sdrh   assert( pPrior->pRightmost==p->pRightmost );
1655bc10377aSdrh   dest = *pDest;
1656d8bc7086Sdrh   if( pPrior->pOrderBy ){
16574adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1658da93d238Sdrh       selectOpName(p->op));
165984ac9d02Sdanielk1977     rc = 1;
166084ac9d02Sdanielk1977     goto multi_select_end;
166182c3d636Sdrh   }
1662a2dc3b1aSdanielk1977   if( pPrior->pLimit ){
16634adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
16647b58daeaSdrh       selectOpName(p->op));
166584ac9d02Sdanielk1977     rc = 1;
166684ac9d02Sdanielk1977     goto multi_select_end;
16677b58daeaSdrh   }
166882c3d636Sdrh 
16694adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
1670701bb3b4Sdrh   assert( v!=0 );  /* The VDBE already created by calling function */
1671d8bc7086Sdrh 
16721cc3d75fSdrh   /* Create the destination temporary table if necessary
16731cc3d75fSdrh   */
16746c8c8ce0Sdanielk1977   if( dest.eDest==SRT_EphemTab ){
1675b4964b72Sdanielk1977     assert( p->pEList );
16762b596da8Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
1677d4187c71Sdrh     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
16786c8c8ce0Sdanielk1977     dest.eDest = SRT_Table;
16791cc3d75fSdrh   }
16801cc3d75fSdrh 
1681f6e369a1Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
1682f6e369a1Sdrh   ** in their result sets.
1683f6e369a1Sdrh   */
1684f6e369a1Sdrh   assert( p->pEList && pPrior->pEList );
1685f6e369a1Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
16867b113babSdrh     if( p->selFlags & SF_Values ){
16877b113babSdrh       sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
16887b113babSdrh     }else{
1689f6e369a1Sdrh       sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
1690f6e369a1Sdrh         " do not have the same number of result columns", selectOpName(p->op));
16917b113babSdrh     }
1692f6e369a1Sdrh     rc = 1;
1693f6e369a1Sdrh     goto multi_select_end;
1694f6e369a1Sdrh   }
1695f6e369a1Sdrh 
1696a9671a22Sdrh   /* Compound SELECTs that have an ORDER BY clause are handled separately.
1697a9671a22Sdrh   */
1698f6e369a1Sdrh   if( p->pOrderBy ){
1699a9671a22Sdrh     return multiSelectOrderBy(pParse, p, pDest);
1700f6e369a1Sdrh   }
1701f6e369a1Sdrh 
1702f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1703d8bc7086Sdrh   */
170482c3d636Sdrh   switch( p->op ){
1705f46f905aSdrh     case TK_ALL: {
1706ec7429aeSdrh       int addr = 0;
170795aa47b1Sdrh       int nLimit;
1708a2dc3b1aSdanielk1977       assert( !pPrior->pLimit );
1709a2dc3b1aSdanielk1977       pPrior->pLimit = p->pLimit;
1710a2dc3b1aSdanielk1977       pPrior->pOffset = p->pOffset;
17117f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
17127d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &dest);
1713ad68cb6bSdanielk1977       p->pLimit = 0;
1714ad68cb6bSdanielk1977       p->pOffset = 0;
171584ac9d02Sdanielk1977       if( rc ){
171684ac9d02Sdanielk1977         goto multi_select_end;
171784ac9d02Sdanielk1977       }
1718f46f905aSdrh       p->pPrior = 0;
17197b58daeaSdrh       p->iLimit = pPrior->iLimit;
17207b58daeaSdrh       p->iOffset = pPrior->iOffset;
172192b01d53Sdrh       if( p->iLimit ){
17223c84ddffSdrh         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
1723d4e70ebdSdrh         VdbeComment((v, "Jump ahead if LIMIT reached"));
1724ec7429aeSdrh       }
17257f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
17267d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &dest);
1727373cc2ddSdrh       testcase( rc!=SQLITE_OK );
1728eca7e01aSdanielk1977       pDelete = p->pPrior;
1729f46f905aSdrh       p->pPrior = pPrior;
173095aa47b1Sdrh       p->nSelectRow += pPrior->nSelectRow;
173195aa47b1Sdrh       if( pPrior->pLimit
173295aa47b1Sdrh        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
173395aa47b1Sdrh        && p->nSelectRow > (double)nLimit
173495aa47b1Sdrh       ){
173595aa47b1Sdrh         p->nSelectRow = (double)nLimit;
173695aa47b1Sdrh       }
1737ec7429aeSdrh       if( addr ){
1738ec7429aeSdrh         sqlite3VdbeJumpHere(v, addr);
1739ec7429aeSdrh       }
1740f46f905aSdrh       break;
1741f46f905aSdrh     }
174282c3d636Sdrh     case TK_EXCEPT:
174382c3d636Sdrh     case TK_UNION: {
1744d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1745ea678832Sdrh       u8 op = 0;       /* One of the SRT_ operations to apply to self */
1746d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
1747a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
1748dc1bdc4fSdanielk1977       int addr;
17496c8c8ce0Sdanielk1977       SelectDest uniondest;
175082c3d636Sdrh 
1751373cc2ddSdrh       testcase( p->op==TK_EXCEPT );
1752373cc2ddSdrh       testcase( p->op==TK_UNION );
175393a960a0Sdrh       priorOp = SRT_Union;
1754e2f02bacSdrh       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
1755d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1756c926afbcSdrh         ** right.
1757d8bc7086Sdrh         */
1758e2f02bacSdrh         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
1759e2f02bacSdrh                                      ** of a 3-way or more compound */
1760e2f02bacSdrh         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
1761e2f02bacSdrh         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
17622b596da8Sdrh         unionTab = dest.iSDParm;
176382c3d636Sdrh       }else{
1764d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1765d8bc7086Sdrh         ** intermediate results.
1766d8bc7086Sdrh         */
176782c3d636Sdrh         unionTab = pParse->nTab++;
176893a960a0Sdrh         assert( p->pOrderBy==0 );
176966a5167bSdrh         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
1770b9bb7c18Sdrh         assert( p->addrOpenEphm[0] == -1 );
1771b9bb7c18Sdrh         p->addrOpenEphm[0] = addr;
17727d10d5a6Sdrh         p->pRightmost->selFlags |= SF_UsesEphemeral;
177384ac9d02Sdanielk1977         assert( p->pEList );
1774d8bc7086Sdrh       }
1775d8bc7086Sdrh 
1776d8bc7086Sdrh       /* Code the SELECT statements to our left
1777d8bc7086Sdrh       */
1778b3bce662Sdanielk1977       assert( !pPrior->pOrderBy );
17791013c932Sdrh       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
17807f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
17817d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &uniondest);
178284ac9d02Sdanielk1977       if( rc ){
178384ac9d02Sdanielk1977         goto multi_select_end;
178484ac9d02Sdanielk1977       }
1785d8bc7086Sdrh 
1786d8bc7086Sdrh       /* Code the current SELECT statement
1787d8bc7086Sdrh       */
17884cfb22f7Sdrh       if( p->op==TK_EXCEPT ){
17894cfb22f7Sdrh         op = SRT_Except;
17904cfb22f7Sdrh       }else{
17914cfb22f7Sdrh         assert( p->op==TK_UNION );
17924cfb22f7Sdrh         op = SRT_Union;
1793d8bc7086Sdrh       }
179482c3d636Sdrh       p->pPrior = 0;
1795a2dc3b1aSdanielk1977       pLimit = p->pLimit;
1796a2dc3b1aSdanielk1977       p->pLimit = 0;
1797a2dc3b1aSdanielk1977       pOffset = p->pOffset;
1798a2dc3b1aSdanielk1977       p->pOffset = 0;
17996c8c8ce0Sdanielk1977       uniondest.eDest = op;
18007f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
18017d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &uniondest);
1802373cc2ddSdrh       testcase( rc!=SQLITE_OK );
18035bd1bf2eSdrh       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
18045bd1bf2eSdrh       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
1805633e6d57Sdrh       sqlite3ExprListDelete(db, p->pOrderBy);
1806eca7e01aSdanielk1977       pDelete = p->pPrior;
180782c3d636Sdrh       p->pPrior = pPrior;
1808a9671a22Sdrh       p->pOrderBy = 0;
180995aa47b1Sdrh       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
1810633e6d57Sdrh       sqlite3ExprDelete(db, p->pLimit);
1811a2dc3b1aSdanielk1977       p->pLimit = pLimit;
1812a2dc3b1aSdanielk1977       p->pOffset = pOffset;
181392b01d53Sdrh       p->iLimit = 0;
181492b01d53Sdrh       p->iOffset = 0;
1815d8bc7086Sdrh 
1816d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1817d8bc7086Sdrh       ** it is that we currently need.
1818d8bc7086Sdrh       */
18192b596da8Sdrh       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
1820373cc2ddSdrh       if( dest.eDest!=priorOp ){
18216b56344dSdrh         int iCont, iBreak, iStart;
182282c3d636Sdrh         assert( p->pEList );
18237d10d5a6Sdrh         if( dest.eDest==SRT_Output ){
182492378253Sdrh           Select *pFirst = p;
182592378253Sdrh           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
182692378253Sdrh           generateColumnNames(pParse, 0, pFirst->pEList);
182741202ccaSdrh         }
18284adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
18294adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
1830ec7429aeSdrh         computeLimitRegisters(pParse, p, iBreak);
183166a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
18324adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
1833d2b3e23bSdrh         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
1834e8e4af76Sdrh                         0, 0, &dest, iCont, iBreak);
18354adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
183666a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
18374adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
183866a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
183982c3d636Sdrh       }
184082c3d636Sdrh       break;
184182c3d636Sdrh     }
1842373cc2ddSdrh     default: assert( p->op==TK_INTERSECT ); {
184382c3d636Sdrh       int tab1, tab2;
18446b56344dSdrh       int iCont, iBreak, iStart;
1845a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset;
1846dc1bdc4fSdanielk1977       int addr;
18471013c932Sdrh       SelectDest intersectdest;
18489cbf3425Sdrh       int r1;
184982c3d636Sdrh 
1850d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
18516206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
1852d8bc7086Sdrh       ** by allocating the tables we will need.
1853d8bc7086Sdrh       */
185482c3d636Sdrh       tab1 = pParse->nTab++;
185582c3d636Sdrh       tab2 = pParse->nTab++;
185693a960a0Sdrh       assert( p->pOrderBy==0 );
1857dc1bdc4fSdanielk1977 
185866a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
1859b9bb7c18Sdrh       assert( p->addrOpenEphm[0] == -1 );
1860b9bb7c18Sdrh       p->addrOpenEphm[0] = addr;
18617d10d5a6Sdrh       p->pRightmost->selFlags |= SF_UsesEphemeral;
186284ac9d02Sdanielk1977       assert( p->pEList );
1863d8bc7086Sdrh 
1864d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1865d8bc7086Sdrh       */
18661013c932Sdrh       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
18677f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
18687d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &intersectdest);
186984ac9d02Sdanielk1977       if( rc ){
187084ac9d02Sdanielk1977         goto multi_select_end;
187184ac9d02Sdanielk1977       }
1872d8bc7086Sdrh 
1873d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1874d8bc7086Sdrh       */
187566a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
1876b9bb7c18Sdrh       assert( p->addrOpenEphm[1] == -1 );
1877b9bb7c18Sdrh       p->addrOpenEphm[1] = addr;
187882c3d636Sdrh       p->pPrior = 0;
1879a2dc3b1aSdanielk1977       pLimit = p->pLimit;
1880a2dc3b1aSdanielk1977       p->pLimit = 0;
1881a2dc3b1aSdanielk1977       pOffset = p->pOffset;
1882a2dc3b1aSdanielk1977       p->pOffset = 0;
18832b596da8Sdrh       intersectdest.iSDParm = tab2;
18847f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
18857d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &intersectdest);
1886373cc2ddSdrh       testcase( rc!=SQLITE_OK );
1887eca7e01aSdanielk1977       pDelete = p->pPrior;
188882c3d636Sdrh       p->pPrior = pPrior;
188995aa47b1Sdrh       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
1890633e6d57Sdrh       sqlite3ExprDelete(db, p->pLimit);
1891a2dc3b1aSdanielk1977       p->pLimit = pLimit;
1892a2dc3b1aSdanielk1977       p->pOffset = pOffset;
1893d8bc7086Sdrh 
1894d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1895d8bc7086Sdrh       ** tables.
1896d8bc7086Sdrh       */
189782c3d636Sdrh       assert( p->pEList );
18987d10d5a6Sdrh       if( dest.eDest==SRT_Output ){
189992378253Sdrh         Select *pFirst = p;
190092378253Sdrh         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
190192378253Sdrh         generateColumnNames(pParse, 0, pFirst->pEList);
190241202ccaSdrh       }
19034adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
19044adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
1905ec7429aeSdrh       computeLimitRegisters(pParse, p, iBreak);
190666a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
19079cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
19089cbf3425Sdrh       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
19098cff69dfSdrh       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
19109cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
1911d2b3e23bSdrh       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
1912e8e4af76Sdrh                       0, 0, &dest, iCont, iBreak);
19134adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
191466a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
19154adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
191666a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
191766a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
191882c3d636Sdrh       break;
191982c3d636Sdrh     }
192082c3d636Sdrh   }
19218cdbf836Sdrh 
19227f61e92cSdan   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
19237f61e92cSdan 
1924a9671a22Sdrh   /* Compute collating sequences used by
1925a9671a22Sdrh   ** temporary tables needed to implement the compound select.
1926a9671a22Sdrh   ** Attach the KeyInfo structure to all temporary tables.
19278cdbf836Sdrh   **
19288cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
19298cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
19308cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
19318cdbf836Sdrh   ** no temp tables are required.
1932fbc4ee7bSdrh   */
19337d10d5a6Sdrh   if( p->selFlags & SF_UsesEphemeral ){
1934fbc4ee7bSdrh     int i;                        /* Loop counter */
1935fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
19360342b1f5Sdrh     Select *pLoop;                /* For looping through SELECT statements */
1937f68d7d17Sdrh     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
193893a960a0Sdrh     int nCol;                     /* Number of columns in result set */
1939fbc4ee7bSdrh 
19400342b1f5Sdrh     assert( p->pRightmost==p );
194193a960a0Sdrh     nCol = p->pEList->nExpr;
1942633e6d57Sdrh     pKeyInfo = sqlite3DbMallocZero(db,
1943a9671a22Sdrh                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
1944dc1bdc4fSdanielk1977     if( !pKeyInfo ){
1945dc1bdc4fSdanielk1977       rc = SQLITE_NOMEM;
1946dc1bdc4fSdanielk1977       goto multi_select_end;
1947dc1bdc4fSdanielk1977     }
1948dc1bdc4fSdanielk1977 
1949633e6d57Sdrh     pKeyInfo->enc = ENC(db);
1950ea678832Sdrh     pKeyInfo->nField = (u16)nCol;
1951dc1bdc4fSdanielk1977 
19520342b1f5Sdrh     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
19530342b1f5Sdrh       *apColl = multiSelectCollSeq(pParse, p, i);
19540342b1f5Sdrh       if( 0==*apColl ){
1955633e6d57Sdrh         *apColl = db->pDfltColl;
1956dc1bdc4fSdanielk1977       }
1957dc1bdc4fSdanielk1977     }
1958e1a022e4Sdrh     pKeyInfo->aSortOrder = (u8*)apColl;
1959dc1bdc4fSdanielk1977 
19600342b1f5Sdrh     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
19610342b1f5Sdrh       for(i=0; i<2; i++){
1962b9bb7c18Sdrh         int addr = pLoop->addrOpenEphm[i];
19630342b1f5Sdrh         if( addr<0 ){
19640342b1f5Sdrh           /* If [0] is unused then [1] is also unused.  So we can
19650342b1f5Sdrh           ** always safely abort as soon as the first unused slot is found */
1966b9bb7c18Sdrh           assert( pLoop->addrOpenEphm[1]<0 );
19670342b1f5Sdrh           break;
19680342b1f5Sdrh         }
19690342b1f5Sdrh         sqlite3VdbeChangeP2(v, addr, nCol);
197066a5167bSdrh         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
19710ee5a1e7Sdrh         pLoop->addrOpenEphm[i] = -1;
19720342b1f5Sdrh       }
1973dc1bdc4fSdanielk1977     }
1974633e6d57Sdrh     sqlite3DbFree(db, pKeyInfo);
1975dc1bdc4fSdanielk1977   }
1976dc1bdc4fSdanielk1977 
1977dc1bdc4fSdanielk1977 multi_select_end:
19782b596da8Sdrh   pDest->iSdst = dest.iSdst;
19792b596da8Sdrh   pDest->nSdst = dest.nSdst;
1980633e6d57Sdrh   sqlite3SelectDelete(db, pDelete);
198184ac9d02Sdanielk1977   return rc;
19822282792aSdrh }
1983b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
19842282792aSdrh 
1985b21e7c70Sdrh /*
1986b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a
1987b21e7c70Sdrh ** SELECT statment.
19880acb7e48Sdrh **
19892b596da8Sdrh ** The data to be output is contained in pIn->iSdst.  There are
19902b596da8Sdrh ** pIn->nSdst columns to be output.  pDest is where the output should
19910acb7e48Sdrh ** be sent.
19920acb7e48Sdrh **
19930acb7e48Sdrh ** regReturn is the number of the register holding the subroutine
19940acb7e48Sdrh ** return address.
19950acb7e48Sdrh **
1996f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that
19970acb7e48Sdrh ** records the previous output.  mem[regPrev] is a flag that is false
19980acb7e48Sdrh ** if there has been no previous output.  If regPrev>0 then code is
19990acb7e48Sdrh ** generated to suppress duplicates.  pKeyInfo is used for comparing
20000acb7e48Sdrh ** keys.
20010acb7e48Sdrh **
20020acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to
20030acb7e48Sdrh ** iBreak.
2004b21e7c70Sdrh */
20050acb7e48Sdrh static int generateOutputSubroutine(
200692b01d53Sdrh   Parse *pParse,          /* Parsing context */
200792b01d53Sdrh   Select *p,              /* The SELECT statement */
200892b01d53Sdrh   SelectDest *pIn,        /* Coroutine supplying data */
200992b01d53Sdrh   SelectDest *pDest,      /* Where to send the data */
201092b01d53Sdrh   int regReturn,          /* The return address register */
20110acb7e48Sdrh   int regPrev,            /* Previous result register.  No uniqueness if 0 */
20120acb7e48Sdrh   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
20130acb7e48Sdrh   int p4type,             /* The p4 type for pKeyInfo */
201492b01d53Sdrh   int iBreak              /* Jump here if we hit the LIMIT */
2015b21e7c70Sdrh ){
2016b21e7c70Sdrh   Vdbe *v = pParse->pVdbe;
201792b01d53Sdrh   int iContinue;
201892b01d53Sdrh   int addr;
2019b21e7c70Sdrh 
202092b01d53Sdrh   addr = sqlite3VdbeCurrentAddr(v);
202192b01d53Sdrh   iContinue = sqlite3VdbeMakeLabel(v);
20220acb7e48Sdrh 
20230acb7e48Sdrh   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
20240acb7e48Sdrh   */
20250acb7e48Sdrh   if( regPrev ){
20260acb7e48Sdrh     int j1, j2;
2027ec86c724Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
20282b596da8Sdrh     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
20290acb7e48Sdrh                               (char*)pKeyInfo, p4type);
20300acb7e48Sdrh     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
20310acb7e48Sdrh     sqlite3VdbeJumpHere(v, j1);
2032e8e4af76Sdrh     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
2033ec86c724Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
20340acb7e48Sdrh   }
20351f9caa41Sdanielk1977   if( pParse->db->mallocFailed ) return 0;
20360acb7e48Sdrh 
2037d5578433Smistachkin   /* Suppress the first OFFSET entries if there is an OFFSET clause
20380acb7e48Sdrh   */
203992b01d53Sdrh   codeOffset(v, p, iContinue);
2040b21e7c70Sdrh 
2041b21e7c70Sdrh   switch( pDest->eDest ){
2042b21e7c70Sdrh     /* Store the result as data using a unique key.
2043b21e7c70Sdrh     */
2044b21e7c70Sdrh     case SRT_Table:
2045b21e7c70Sdrh     case SRT_EphemTab: {
2046b21e7c70Sdrh       int r1 = sqlite3GetTempReg(pParse);
2047b21e7c70Sdrh       int r2 = sqlite3GetTempReg(pParse);
2048373cc2ddSdrh       testcase( pDest->eDest==SRT_Table );
2049373cc2ddSdrh       testcase( pDest->eDest==SRT_EphemTab );
20502b596da8Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
20512b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
20522b596da8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
2053b21e7c70Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
2054b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r2);
2055b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
2056b21e7c70Sdrh       break;
2057b21e7c70Sdrh     }
2058b21e7c70Sdrh 
2059b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY
2060b21e7c70Sdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
2061b21e7c70Sdrh     ** then there should be a single item on the stack.  Write this
2062b21e7c70Sdrh     ** item into the set table with bogus data.
2063b21e7c70Sdrh     */
2064b21e7c70Sdrh     case SRT_Set: {
20656fccc35aSdrh       int r1;
20662b596da8Sdrh       assert( pIn->nSdst==1 );
2067634d81deSdrh       pDest->affSdst =
20682b596da8Sdrh          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
2069b21e7c70Sdrh       r1 = sqlite3GetTempReg(pParse);
2070634d81deSdrh       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
20712b596da8Sdrh       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
20722b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
2073b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
2074b21e7c70Sdrh       break;
2075b21e7c70Sdrh     }
2076b21e7c70Sdrh 
207785e9e22bSdrh #if 0  /* Never occurs on an ORDER BY query */
2078b21e7c70Sdrh     /* If any row exist in the result set, record that fact and abort.
2079b21e7c70Sdrh     */
2080b21e7c70Sdrh     case SRT_Exists: {
20812b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
2082b21e7c70Sdrh       /* The LIMIT clause will terminate the loop for us */
2083b21e7c70Sdrh       break;
2084b21e7c70Sdrh     }
208585e9e22bSdrh #endif
2086b21e7c70Sdrh 
2087b21e7c70Sdrh     /* If this is a scalar select that is part of an expression, then
2088b21e7c70Sdrh     ** store the results in the appropriate memory cell and break out
2089b21e7c70Sdrh     ** of the scan loop.
2090b21e7c70Sdrh     */
2091b21e7c70Sdrh     case SRT_Mem: {
20922b596da8Sdrh       assert( pIn->nSdst==1 );
20932b596da8Sdrh       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
2094b21e7c70Sdrh       /* The LIMIT clause will jump out of the loop for us */
2095b21e7c70Sdrh       break;
2096b21e7c70Sdrh     }
2097b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
2098b21e7c70Sdrh 
20997d10d5a6Sdrh     /* The results are stored in a sequence of registers
21002b596da8Sdrh     ** starting at pDest->iSdst.  Then the co-routine yields.
2101b21e7c70Sdrh     */
210292b01d53Sdrh     case SRT_Coroutine: {
21032b596da8Sdrh       if( pDest->iSdst==0 ){
21042b596da8Sdrh         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
21052b596da8Sdrh         pDest->nSdst = pIn->nSdst;
2106b21e7c70Sdrh       }
21072b596da8Sdrh       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
21082b596da8Sdrh       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
210992b01d53Sdrh       break;
211092b01d53Sdrh     }
211192b01d53Sdrh 
2112ccfcbceaSdrh     /* If none of the above, then the result destination must be
2113ccfcbceaSdrh     ** SRT_Output.  This routine is never called with any other
2114ccfcbceaSdrh     ** destination other than the ones handled above or SRT_Output.
2115ccfcbceaSdrh     **
2116ccfcbceaSdrh     ** For SRT_Output, results are stored in a sequence of registers.
2117ccfcbceaSdrh     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
2118ccfcbceaSdrh     ** return the next row of result.
21197d10d5a6Sdrh     */
2120ccfcbceaSdrh     default: {
2121ccfcbceaSdrh       assert( pDest->eDest==SRT_Output );
21222b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
21232b596da8Sdrh       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
2124b21e7c70Sdrh       break;
2125b21e7c70Sdrh     }
2126b21e7c70Sdrh   }
212792b01d53Sdrh 
212892b01d53Sdrh   /* Jump to the end of the loop if the LIMIT is reached.
212992b01d53Sdrh   */
213092b01d53Sdrh   if( p->iLimit ){
21319b918ed1Sdrh     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
213292b01d53Sdrh   }
213392b01d53Sdrh 
213492b01d53Sdrh   /* Generate the subroutine return
213592b01d53Sdrh   */
21360acb7e48Sdrh   sqlite3VdbeResolveLabel(v, iContinue);
213792b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
213892b01d53Sdrh 
213992b01d53Sdrh   return addr;
2140b21e7c70Sdrh }
2141b21e7c70Sdrh 
2142b21e7c70Sdrh /*
2143b21e7c70Sdrh ** Alternative compound select code generator for cases when there
2144b21e7c70Sdrh ** is an ORDER BY clause.
2145b21e7c70Sdrh **
2146b21e7c70Sdrh ** We assume a query of the following form:
2147b21e7c70Sdrh **
2148b21e7c70Sdrh **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
2149b21e7c70Sdrh **
2150b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
2151b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as
2152b21e7c70Sdrh ** co-routines.  Then run the co-routines in parallel and merge the results
2153b21e7c70Sdrh ** into the output.  In addition to the two coroutines (called selectA and
2154b21e7c70Sdrh ** selectB) there are 7 subroutines:
2155b21e7c70Sdrh **
2156b21e7c70Sdrh **    outA:    Move the output of the selectA coroutine into the output
2157b21e7c70Sdrh **             of the compound query.
2158b21e7c70Sdrh **
2159b21e7c70Sdrh **    outB:    Move the output of the selectB coroutine into the output
2160b21e7c70Sdrh **             of the compound query.  (Only generated for UNION and
2161b21e7c70Sdrh **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
2162b21e7c70Sdrh **             appears only in B.)
2163b21e7c70Sdrh **
2164b21e7c70Sdrh **    AltB:    Called when there is data from both coroutines and A<B.
2165b21e7c70Sdrh **
2166b21e7c70Sdrh **    AeqB:    Called when there is data from both coroutines and A==B.
2167b21e7c70Sdrh **
2168b21e7c70Sdrh **    AgtB:    Called when there is data from both coroutines and A>B.
2169b21e7c70Sdrh **
2170b21e7c70Sdrh **    EofA:    Called when data is exhausted from selectA.
2171b21e7c70Sdrh **
2172b21e7c70Sdrh **    EofB:    Called when data is exhausted from selectB.
2173b21e7c70Sdrh **
2174b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which
2175b21e7c70Sdrh ** <operator> is used:
2176b21e7c70Sdrh **
2177b21e7c70Sdrh **
2178b21e7c70Sdrh **             UNION ALL         UNION            EXCEPT          INTERSECT
2179b21e7c70Sdrh **          -------------  -----------------  --------------  -----------------
2180b21e7c70Sdrh **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
2181b21e7c70Sdrh **
21820acb7e48Sdrh **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
2183b21e7c70Sdrh **
2184b21e7c70Sdrh **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
2185b21e7c70Sdrh **
21860acb7e48Sdrh **   EofA:   outB, nextB      outB, nextB          halt             halt
2187b21e7c70Sdrh **
21880acb7e48Sdrh **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
21890acb7e48Sdrh **
21900acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
21910acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes
21920acb7e48Sdrh ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
21930acb7e48Sdrh ** following nextX causes a jump to the end of the select processing.
21940acb7e48Sdrh **
21950acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
21960acb7e48Sdrh ** within the output subroutine.  The regPrev register set holds the previously
21970acb7e48Sdrh ** output value.  A comparison is made against this value and the output
21980acb7e48Sdrh ** is skipped if the next results would be the same as the previous.
2199b21e7c70Sdrh **
2200b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven
2201b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom.  Like this:
2202b21e7c70Sdrh **
2203b21e7c70Sdrh **          goto Init
2204b21e7c70Sdrh **     coA: coroutine for left query (A)
2205b21e7c70Sdrh **     coB: coroutine for right query (B)
2206b21e7c70Sdrh **    outA: output one row of A
2207b21e7c70Sdrh **    outB: output one row of B (UNION and UNION ALL only)
2208b21e7c70Sdrh **    EofA: ...
2209b21e7c70Sdrh **    EofB: ...
2210b21e7c70Sdrh **    AltB: ...
2211b21e7c70Sdrh **    AeqB: ...
2212b21e7c70Sdrh **    AgtB: ...
2213b21e7c70Sdrh **    Init: initialize coroutine registers
2214b21e7c70Sdrh **          yield coA
2215b21e7c70Sdrh **          if eof(A) goto EofA
2216b21e7c70Sdrh **          yield coB
2217b21e7c70Sdrh **          if eof(B) goto EofB
2218b21e7c70Sdrh **    Cmpr: Compare A, B
2219b21e7c70Sdrh **          Jump AltB, AeqB, AgtB
2220b21e7c70Sdrh **     End: ...
2221b21e7c70Sdrh **
2222b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
2223b21e7c70Sdrh ** actually called using Gosub and they do not Return.  EofA and EofB loop
2224b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
2225b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB.
2226b21e7c70Sdrh */
2227de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
2228b21e7c70Sdrh static int multiSelectOrderBy(
2229b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
2230b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
2231a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
2232b21e7c70Sdrh ){
22330acb7e48Sdrh   int i, j;             /* Loop counters */
2234b21e7c70Sdrh   Select *pPrior;       /* Another SELECT immediately to our left */
2235b21e7c70Sdrh   Vdbe *v;              /* Generate code to this VDBE */
2236b21e7c70Sdrh   SelectDest destA;     /* Destination for coroutine A */
2237b21e7c70Sdrh   SelectDest destB;     /* Destination for coroutine B */
223892b01d53Sdrh   int regAddrA;         /* Address register for select-A coroutine */
223992b01d53Sdrh   int regEofA;          /* Flag to indicate when select-A is complete */
224092b01d53Sdrh   int regAddrB;         /* Address register for select-B coroutine */
224192b01d53Sdrh   int regEofB;          /* Flag to indicate when select-B is complete */
224292b01d53Sdrh   int addrSelectA;      /* Address of the select-A coroutine */
224392b01d53Sdrh   int addrSelectB;      /* Address of the select-B coroutine */
224492b01d53Sdrh   int regOutA;          /* Address register for the output-A subroutine */
224592b01d53Sdrh   int regOutB;          /* Address register for the output-B subroutine */
224692b01d53Sdrh   int addrOutA;         /* Address of the output-A subroutine */
2247b27b7f5dSdrh   int addrOutB = 0;     /* Address of the output-B subroutine */
224892b01d53Sdrh   int addrEofA;         /* Address of the select-A-exhausted subroutine */
224992b01d53Sdrh   int addrEofB;         /* Address of the select-B-exhausted subroutine */
225092b01d53Sdrh   int addrAltB;         /* Address of the A<B subroutine */
225192b01d53Sdrh   int addrAeqB;         /* Address of the A==B subroutine */
225292b01d53Sdrh   int addrAgtB;         /* Address of the A>B subroutine */
225392b01d53Sdrh   int regLimitA;        /* Limit register for select-A */
225492b01d53Sdrh   int regLimitB;        /* Limit register for select-A */
22550acb7e48Sdrh   int regPrev;          /* A range of registers to hold previous output */
225692b01d53Sdrh   int savedLimit;       /* Saved value of p->iLimit */
225792b01d53Sdrh   int savedOffset;      /* Saved value of p->iOffset */
225892b01d53Sdrh   int labelCmpr;        /* Label for the start of the merge algorithm */
225992b01d53Sdrh   int labelEnd;         /* Label for the end of the overall SELECT stmt */
22600acb7e48Sdrh   int j1;               /* Jump instructions that get retargetted */
226192b01d53Sdrh   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
226296067816Sdrh   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
22630acb7e48Sdrh   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
22640acb7e48Sdrh   sqlite3 *db;          /* Database connection */
22650acb7e48Sdrh   ExprList *pOrderBy;   /* The ORDER BY clause */
22660acb7e48Sdrh   int nOrderBy;         /* Number of terms in the ORDER BY clause */
22670acb7e48Sdrh   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
22687f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN
22697f61e92cSdan   int iSub1;            /* EQP id of left-hand query */
22707f61e92cSdan   int iSub2;            /* EQP id of right-hand query */
22717f61e92cSdan #endif
2272b21e7c70Sdrh 
227392b01d53Sdrh   assert( p->pOrderBy!=0 );
227496067816Sdrh   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
22750acb7e48Sdrh   db = pParse->db;
227692b01d53Sdrh   v = pParse->pVdbe;
2277ccfcbceaSdrh   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
227892b01d53Sdrh   labelEnd = sqlite3VdbeMakeLabel(v);
227992b01d53Sdrh   labelCmpr = sqlite3VdbeMakeLabel(v);
22800acb7e48Sdrh 
2281b21e7c70Sdrh 
228292b01d53Sdrh   /* Patch up the ORDER BY clause
228392b01d53Sdrh   */
228492b01d53Sdrh   op = p->op;
2285b21e7c70Sdrh   pPrior = p->pPrior;
228692b01d53Sdrh   assert( pPrior->pOrderBy==0 );
22870acb7e48Sdrh   pOrderBy = p->pOrderBy;
228893a960a0Sdrh   assert( pOrderBy );
22890acb7e48Sdrh   nOrderBy = pOrderBy->nExpr;
229093a960a0Sdrh 
22910acb7e48Sdrh   /* For operators other than UNION ALL we have to make sure that
22920acb7e48Sdrh   ** the ORDER BY clause covers every term of the result set.  Add
22930acb7e48Sdrh   ** terms to the ORDER BY clause as necessary.
22940acb7e48Sdrh   */
22950acb7e48Sdrh   if( op!=TK_ALL ){
22960acb7e48Sdrh     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
22977d10d5a6Sdrh       struct ExprList_item *pItem;
22987d10d5a6Sdrh       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
22994b3ac73cSdrh         assert( pItem->iOrderByCol>0 );
23004b3ac73cSdrh         if( pItem->iOrderByCol==i ) break;
23010acb7e48Sdrh       }
23020acb7e48Sdrh       if( j==nOrderBy ){
2303b7916a78Sdrh         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
23040acb7e48Sdrh         if( pNew==0 ) return SQLITE_NOMEM;
23050acb7e48Sdrh         pNew->flags |= EP_IntValue;
230633e619fcSdrh         pNew->u.iValue = i;
2307b7916a78Sdrh         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
2308a3cc3c96Sdrh         if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
23090acb7e48Sdrh       }
23100acb7e48Sdrh     }
23110acb7e48Sdrh   }
23120acb7e48Sdrh 
23130acb7e48Sdrh   /* Compute the comparison permutation and keyinfo that is used with
231410c081adSdrh   ** the permutation used to determine if the next
23150acb7e48Sdrh   ** row of results comes from selectA or selectB.  Also add explicit
23160acb7e48Sdrh   ** collations to the ORDER BY clause terms so that when the subqueries
23170acb7e48Sdrh   ** to the right and the left are evaluated, they use the correct
23180acb7e48Sdrh   ** collation.
23190acb7e48Sdrh   */
23200acb7e48Sdrh   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
23210acb7e48Sdrh   if( aPermute ){
23227d10d5a6Sdrh     struct ExprList_item *pItem;
23237d10d5a6Sdrh     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
23244b3ac73cSdrh       assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );
23254b3ac73cSdrh       aPermute[i] = pItem->iOrderByCol - 1;
23260acb7e48Sdrh     }
23270acb7e48Sdrh     pKeyMerge =
23280acb7e48Sdrh       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
23290acb7e48Sdrh     if( pKeyMerge ){
23300acb7e48Sdrh       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
2331ea678832Sdrh       pKeyMerge->nField = (u16)nOrderBy;
23320acb7e48Sdrh       pKeyMerge->enc = ENC(db);
23330acb7e48Sdrh       for(i=0; i<nOrderBy; i++){
23340acb7e48Sdrh         CollSeq *pColl;
23350acb7e48Sdrh         Expr *pTerm = pOrderBy->a[i].pExpr;
2336*ae80ddeaSdrh         if( pTerm->flags & EP_Collate ){
2337*ae80ddeaSdrh           pColl = sqlite3ExprCollSeq(pParse, pTerm);
23380acb7e48Sdrh         }else{
23390acb7e48Sdrh           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
23400acb7e48Sdrh         }
23410acb7e48Sdrh         pKeyMerge->aColl[i] = pColl;
23420acb7e48Sdrh         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
23430acb7e48Sdrh       }
23440acb7e48Sdrh     }
23450acb7e48Sdrh   }else{
23460acb7e48Sdrh     pKeyMerge = 0;
23470acb7e48Sdrh   }
23480acb7e48Sdrh 
23490acb7e48Sdrh   /* Reattach the ORDER BY clause to the query.
23500acb7e48Sdrh   */
23510acb7e48Sdrh   p->pOrderBy = pOrderBy;
23526ab3a2ecSdanielk1977   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
23530acb7e48Sdrh 
23540acb7e48Sdrh   /* Allocate a range of temporary registers and the KeyInfo needed
23550acb7e48Sdrh   ** for the logic that removes duplicate result rows when the
23560acb7e48Sdrh   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
23570acb7e48Sdrh   */
23580acb7e48Sdrh   if( op==TK_ALL ){
23590acb7e48Sdrh     regPrev = 0;
23600acb7e48Sdrh   }else{
23610acb7e48Sdrh     int nExpr = p->pEList->nExpr;
23621c0dc825Sdrh     assert( nOrderBy>=nExpr || db->mallocFailed );
23630acb7e48Sdrh     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
23640acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
23650acb7e48Sdrh     pKeyDup = sqlite3DbMallocZero(db,
23660acb7e48Sdrh                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
23670acb7e48Sdrh     if( pKeyDup ){
23680acb7e48Sdrh       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
2369ea678832Sdrh       pKeyDup->nField = (u16)nExpr;
23700acb7e48Sdrh       pKeyDup->enc = ENC(db);
23710acb7e48Sdrh       for(i=0; i<nExpr; i++){
23720acb7e48Sdrh         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
23730acb7e48Sdrh         pKeyDup->aSortOrder[i] = 0;
23740acb7e48Sdrh       }
23750acb7e48Sdrh     }
23760acb7e48Sdrh   }
237792b01d53Sdrh 
237892b01d53Sdrh   /* Separate the left and the right query from one another
237992b01d53Sdrh   */
238092b01d53Sdrh   p->pPrior = 0;
23817d10d5a6Sdrh   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
23820acb7e48Sdrh   if( pPrior->pPrior==0 ){
23837d10d5a6Sdrh     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
23840acb7e48Sdrh   }
238592b01d53Sdrh 
238692b01d53Sdrh   /* Compute the limit registers */
238792b01d53Sdrh   computeLimitRegisters(pParse, p, labelEnd);
23880acb7e48Sdrh   if( p->iLimit && op==TK_ALL ){
238992b01d53Sdrh     regLimitA = ++pParse->nMem;
239092b01d53Sdrh     regLimitB = ++pParse->nMem;
239192b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
239292b01d53Sdrh                                   regLimitA);
239392b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
239492b01d53Sdrh   }else{
239592b01d53Sdrh     regLimitA = regLimitB = 0;
239692b01d53Sdrh   }
2397633e6d57Sdrh   sqlite3ExprDelete(db, p->pLimit);
23980acb7e48Sdrh   p->pLimit = 0;
2399633e6d57Sdrh   sqlite3ExprDelete(db, p->pOffset);
24000acb7e48Sdrh   p->pOffset = 0;
240192b01d53Sdrh 
2402b21e7c70Sdrh   regAddrA = ++pParse->nMem;
2403b21e7c70Sdrh   regEofA = ++pParse->nMem;
2404b21e7c70Sdrh   regAddrB = ++pParse->nMem;
2405b21e7c70Sdrh   regEofB = ++pParse->nMem;
2406b21e7c70Sdrh   regOutA = ++pParse->nMem;
2407b21e7c70Sdrh   regOutB = ++pParse->nMem;
2408b21e7c70Sdrh   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
2409b21e7c70Sdrh   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
2410b21e7c70Sdrh 
241192b01d53Sdrh   /* Jump past the various subroutines and coroutines to the main
241292b01d53Sdrh   ** merge loop
241392b01d53Sdrh   */
2414b21e7c70Sdrh   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
2415b21e7c70Sdrh   addrSelectA = sqlite3VdbeCurrentAddr(v);
241692b01d53Sdrh 
24170acb7e48Sdrh 
241892b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement to the
24190acb7e48Sdrh   ** left of the compound operator - the "A" select.
24200acb7e48Sdrh   */
2421b21e7c70Sdrh   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
242292b01d53Sdrh   pPrior->iLimit = regLimitA;
24237f61e92cSdan   explainSetInteger(iSub1, pParse->iNextSelectId);
24247d10d5a6Sdrh   sqlite3Select(pParse, pPrior, &destA);
2425b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
242692b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2427b21e7c70Sdrh   VdbeNoopComment((v, "End coroutine for left SELECT"));
2428b21e7c70Sdrh 
242992b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement on
243092b01d53Sdrh   ** the right - the "B" select
243192b01d53Sdrh   */
2432b21e7c70Sdrh   addrSelectB = sqlite3VdbeCurrentAddr(v);
2433b21e7c70Sdrh   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
243492b01d53Sdrh   savedLimit = p->iLimit;
243592b01d53Sdrh   savedOffset = p->iOffset;
243692b01d53Sdrh   p->iLimit = regLimitB;
243792b01d53Sdrh   p->iOffset = 0;
24387f61e92cSdan   explainSetInteger(iSub2, pParse->iNextSelectId);
24397d10d5a6Sdrh   sqlite3Select(pParse, p, &destB);
244092b01d53Sdrh   p->iLimit = savedLimit;
244192b01d53Sdrh   p->iOffset = savedOffset;
2442b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
244392b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
2444b21e7c70Sdrh   VdbeNoopComment((v, "End coroutine for right SELECT"));
2445b21e7c70Sdrh 
244692b01d53Sdrh   /* Generate a subroutine that outputs the current row of the A
24470acb7e48Sdrh   ** select as the next output row of the compound select.
244892b01d53Sdrh   */
2449b21e7c70Sdrh   VdbeNoopComment((v, "Output routine for A"));
24500acb7e48Sdrh   addrOutA = generateOutputSubroutine(pParse,
24510acb7e48Sdrh                  p, &destA, pDest, regOutA,
24520acb7e48Sdrh                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
2453b21e7c70Sdrh 
245492b01d53Sdrh   /* Generate a subroutine that outputs the current row of the B
24550acb7e48Sdrh   ** select as the next output row of the compound select.
245692b01d53Sdrh   */
24570acb7e48Sdrh   if( op==TK_ALL || op==TK_UNION ){
2458b21e7c70Sdrh     VdbeNoopComment((v, "Output routine for B"));
24590acb7e48Sdrh     addrOutB = generateOutputSubroutine(pParse,
24600acb7e48Sdrh                  p, &destB, pDest, regOutB,
24610acb7e48Sdrh                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
24620acb7e48Sdrh   }
2463b21e7c70Sdrh 
246492b01d53Sdrh   /* Generate a subroutine to run when the results from select A
246592b01d53Sdrh   ** are exhausted and only data in select B remains.
246692b01d53Sdrh   */
246792b01d53Sdrh   VdbeNoopComment((v, "eof-A subroutine"));
246892b01d53Sdrh   if( op==TK_EXCEPT || op==TK_INTERSECT ){
24690acb7e48Sdrh     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
247092b01d53Sdrh   }else{
24710acb7e48Sdrh     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
2472b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
247392b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
24740acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
247595aa47b1Sdrh     p->nSelectRow += pPrior->nSelectRow;
2476b21e7c70Sdrh   }
2477b21e7c70Sdrh 
247892b01d53Sdrh   /* Generate a subroutine to run when the results from select B
247992b01d53Sdrh   ** are exhausted and only data in select A remains.
248092b01d53Sdrh   */
2481b21e7c70Sdrh   if( op==TK_INTERSECT ){
248292b01d53Sdrh     addrEofB = addrEofA;
248395aa47b1Sdrh     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
2484b21e7c70Sdrh   }else{
248592b01d53Sdrh     VdbeNoopComment((v, "eof-B subroutine"));
24860acb7e48Sdrh     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
2487b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
248892b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
24890acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
2490b21e7c70Sdrh   }
2491b21e7c70Sdrh 
249292b01d53Sdrh   /* Generate code to handle the case of A<B
249392b01d53Sdrh   */
2494b21e7c70Sdrh   VdbeNoopComment((v, "A-lt-B subroutine"));
24950acb7e48Sdrh   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
249692b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2497b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
249892b01d53Sdrh   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2499b21e7c70Sdrh 
250092b01d53Sdrh   /* Generate code to handle the case of A==B
250192b01d53Sdrh   */
2502b21e7c70Sdrh   if( op==TK_ALL ){
2503b21e7c70Sdrh     addrAeqB = addrAltB;
25040acb7e48Sdrh   }else if( op==TK_INTERSECT ){
25050acb7e48Sdrh     addrAeqB = addrAltB;
25060acb7e48Sdrh     addrAltB++;
250792b01d53Sdrh   }else{
2508b21e7c70Sdrh     VdbeNoopComment((v, "A-eq-B subroutine"));
25090acb7e48Sdrh     addrAeqB =
251092b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
251192b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
251292b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
251392b01d53Sdrh   }
2514b21e7c70Sdrh 
251592b01d53Sdrh   /* Generate code to handle the case of A>B
251692b01d53Sdrh   */
2517b21e7c70Sdrh   VdbeNoopComment((v, "A-gt-B subroutine"));
2518b21e7c70Sdrh   addrAgtB = sqlite3VdbeCurrentAddr(v);
2519b21e7c70Sdrh   if( op==TK_ALL || op==TK_UNION ){
2520b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
252192b01d53Sdrh   }
25220acb7e48Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
2523b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
252492b01d53Sdrh   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2525b21e7c70Sdrh 
252692b01d53Sdrh   /* This code runs once to initialize everything.
252792b01d53Sdrh   */
2528b21e7c70Sdrh   sqlite3VdbeJumpHere(v, j1);
2529b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
2530b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
253192b01d53Sdrh   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
25320acb7e48Sdrh   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
2533b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
2534b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
253592b01d53Sdrh 
253692b01d53Sdrh   /* Implement the main merge loop
253792b01d53Sdrh   */
253892b01d53Sdrh   sqlite3VdbeResolveLabel(v, labelCmpr);
25390acb7e48Sdrh   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
25402b596da8Sdrh   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
25410acb7e48Sdrh                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
2542b21e7c70Sdrh   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
254392b01d53Sdrh 
25440acb7e48Sdrh   /* Release temporary registers
25450acb7e48Sdrh   */
25460acb7e48Sdrh   if( regPrev ){
25470acb7e48Sdrh     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
25480acb7e48Sdrh   }
25490acb7e48Sdrh 
255092b01d53Sdrh   /* Jump to the this point in order to terminate the query.
255192b01d53Sdrh   */
2552b21e7c70Sdrh   sqlite3VdbeResolveLabel(v, labelEnd);
2553b21e7c70Sdrh 
255492b01d53Sdrh   /* Set the number of output columns
255592b01d53Sdrh   */
25567d10d5a6Sdrh   if( pDest->eDest==SRT_Output ){
25570acb7e48Sdrh     Select *pFirst = pPrior;
255892b01d53Sdrh     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
255992b01d53Sdrh     generateColumnNames(pParse, 0, pFirst->pEList);
2560b21e7c70Sdrh   }
256192b01d53Sdrh 
25620acb7e48Sdrh   /* Reassembly the compound query so that it will be freed correctly
25630acb7e48Sdrh   ** by the calling function */
25645e7ad508Sdanielk1977   if( p->pPrior ){
2565633e6d57Sdrh     sqlite3SelectDelete(db, p->pPrior);
25665e7ad508Sdanielk1977   }
25670acb7e48Sdrh   p->pPrior = pPrior;
256892b01d53Sdrh 
256992b01d53Sdrh   /*** TBD:  Insert subroutine calls to close cursors on incomplete
257092b01d53Sdrh   **** subqueries ****/
25717f61e92cSdan   explainComposite(pParse, p->op, iSub1, iSub2, 0);
257292b01d53Sdrh   return SQLITE_OK;
257392b01d53Sdrh }
2574de3e41e3Sdanielk1977 #endif
2575b21e7c70Sdrh 
25763514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
257717435752Sdrh /* Forward Declarations */
257817435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*);
257917435752Sdrh static void substSelect(sqlite3*, Select *, int, ExprList *);
258017435752Sdrh 
25812282792aSdrh /*
2582832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
25836a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
258484e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
25856a3ea0e6Sdrh ** unchanged.)
2586832508b7Sdrh **
2587832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
2588832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
2589832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
2590832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
2591832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
2592832508b7Sdrh ** of the subquery rather the result set of the subquery.
2593832508b7Sdrh */
2594b7916a78Sdrh static Expr *substExpr(
259517435752Sdrh   sqlite3 *db,        /* Report malloc errors to this connection */
259617435752Sdrh   Expr *pExpr,        /* Expr in which substitution occurs */
259717435752Sdrh   int iTable,         /* Table to be substituted */
259817435752Sdrh   ExprList *pEList    /* Substitute expressions */
259917435752Sdrh ){
2600b7916a78Sdrh   if( pExpr==0 ) return 0;
260150350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
260250350a15Sdrh     if( pExpr->iColumn<0 ){
260350350a15Sdrh       pExpr->op = TK_NULL;
260450350a15Sdrh     }else{
2605832508b7Sdrh       Expr *pNew;
260684e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
26076ab3a2ecSdanielk1977       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
2608b7916a78Sdrh       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
2609b7916a78Sdrh       sqlite3ExprDelete(db, pExpr);
2610b7916a78Sdrh       pExpr = pNew;
261150350a15Sdrh     }
2612832508b7Sdrh   }else{
2613b7916a78Sdrh     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
2614b7916a78Sdrh     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
26156ab3a2ecSdanielk1977     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
26166ab3a2ecSdanielk1977       substSelect(db, pExpr->x.pSelect, iTable, pEList);
26176ab3a2ecSdanielk1977     }else{
26186ab3a2ecSdanielk1977       substExprList(db, pExpr->x.pList, iTable, pEList);
26196ab3a2ecSdanielk1977     }
2620832508b7Sdrh   }
2621b7916a78Sdrh   return pExpr;
2622832508b7Sdrh }
262317435752Sdrh static void substExprList(
262417435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
262517435752Sdrh   ExprList *pList,     /* List to scan and in which to make substitutes */
262617435752Sdrh   int iTable,          /* Table to be substituted */
262717435752Sdrh   ExprList *pEList     /* Substitute values */
262817435752Sdrh ){
2629832508b7Sdrh   int i;
2630832508b7Sdrh   if( pList==0 ) return;
2631832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
2632b7916a78Sdrh     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
2633832508b7Sdrh   }
2634832508b7Sdrh }
263517435752Sdrh static void substSelect(
263617435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
263717435752Sdrh   Select *p,           /* SELECT statement in which to make substitutions */
263817435752Sdrh   int iTable,          /* Table to be replaced */
263917435752Sdrh   ExprList *pEList     /* Substitute values */
264017435752Sdrh ){
2641588a9a1aSdrh   SrcList *pSrc;
2642588a9a1aSdrh   struct SrcList_item *pItem;
2643588a9a1aSdrh   int i;
2644b3bce662Sdanielk1977   if( !p ) return;
264517435752Sdrh   substExprList(db, p->pEList, iTable, pEList);
264617435752Sdrh   substExprList(db, p->pGroupBy, iTable, pEList);
264717435752Sdrh   substExprList(db, p->pOrderBy, iTable, pEList);
2648b7916a78Sdrh   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
2649b7916a78Sdrh   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
265017435752Sdrh   substSelect(db, p->pPrior, iTable, pEList);
2651588a9a1aSdrh   pSrc = p->pSrc;
2652e2f02bacSdrh   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
2653e2f02bacSdrh   if( ALWAYS(pSrc) ){
2654588a9a1aSdrh     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
2655588a9a1aSdrh       substSelect(db, pItem->pSelect, iTable, pEList);
2656588a9a1aSdrh     }
2657588a9a1aSdrh   }
2658b3bce662Sdanielk1977 }
26593514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
2660832508b7Sdrh 
26613514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
2662832508b7Sdrh /*
2663630d296cSdrh ** This routine attempts to flatten subqueries as a performance optimization.
2664630d296cSdrh ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
26651350b030Sdrh **
26661350b030Sdrh ** To understand the concept of flattening, consider the following
26671350b030Sdrh ** query:
26681350b030Sdrh **
26691350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
26701350b030Sdrh **
26711350b030Sdrh ** The default way of implementing this query is to execute the
26721350b030Sdrh ** subquery first and store the results in a temporary table, then
26731350b030Sdrh ** run the outer query on that temporary table.  This requires two
26741350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
26751350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
2676832508b7Sdrh ** optimized.
26771350b030Sdrh **
2678832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
26791350b030Sdrh ** a single flat select, like this:
26801350b030Sdrh **
26811350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
26821350b030Sdrh **
26831350b030Sdrh ** The code generated for this simpification gives the same result
2684832508b7Sdrh ** but only has to scan the data once.  And because indices might
2685832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
2686832508b7Sdrh ** avoided.
26871350b030Sdrh **
2688832508b7Sdrh ** Flattening is only attempted if all of the following are true:
26891350b030Sdrh **
2690832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
26911350b030Sdrh **
2692832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
2693832508b7Sdrh **
26942b300d5dSdrh **   (3)  The subquery is not the right operand of a left outer join
269549ad330dSdan **        (Originally ticket #306.  Strengthened by ticket #3300)
2696832508b7Sdrh **
269749ad330dSdan **   (4)  The subquery is not DISTINCT.
2698832508b7Sdrh **
269949ad330dSdan **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
270049ad330dSdan **        sub-queries that were excluded from this optimization. Restriction
270149ad330dSdan **        (4) has since been expanded to exclude all DISTINCT subqueries.
2702832508b7Sdrh **
2703832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
2704832508b7Sdrh **        DISTINCT.
2705832508b7Sdrh **
2706630d296cSdrh **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
2707630d296cSdrh **        A FROM clause, consider adding a FROM close with the special
2708630d296cSdrh **        table sqlite_once that consists of a single row containing a
2709630d296cSdrh **        single NULL.
271008192d5fSdrh **
2711df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
2712df199a25Sdrh **
2713df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
2714df199a25Sdrh **        aggregates.
2715df199a25Sdrh **
2716df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
2717df199a25Sdrh **        use LIMIT.
2718df199a25Sdrh **
2719174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
2720174b6195Sdrh **
27217b688edeSdrh **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
27222b300d5dSdrh **        a separate restriction deriving from ticket #350.
27233fc673e6Sdrh **
272449ad330dSdan **  (13)  The subquery and outer query do not both use LIMIT.
2725ac83963aSdrh **
272649ad330dSdan **  (14)  The subquery does not use OFFSET.
2727ac83963aSdrh **
2728ad91c6cdSdrh **  (15)  The outer query is not part of a compound select or the
2729f3913278Sdrh **        subquery does not have a LIMIT clause.
2730f3913278Sdrh **        (See ticket #2339 and ticket [02a8e81d44]).
2731ad91c6cdSdrh **
2732c52e355dSdrh **  (16)  The outer query is not an aggregate or the subquery does
2733c52e355dSdrh **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
2734c52e355dSdrh **        until we introduced the group_concat() function.
2735c52e355dSdrh **
2736f23329a2Sdanielk1977 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
27374914cf92Sdanielk1977 **        compound clause made up entirely of non-aggregate queries, and
2738f23329a2Sdanielk1977 **        the parent query:
2739f23329a2Sdanielk1977 **
2740f23329a2Sdanielk1977 **          * is not itself part of a compound select,
2741f23329a2Sdanielk1977 **          * is not an aggregate or DISTINCT query, and
2742630d296cSdrh **          * is not a join
2743f23329a2Sdanielk1977 **
27444914cf92Sdanielk1977 **        The parent and sub-query may contain WHERE clauses. Subject to
27454914cf92Sdanielk1977 **        rules (11), (13) and (14), they may also contain ORDER BY,
2746630d296cSdrh **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
2747630d296cSdrh **        operator other than UNION ALL because all the other compound
2748630d296cSdrh **        operators have an implied DISTINCT which is disallowed by
2749630d296cSdrh **        restriction (4).
2750f23329a2Sdanielk1977 **
275167c70142Sdan **        Also, each component of the sub-query must return the same number
275267c70142Sdan **        of result columns. This is actually a requirement for any compound
275367c70142Sdan **        SELECT statement, but all the code here does is make sure that no
275467c70142Sdan **        such (illegal) sub-query is flattened. The caller will detect the
275567c70142Sdan **        syntax error and return a detailed message.
275667c70142Sdan **
275749fc1f60Sdanielk1977 **  (18)  If the sub-query is a compound select, then all terms of the
275849fc1f60Sdanielk1977 **        ORDER by clause of the parent must be simple references to
275949fc1f60Sdanielk1977 **        columns of the sub-query.
276049fc1f60Sdanielk1977 **
2761229cf702Sdrh **  (19)  The subquery does not use LIMIT or the outer query does not
2762229cf702Sdrh **        have a WHERE clause.
2763229cf702Sdrh **
2764e8902a70Sdrh **  (20)  If the sub-query is a compound select, then it must not use
2765e8902a70Sdrh **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
2766e8902a70Sdrh **        somewhat by saying that the terms of the ORDER BY clause must
2767630d296cSdrh **        appear as unmodified result columns in the outer query.  But we
2768e8902a70Sdrh **        have other optimizations in mind to deal with that case.
2769e8902a70Sdrh **
2770a91491e5Sshaneh **  (21)  The subquery does not use LIMIT or the outer query is not
2771a91491e5Sshaneh **        DISTINCT.  (See ticket [752e1646fc]).
2772a91491e5Sshaneh **
2773832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
2774832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
2775832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
2776832508b7Sdrh **
2777665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
2778832508b7Sdrh ** If flattening is attempted this routine returns 1.
2779832508b7Sdrh **
2780832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
2781832508b7Sdrh ** the subquery before this routine runs.
27821350b030Sdrh */
27838c74a8caSdrh static int flattenSubquery(
2784524cc21eSdanielk1977   Parse *pParse,       /* Parsing context */
27858c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
27868c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
27878c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
27888c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
27898c74a8caSdrh ){
2790524cc21eSdanielk1977   const char *zSavedAuthContext = pParse->zAuthContext;
2791f23329a2Sdanielk1977   Select *pParent;
27920bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
2793f23329a2Sdanielk1977   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
2794ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
2795ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
27960bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
27976a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
279891bb0eedSdrh   int i;              /* Loop counter */
279991bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
280091bb0eedSdrh   struct SrcList_item *pSubitem;   /* The subquery */
2801524cc21eSdanielk1977   sqlite3 *db = pParse->db;
28021350b030Sdrh 
2803832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
2804832508b7Sdrh   */
2805a78c22c4Sdrh   assert( p!=0 );
2806a78c22c4Sdrh   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
28077e5418e4Sdrh   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
2808832508b7Sdrh   pSrc = p->pSrc;
2809ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
281091bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
281149fc1f60Sdanielk1977   iParent = pSubitem->iCursor;
281291bb0eedSdrh   pSub = pSubitem->pSelect;
2813832508b7Sdrh   assert( pSub!=0 );
2814ac83963aSdrh   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
2815ac83963aSdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
2816832508b7Sdrh   pSubSrc = pSub->pSrc;
2817832508b7Sdrh   assert( pSubSrc );
2818ac83963aSdrh   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
2819ac83963aSdrh   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
2820ac83963aSdrh   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
2821ac83963aSdrh   ** became arbitrary expressions, we were forced to add restrictions (13)
2822ac83963aSdrh   ** and (14). */
2823ac83963aSdrh   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
2824ac83963aSdrh   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
2825f3913278Sdrh   if( p->pRightmost && pSub->pLimit ){
2826ad91c6cdSdrh     return 0;                                            /* Restriction (15) */
2827ad91c6cdSdrh   }
2828ac83963aSdrh   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
282949ad330dSdan   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
283049ad330dSdan   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
283149ad330dSdan      return 0;         /* Restrictions (8)(9) */
2832df199a25Sdrh   }
28337d10d5a6Sdrh   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
28347d10d5a6Sdrh      return 0;         /* Restriction (6)  */
28357d10d5a6Sdrh   }
28367d10d5a6Sdrh   if( p->pOrderBy && pSub->pOrderBy ){
2837ac83963aSdrh      return 0;                                           /* Restriction (11) */
2838ac83963aSdrh   }
2839c52e355dSdrh   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
2840229cf702Sdrh   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
2841a91491e5Sshaneh   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
2842a91491e5Sshaneh      return 0;         /* Restriction (21) */
2843a91491e5Sshaneh   }
2844832508b7Sdrh 
28452b300d5dSdrh   /* OBSOLETE COMMENT 1:
28462b300d5dSdrh   ** Restriction 3:  If the subquery is a join, make sure the subquery is
28478af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
28488af4d3acSdrh   ** is not allowed:
28498af4d3acSdrh   **
28508af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
28518af4d3acSdrh   **
28528af4d3acSdrh   ** If we flatten the above, we would get
28538af4d3acSdrh   **
28548af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
28558af4d3acSdrh   **
28568af4d3acSdrh   ** which is not at all the same thing.
28572b300d5dSdrh   **
28582b300d5dSdrh   ** OBSOLETE COMMENT 2:
28592b300d5dSdrh   ** Restriction 12:  If the subquery is the right operand of a left outer
28603fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
28613fc673e6Sdrh   ** An examples of why this is not allowed:
28623fc673e6Sdrh   **
28633fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
28643fc673e6Sdrh   **
28653fc673e6Sdrh   ** If we flatten the above, we would get
28663fc673e6Sdrh   **
28673fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
28683fc673e6Sdrh   **
28693fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
28703fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
28712b300d5dSdrh   **
28722b300d5dSdrh   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
28732b300d5dSdrh   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
28742b300d5dSdrh   ** is fraught with danger.  Best to avoid the whole thing.  If the
28752b300d5dSdrh   ** subquery is the right term of a LEFT JOIN, then do not flatten.
28763fc673e6Sdrh   */
28772b300d5dSdrh   if( (pSubitem->jointype & JT_OUTER)!=0 ){
28783fc673e6Sdrh     return 0;
28793fc673e6Sdrh   }
28803fc673e6Sdrh 
2881f23329a2Sdanielk1977   /* Restriction 17: If the sub-query is a compound SELECT, then it must
2882f23329a2Sdanielk1977   ** use only the UNION ALL operator. And none of the simple select queries
2883f23329a2Sdanielk1977   ** that make up the compound SELECT are allowed to be aggregate or distinct
2884f23329a2Sdanielk1977   ** queries.
2885f23329a2Sdanielk1977   */
2886f23329a2Sdanielk1977   if( pSub->pPrior ){
2887e8902a70Sdrh     if( pSub->pOrderBy ){
2888e8902a70Sdrh       return 0;  /* Restriction 20 */
2889e8902a70Sdrh     }
2890e2f02bacSdrh     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
2891f23329a2Sdanielk1977       return 0;
2892f23329a2Sdanielk1977     }
2893f23329a2Sdanielk1977     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
2894ccfcbceaSdrh       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
2895ccfcbceaSdrh       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
28964b3ac73cSdrh       assert( pSub->pSrc!=0 );
28977d10d5a6Sdrh       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
289880b3c548Sdanielk1977        || (pSub1->pPrior && pSub1->op!=TK_ALL)
28994b3ac73cSdrh        || pSub1->pSrc->nSrc<1
290067c70142Sdan        || pSub->pEList->nExpr!=pSub1->pEList->nExpr
290180b3c548Sdanielk1977       ){
2902f23329a2Sdanielk1977         return 0;
2903f23329a2Sdanielk1977       }
29044b3ac73cSdrh       testcase( pSub1->pSrc->nSrc>1 );
2905f23329a2Sdanielk1977     }
290649fc1f60Sdanielk1977 
290749fc1f60Sdanielk1977     /* Restriction 18. */
290849fc1f60Sdanielk1977     if( p->pOrderBy ){
290949fc1f60Sdanielk1977       int ii;
291049fc1f60Sdanielk1977       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
29114b3ac73cSdrh         if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
291249fc1f60Sdanielk1977       }
291349fc1f60Sdanielk1977     }
2914f23329a2Sdanielk1977   }
2915f23329a2Sdanielk1977 
29167d10d5a6Sdrh   /***** If we reach this point, flattening is permitted. *****/
29177d10d5a6Sdrh 
29187d10d5a6Sdrh   /* Authorize the subquery */
2919524cc21eSdanielk1977   pParse->zAuthContext = pSubitem->zName;
2920a2acb0d7Sdrh   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
2921a2acb0d7Sdrh   testcase( i==SQLITE_DENY );
2922524cc21eSdanielk1977   pParse->zAuthContext = zSavedAuthContext;
2923524cc21eSdanielk1977 
29247d10d5a6Sdrh   /* If the sub-query is a compound SELECT statement, then (by restrictions
29257d10d5a6Sdrh   ** 17 and 18 above) it must be a UNION ALL and the parent query must
29267d10d5a6Sdrh   ** be of the form:
2927f23329a2Sdanielk1977   **
2928f23329a2Sdanielk1977   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
2929f23329a2Sdanielk1977   **
2930f23329a2Sdanielk1977   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
2931a78c22c4Sdrh   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
2932f23329a2Sdanielk1977   ** OFFSET clauses and joins them to the left-hand-side of the original
2933f23329a2Sdanielk1977   ** using UNION ALL operators. In this case N is the number of simple
2934f23329a2Sdanielk1977   ** select statements in the compound sub-query.
2935a78c22c4Sdrh   **
2936a78c22c4Sdrh   ** Example:
2937a78c22c4Sdrh   **
2938a78c22c4Sdrh   **     SELECT a+1 FROM (
2939a78c22c4Sdrh   **        SELECT x FROM tab
2940a78c22c4Sdrh   **        UNION ALL
2941a78c22c4Sdrh   **        SELECT y FROM tab
2942a78c22c4Sdrh   **        UNION ALL
2943a78c22c4Sdrh   **        SELECT abs(z*2) FROM tab2
2944a78c22c4Sdrh   **     ) WHERE a!=5 ORDER BY 1
2945a78c22c4Sdrh   **
2946a78c22c4Sdrh   ** Transformed into:
2947a78c22c4Sdrh   **
2948a78c22c4Sdrh   **     SELECT x+1 FROM tab WHERE x+1!=5
2949a78c22c4Sdrh   **     UNION ALL
2950a78c22c4Sdrh   **     SELECT y+1 FROM tab WHERE y+1!=5
2951a78c22c4Sdrh   **     UNION ALL
2952a78c22c4Sdrh   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
2953a78c22c4Sdrh   **     ORDER BY 1
2954a78c22c4Sdrh   **
2955a78c22c4Sdrh   ** We call this the "compound-subquery flattening".
2956f23329a2Sdanielk1977   */
2957f23329a2Sdanielk1977   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
2958f23329a2Sdanielk1977     Select *pNew;
2959f23329a2Sdanielk1977     ExprList *pOrderBy = p->pOrderBy;
29604b86ef1dSdanielk1977     Expr *pLimit = p->pLimit;
2961f23329a2Sdanielk1977     Select *pPrior = p->pPrior;
2962f23329a2Sdanielk1977     p->pOrderBy = 0;
2963f23329a2Sdanielk1977     p->pSrc = 0;
2964f23329a2Sdanielk1977     p->pPrior = 0;
29654b86ef1dSdanielk1977     p->pLimit = 0;
29666ab3a2ecSdanielk1977     pNew = sqlite3SelectDup(db, p, 0);
29674b86ef1dSdanielk1977     p->pLimit = pLimit;
2968a78c22c4Sdrh     p->pOrderBy = pOrderBy;
2969a78c22c4Sdrh     p->pSrc = pSrc;
2970a78c22c4Sdrh     p->op = TK_ALL;
2971f23329a2Sdanielk1977     p->pRightmost = 0;
2972a78c22c4Sdrh     if( pNew==0 ){
2973a78c22c4Sdrh       pNew = pPrior;
2974a78c22c4Sdrh     }else{
2975a78c22c4Sdrh       pNew->pPrior = pPrior;
2976f23329a2Sdanielk1977       pNew->pRightmost = 0;
2977f23329a2Sdanielk1977     }
2978a78c22c4Sdrh     p->pPrior = pNew;
2979a78c22c4Sdrh     if( db->mallocFailed ) return 1;
2980a78c22c4Sdrh   }
2981f23329a2Sdanielk1977 
29827d10d5a6Sdrh   /* Begin flattening the iFrom-th entry of the FROM clause
29837d10d5a6Sdrh   ** in the outer query.
2984832508b7Sdrh   */
2985f23329a2Sdanielk1977   pSub = pSub1 = pSubitem->pSelect;
2986c31c2eb8Sdrh 
2987a78c22c4Sdrh   /* Delete the transient table structure associated with the
2988a78c22c4Sdrh   ** subquery
2989a78c22c4Sdrh   */
2990a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zDatabase);
2991a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zName);
2992a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zAlias);
2993a78c22c4Sdrh   pSubitem->zDatabase = 0;
2994a78c22c4Sdrh   pSubitem->zName = 0;
2995a78c22c4Sdrh   pSubitem->zAlias = 0;
2996a78c22c4Sdrh   pSubitem->pSelect = 0;
2997a78c22c4Sdrh 
2998a78c22c4Sdrh   /* Defer deleting the Table object associated with the
2999a78c22c4Sdrh   ** subquery until code generation is
3000a78c22c4Sdrh   ** complete, since there may still exist Expr.pTab entries that
3001a78c22c4Sdrh   ** refer to the subquery even after flattening.  Ticket #3346.
3002ccfcbceaSdrh   **
3003ccfcbceaSdrh   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
3004a78c22c4Sdrh   */
3005ccfcbceaSdrh   if( ALWAYS(pSubitem->pTab!=0) ){
3006a78c22c4Sdrh     Table *pTabToDel = pSubitem->pTab;
3007a78c22c4Sdrh     if( pTabToDel->nRef==1 ){
300865a7cd16Sdan       Parse *pToplevel = sqlite3ParseToplevel(pParse);
300965a7cd16Sdan       pTabToDel->pNextZombie = pToplevel->pZombieTab;
301065a7cd16Sdan       pToplevel->pZombieTab = pTabToDel;
3011a78c22c4Sdrh     }else{
3012a78c22c4Sdrh       pTabToDel->nRef--;
3013a78c22c4Sdrh     }
3014a78c22c4Sdrh     pSubitem->pTab = 0;
3015a78c22c4Sdrh   }
3016a78c22c4Sdrh 
3017a78c22c4Sdrh   /* The following loop runs once for each term in a compound-subquery
3018a78c22c4Sdrh   ** flattening (as described above).  If we are doing a different kind
3019a78c22c4Sdrh   ** of flattening - a flattening other than a compound-subquery flattening -
3020a78c22c4Sdrh   ** then this loop only runs once.
3021a78c22c4Sdrh   **
3022a78c22c4Sdrh   ** This loop moves all of the FROM elements of the subquery into the
3023c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
3024c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
3025c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
3026c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
3027c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
3028c31c2eb8Sdrh   ** elements we are now copying in.
3029c31c2eb8Sdrh   */
3030a78c22c4Sdrh   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
3031a78c22c4Sdrh     int nSubSrc;
3032ea678832Sdrh     u8 jointype = 0;
3033a78c22c4Sdrh     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
3034a78c22c4Sdrh     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
3035a78c22c4Sdrh     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
3036588a9a1aSdrh 
3037a78c22c4Sdrh     if( pSrc ){
3038a78c22c4Sdrh       assert( pParent==p );  /* First time through the loop */
3039a78c22c4Sdrh       jointype = pSubitem->jointype;
3040588a9a1aSdrh     }else{
3041a78c22c4Sdrh       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
3042a78c22c4Sdrh       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
3043cfa063b3Sdrh       if( pSrc==0 ){
3044a78c22c4Sdrh         assert( db->mallocFailed );
3045a78c22c4Sdrh         break;
3046cfa063b3Sdrh       }
3047c31c2eb8Sdrh     }
3048a78c22c4Sdrh 
3049a78c22c4Sdrh     /* The subquery uses a single slot of the FROM clause of the outer
3050a78c22c4Sdrh     ** query.  If the subquery has more than one element in its FROM clause,
3051a78c22c4Sdrh     ** then expand the outer query to make space for it to hold all elements
3052a78c22c4Sdrh     ** of the subquery.
3053a78c22c4Sdrh     **
3054a78c22c4Sdrh     ** Example:
3055a78c22c4Sdrh     **
3056a78c22c4Sdrh     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
3057a78c22c4Sdrh     **
3058a78c22c4Sdrh     ** The outer query has 3 slots in its FROM clause.  One slot of the
3059a78c22c4Sdrh     ** outer query (the middle slot) is used by the subquery.  The next
3060a78c22c4Sdrh     ** block of code will expand the out query to 4 slots.  The middle
3061a78c22c4Sdrh     ** slot is expanded to two slots in order to make space for the
3062a78c22c4Sdrh     ** two elements in the FROM clause of the subquery.
3063a78c22c4Sdrh     */
3064a78c22c4Sdrh     if( nSubSrc>1 ){
3065a78c22c4Sdrh       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
3066a78c22c4Sdrh       if( db->mallocFailed ){
3067a78c22c4Sdrh         break;
3068c31c2eb8Sdrh       }
3069c31c2eb8Sdrh     }
3070a78c22c4Sdrh 
3071a78c22c4Sdrh     /* Transfer the FROM clause terms from the subquery into the
3072a78c22c4Sdrh     ** outer query.
3073a78c22c4Sdrh     */
3074c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
3075c3a8402aSdrh       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
3076c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
3077c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
3078c31c2eb8Sdrh     }
307961dfc31dSdrh     pSrc->a[iFrom].jointype = jointype;
3080c31c2eb8Sdrh 
3081c31c2eb8Sdrh     /* Now begin substituting subquery result set expressions for
3082c31c2eb8Sdrh     ** references to the iParent in the outer query.
3083c31c2eb8Sdrh     **
3084c31c2eb8Sdrh     ** Example:
3085c31c2eb8Sdrh     **
3086c31c2eb8Sdrh     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
3087c31c2eb8Sdrh     **   \                     \_____________ subquery __________/          /
3088c31c2eb8Sdrh     **    \_____________________ outer query ______________________________/
3089c31c2eb8Sdrh     **
3090c31c2eb8Sdrh     ** We look at every expression in the outer query and every place we see
3091c31c2eb8Sdrh     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
3092c31c2eb8Sdrh     */
3093f23329a2Sdanielk1977     pList = pParent->pEList;
3094832508b7Sdrh     for(i=0; i<pList->nExpr; i++){
3095ccfcbceaSdrh       if( pList->a[i].zName==0 ){
309642fbf321Sdrh         char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
309742fbf321Sdrh         sqlite3Dequote(zName);
309842fbf321Sdrh         pList->a[i].zName = zName;
3099832508b7Sdrh       }
3100ccfcbceaSdrh     }
3101f23329a2Sdanielk1977     substExprList(db, pParent->pEList, iParent, pSub->pEList);
31021b2e0329Sdrh     if( isAgg ){
3103f23329a2Sdanielk1977       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
3104b7916a78Sdrh       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
31051b2e0329Sdrh     }
3106174b6195Sdrh     if( pSub->pOrderBy ){
3107f23329a2Sdanielk1977       assert( pParent->pOrderBy==0 );
3108f23329a2Sdanielk1977       pParent->pOrderBy = pSub->pOrderBy;
3109174b6195Sdrh       pSub->pOrderBy = 0;
3110f23329a2Sdanielk1977     }else if( pParent->pOrderBy ){
3111f23329a2Sdanielk1977       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
3112174b6195Sdrh     }
3113832508b7Sdrh     if( pSub->pWhere ){
31146ab3a2ecSdanielk1977       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
3115832508b7Sdrh     }else{
3116832508b7Sdrh       pWhere = 0;
3117832508b7Sdrh     }
3118832508b7Sdrh     if( subqueryIsAgg ){
3119f23329a2Sdanielk1977       assert( pParent->pHaving==0 );
3120f23329a2Sdanielk1977       pParent->pHaving = pParent->pWhere;
3121f23329a2Sdanielk1977       pParent->pWhere = pWhere;
3122b7916a78Sdrh       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
3123f23329a2Sdanielk1977       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
31246ab3a2ecSdanielk1977                                   sqlite3ExprDup(db, pSub->pHaving, 0));
3125f23329a2Sdanielk1977       assert( pParent->pGroupBy==0 );
31266ab3a2ecSdanielk1977       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
3127832508b7Sdrh     }else{
3128b7916a78Sdrh       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
3129f23329a2Sdanielk1977       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
3130832508b7Sdrh     }
3131c31c2eb8Sdrh 
3132c31c2eb8Sdrh     /* The flattened query is distinct if either the inner or the
3133c31c2eb8Sdrh     ** outer query is distinct.
3134c31c2eb8Sdrh     */
31357d10d5a6Sdrh     pParent->selFlags |= pSub->selFlags & SF_Distinct;
31368c74a8caSdrh 
3137a58fdfb1Sdanielk1977     /*
3138a58fdfb1Sdanielk1977     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
3139ac83963aSdrh     **
3140ac83963aSdrh     ** One is tempted to try to add a and b to combine the limits.  But this
3141ac83963aSdrh     ** does not work if either limit is negative.
3142a58fdfb1Sdanielk1977     */
3143a2dc3b1aSdanielk1977     if( pSub->pLimit ){
3144f23329a2Sdanielk1977       pParent->pLimit = pSub->pLimit;
3145a2dc3b1aSdanielk1977       pSub->pLimit = 0;
3146df199a25Sdrh     }
3147f23329a2Sdanielk1977   }
31488c74a8caSdrh 
3149c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
3150c31c2eb8Sdrh   ** success.
3151c31c2eb8Sdrh   */
3152633e6d57Sdrh   sqlite3SelectDelete(db, pSub1);
3153f23329a2Sdanielk1977 
3154832508b7Sdrh   return 1;
31551350b030Sdrh }
31563514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
31571350b030Sdrh 
31581350b030Sdrh /*
3159a9d1ccb9Sdanielk1977 ** Analyze the SELECT statement passed as an argument to see if it
316008c88eb0Sdrh ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
3161a9d1ccb9Sdanielk1977 ** it is, or 0 otherwise. At present, a query is considered to be
3162a9d1ccb9Sdanielk1977 ** a min()/max() query if:
3163a9d1ccb9Sdanielk1977 **
3164738bdcfbSdanielk1977 **   1. There is a single object in the FROM clause.
3165738bdcfbSdanielk1977 **
3166738bdcfbSdanielk1977 **   2. There is a single expression in the result set, and it is
3167738bdcfbSdanielk1977 **      either min(x) or max(x), where x is a column reference.
3168a9d1ccb9Sdanielk1977 */
31694f21c4afSdrh static u8 minMaxQuery(Select *p){
3170a9d1ccb9Sdanielk1977   Expr *pExpr;
3171a9d1ccb9Sdanielk1977   ExprList *pEList = p->pEList;
3172a9d1ccb9Sdanielk1977 
317308c88eb0Sdrh   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
3174a9d1ccb9Sdanielk1977   pExpr = pEList->a[0].pExpr;
317543152cf8Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
317643152cf8Sdrh   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
31776ab3a2ecSdanielk1977   pEList = pExpr->x.pList;
317843152cf8Sdrh   if( pEList==0 || pEList->nExpr!=1 ) return 0;
317908c88eb0Sdrh   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
318033e619fcSdrh   assert( !ExprHasProperty(pExpr, EP_IntValue) );
318133e619fcSdrh   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
318208c88eb0Sdrh     return WHERE_ORDERBY_MIN;
318333e619fcSdrh   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
318408c88eb0Sdrh     return WHERE_ORDERBY_MAX;
3185a9d1ccb9Sdanielk1977   }
318608c88eb0Sdrh   return WHERE_ORDERBY_NORMAL;
3187a9d1ccb9Sdanielk1977 }
3188a9d1ccb9Sdanielk1977 
3189a9d1ccb9Sdanielk1977 /*
3190a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query.
3191a5533162Sdanielk1977 ** The second argment is the associated aggregate-info object. This
3192a5533162Sdanielk1977 ** function tests if the SELECT is of the form:
3193a5533162Sdanielk1977 **
3194a5533162Sdanielk1977 **   SELECT count(*) FROM <tbl>
3195a5533162Sdanielk1977 **
3196a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query
3197a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing
3198a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned.
3199a5533162Sdanielk1977 */
3200a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
3201a5533162Sdanielk1977   Table *pTab;
3202a5533162Sdanielk1977   Expr *pExpr;
3203a5533162Sdanielk1977 
3204a5533162Sdanielk1977   assert( !p->pGroupBy );
3205a5533162Sdanielk1977 
32067a895a80Sdanielk1977   if( p->pWhere || p->pEList->nExpr!=1
3207a5533162Sdanielk1977    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
3208a5533162Sdanielk1977   ){
3209a5533162Sdanielk1977     return 0;
3210a5533162Sdanielk1977   }
3211a5533162Sdanielk1977   pTab = p->pSrc->a[0].pTab;
3212a5533162Sdanielk1977   pExpr = p->pEList->a[0].pExpr;
321302f33725Sdanielk1977   assert( pTab && !pTab->pSelect && pExpr );
321402f33725Sdanielk1977 
321502f33725Sdanielk1977   if( IsVirtual(pTab) ) return 0;
3216a5533162Sdanielk1977   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
3217fb0a6081Sdrh   if( NEVER(pAggInfo->nFunc==0) ) return 0;
3218a5533162Sdanielk1977   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
3219a5533162Sdanielk1977   if( pExpr->flags&EP_Distinct ) return 0;
3220a5533162Sdanielk1977 
3221a5533162Sdanielk1977   return pTab;
3222a5533162Sdanielk1977 }
3223a5533162Sdanielk1977 
3224a5533162Sdanielk1977 /*
3225b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an
3226b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there
3227b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return
3228b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
3229b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK.
3230b1c685b0Sdanielk1977 */
3231b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
3232b1c685b0Sdanielk1977   if( pFrom->pTab && pFrom->zIndex ){
3233b1c685b0Sdanielk1977     Table *pTab = pFrom->pTab;
3234b1c685b0Sdanielk1977     char *zIndex = pFrom->zIndex;
3235b1c685b0Sdanielk1977     Index *pIdx;
3236b1c685b0Sdanielk1977     for(pIdx=pTab->pIndex;
3237b1c685b0Sdanielk1977         pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
3238b1c685b0Sdanielk1977         pIdx=pIdx->pNext
3239b1c685b0Sdanielk1977     );
3240b1c685b0Sdanielk1977     if( !pIdx ){
3241b1c685b0Sdanielk1977       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
32421db95106Sdan       pParse->checkSchema = 1;
3243b1c685b0Sdanielk1977       return SQLITE_ERROR;
3244b1c685b0Sdanielk1977     }
3245b1c685b0Sdanielk1977     pFrom->pIndex = pIdx;
3246b1c685b0Sdanielk1977   }
3247b1c685b0Sdanielk1977   return SQLITE_OK;
3248b1c685b0Sdanielk1977 }
3249b1c685b0Sdanielk1977 
3250b1c685b0Sdanielk1977 /*
32517d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement.
32527d10d5a6Sdrh ** "Expanding" means to do the following:
32537d10d5a6Sdrh **
32547d10d5a6Sdrh **    (1)  Make sure VDBE cursor numbers have been assigned to every
32557d10d5a6Sdrh **         element of the FROM clause.
32567d10d5a6Sdrh **
32577d10d5a6Sdrh **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
32587d10d5a6Sdrh **         defines FROM clause.  When views appear in the FROM clause,
32597d10d5a6Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
32607d10d5a6Sdrh **         that implements the view.  A copy is made of the view's SELECT
32617d10d5a6Sdrh **         statement so that we can freely modify or delete that statement
32627d10d5a6Sdrh **         without worrying about messing up the presistent representation
32637d10d5a6Sdrh **         of the view.
32647d10d5a6Sdrh **
32657d10d5a6Sdrh **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
32667d10d5a6Sdrh **         on joins and the ON and USING clause of joins.
32677d10d5a6Sdrh **
32687d10d5a6Sdrh **    (4)  Scan the list of columns in the result set (pEList) looking
32697d10d5a6Sdrh **         for instances of the "*" operator or the TABLE.* operator.
32707d10d5a6Sdrh **         If found, expand each "*" to be every column in every table
32717d10d5a6Sdrh **         and TABLE.* to be every column in TABLE.
32727d10d5a6Sdrh **
3273b3bce662Sdanielk1977 */
32747d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){
32757d10d5a6Sdrh   Parse *pParse = pWalker->pParse;
32767d10d5a6Sdrh   int i, j, k;
32777d10d5a6Sdrh   SrcList *pTabList;
32787d10d5a6Sdrh   ExprList *pEList;
32797d10d5a6Sdrh   struct SrcList_item *pFrom;
32807d10d5a6Sdrh   sqlite3 *db = pParse->db;
32817d10d5a6Sdrh 
32827d10d5a6Sdrh   if( db->mallocFailed  ){
32837d10d5a6Sdrh     return WRC_Abort;
32847d10d5a6Sdrh   }
328543152cf8Sdrh   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
32867d10d5a6Sdrh     return WRC_Prune;
32877d10d5a6Sdrh   }
32887d10d5a6Sdrh   p->selFlags |= SF_Expanded;
32897d10d5a6Sdrh   pTabList = p->pSrc;
32907d10d5a6Sdrh   pEList = p->pEList;
32917d10d5a6Sdrh 
32927d10d5a6Sdrh   /* Make sure cursor numbers have been assigned to all entries in
32937d10d5a6Sdrh   ** the FROM clause of the SELECT statement.
32947d10d5a6Sdrh   */
32957d10d5a6Sdrh   sqlite3SrcListAssignCursors(pParse, pTabList);
32967d10d5a6Sdrh 
32977d10d5a6Sdrh   /* Look up every table named in the FROM clause of the select.  If
32987d10d5a6Sdrh   ** an entry of the FROM clause is a subquery instead of a table or view,
32997d10d5a6Sdrh   ** then create a transient table structure to describe the subquery.
33007d10d5a6Sdrh   */
33017d10d5a6Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
33027d10d5a6Sdrh     Table *pTab;
33037d10d5a6Sdrh     if( pFrom->pTab!=0 ){
33047d10d5a6Sdrh       /* This statement has already been prepared.  There is no need
33057d10d5a6Sdrh       ** to go further. */
33067d10d5a6Sdrh       assert( i==0 );
33077d10d5a6Sdrh       return WRC_Prune;
33087d10d5a6Sdrh     }
33097d10d5a6Sdrh     if( pFrom->zName==0 ){
33107d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
33117d10d5a6Sdrh       Select *pSel = pFrom->pSelect;
33127d10d5a6Sdrh       /* A sub-query in the FROM clause of a SELECT */
33137d10d5a6Sdrh       assert( pSel!=0 );
33147d10d5a6Sdrh       assert( pFrom->pTab==0 );
33157d10d5a6Sdrh       sqlite3WalkSelect(pWalker, pSel);
33167d10d5a6Sdrh       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
33177d10d5a6Sdrh       if( pTab==0 ) return WRC_Abort;
33187d10d5a6Sdrh       pTab->nRef = 1;
33197d10d5a6Sdrh       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
33207d10d5a6Sdrh       while( pSel->pPrior ){ pSel = pSel->pPrior; }
33217d10d5a6Sdrh       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
33227d10d5a6Sdrh       pTab->iPKey = -1;
33231ea87012Sdrh       pTab->nRowEst = 1000000;
33247d10d5a6Sdrh       pTab->tabFlags |= TF_Ephemeral;
33257d10d5a6Sdrh #endif
33267d10d5a6Sdrh     }else{
33277d10d5a6Sdrh       /* An ordinary table or view name in the FROM clause */
33287d10d5a6Sdrh       assert( pFrom->pTab==0 );
332941fb5cd1Sdan       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
33307d10d5a6Sdrh       if( pTab==0 ) return WRC_Abort;
33317d10d5a6Sdrh       pTab->nRef++;
33327d10d5a6Sdrh #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
33337d10d5a6Sdrh       if( pTab->pSelect || IsVirtual(pTab) ){
33347d10d5a6Sdrh         /* We reach here if the named table is a really a view */
33357d10d5a6Sdrh         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
333643152cf8Sdrh         assert( pFrom->pSelect==0 );
33376ab3a2ecSdanielk1977         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
33387d10d5a6Sdrh         sqlite3WalkSelect(pWalker, pFrom->pSelect);
33397d10d5a6Sdrh       }
33407d10d5a6Sdrh #endif
33417d10d5a6Sdrh     }
334285574e31Sdanielk1977 
334385574e31Sdanielk1977     /* Locate the index named by the INDEXED BY clause, if any. */
3344b1c685b0Sdanielk1977     if( sqlite3IndexedByLookup(pParse, pFrom) ){
334585574e31Sdanielk1977       return WRC_Abort;
334685574e31Sdanielk1977     }
33477d10d5a6Sdrh   }
33487d10d5a6Sdrh 
33497d10d5a6Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
33507d10d5a6Sdrh   */
33517d10d5a6Sdrh   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
33527d10d5a6Sdrh     return WRC_Abort;
33537d10d5a6Sdrh   }
33547d10d5a6Sdrh 
33557d10d5a6Sdrh   /* For every "*" that occurs in the column list, insert the names of
33567d10d5a6Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
33577d10d5a6Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
33587d10d5a6Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
33597d10d5a6Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
33607d10d5a6Sdrh   ** each one to the list of all columns in all tables.
33617d10d5a6Sdrh   **
33627d10d5a6Sdrh   ** The first loop just checks to see if there are any "*" operators
33637d10d5a6Sdrh   ** that need expanding.
33647d10d5a6Sdrh   */
33657d10d5a6Sdrh   for(k=0; k<pEList->nExpr; k++){
33667d10d5a6Sdrh     Expr *pE = pEList->a[k].pExpr;
33677d10d5a6Sdrh     if( pE->op==TK_ALL ) break;
336843152cf8Sdrh     assert( pE->op!=TK_DOT || pE->pRight!=0 );
336943152cf8Sdrh     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
337043152cf8Sdrh     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
33717d10d5a6Sdrh   }
33727d10d5a6Sdrh   if( k<pEList->nExpr ){
33737d10d5a6Sdrh     /*
33747d10d5a6Sdrh     ** If we get here it means the result set contains one or more "*"
33757d10d5a6Sdrh     ** operators that need to be expanded.  Loop through each expression
33767d10d5a6Sdrh     ** in the result set and expand them one by one.
33777d10d5a6Sdrh     */
33787d10d5a6Sdrh     struct ExprList_item *a = pEList->a;
33797d10d5a6Sdrh     ExprList *pNew = 0;
33807d10d5a6Sdrh     int flags = pParse->db->flags;
33817d10d5a6Sdrh     int longNames = (flags & SQLITE_FullColNames)!=0
33827d10d5a6Sdrh                       && (flags & SQLITE_ShortColNames)==0;
33837d10d5a6Sdrh 
33847d10d5a6Sdrh     for(k=0; k<pEList->nExpr; k++){
33857d10d5a6Sdrh       Expr *pE = a[k].pExpr;
338643152cf8Sdrh       assert( pE->op!=TK_DOT || pE->pRight!=0 );
338743152cf8Sdrh       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
33887d10d5a6Sdrh         /* This particular expression does not need to be expanded.
33897d10d5a6Sdrh         */
3390b7916a78Sdrh         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
33917d10d5a6Sdrh         if( pNew ){
33927d10d5a6Sdrh           pNew->a[pNew->nExpr-1].zName = a[k].zName;
3393b7916a78Sdrh           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
3394b7916a78Sdrh           a[k].zName = 0;
3395b7916a78Sdrh           a[k].zSpan = 0;
33967d10d5a6Sdrh         }
33977d10d5a6Sdrh         a[k].pExpr = 0;
33987d10d5a6Sdrh       }else{
33997d10d5a6Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
34007d10d5a6Sdrh         ** expanded. */
34017d10d5a6Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
34027d10d5a6Sdrh         char *zTName;            /* text of name of TABLE */
340343152cf8Sdrh         if( pE->op==TK_DOT ){
340443152cf8Sdrh           assert( pE->pLeft!=0 );
340533e619fcSdrh           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
340633e619fcSdrh           zTName = pE->pLeft->u.zToken;
34077d10d5a6Sdrh         }else{
34087d10d5a6Sdrh           zTName = 0;
34097d10d5a6Sdrh         }
34107d10d5a6Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
34117d10d5a6Sdrh           Table *pTab = pFrom->pTab;
34127d10d5a6Sdrh           char *zTabName = pFrom->zAlias;
341343152cf8Sdrh           if( zTabName==0 ){
34147d10d5a6Sdrh             zTabName = pTab->zName;
34157d10d5a6Sdrh           }
34167d10d5a6Sdrh           if( db->mallocFailed ) break;
34177d10d5a6Sdrh           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
34187d10d5a6Sdrh             continue;
34197d10d5a6Sdrh           }
34207d10d5a6Sdrh           tableSeen = 1;
34217d10d5a6Sdrh           for(j=0; j<pTab->nCol; j++){
34227d10d5a6Sdrh             Expr *pExpr, *pRight;
34237d10d5a6Sdrh             char *zName = pTab->aCol[j].zName;
3424b7916a78Sdrh             char *zColname;  /* The computed column name */
3425b7916a78Sdrh             char *zToFree;   /* Malloced string that needs to be freed */
3426b7916a78Sdrh             Token sColname;  /* Computed column name as a token */
34277d10d5a6Sdrh 
34287d10d5a6Sdrh             /* If a column is marked as 'hidden' (currently only possible
34297d10d5a6Sdrh             ** for virtual tables), do not include it in the expanded
34307d10d5a6Sdrh             ** result-set list.
34317d10d5a6Sdrh             */
34327d10d5a6Sdrh             if( IsHiddenColumn(&pTab->aCol[j]) ){
34337d10d5a6Sdrh               assert(IsVirtual(pTab));
34347d10d5a6Sdrh               continue;
34357d10d5a6Sdrh             }
34367d10d5a6Sdrh 
3437da55c48aSdrh             if( i>0 && zTName==0 ){
34382179b434Sdrh               if( (pFrom->jointype & JT_NATURAL)!=0
34392179b434Sdrh                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
34402179b434Sdrh               ){
34417d10d5a6Sdrh                 /* In a NATURAL join, omit the join columns from the
34422179b434Sdrh                 ** table to the right of the join */
34437d10d5a6Sdrh                 continue;
34447d10d5a6Sdrh               }
34452179b434Sdrh               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
34467d10d5a6Sdrh                 /* In a join with a USING clause, omit columns in the
34477d10d5a6Sdrh                 ** using clause from the table on the right. */
34487d10d5a6Sdrh                 continue;
34497d10d5a6Sdrh               }
34507d10d5a6Sdrh             }
3451b7916a78Sdrh             pRight = sqlite3Expr(db, TK_ID, zName);
3452b7916a78Sdrh             zColname = zName;
3453b7916a78Sdrh             zToFree = 0;
34547d10d5a6Sdrh             if( longNames || pTabList->nSrc>1 ){
3455b7916a78Sdrh               Expr *pLeft;
3456b7916a78Sdrh               pLeft = sqlite3Expr(db, TK_ID, zTabName);
34577d10d5a6Sdrh               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
3458b7916a78Sdrh               if( longNames ){
3459b7916a78Sdrh                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
3460b7916a78Sdrh                 zToFree = zColname;
3461b7916a78Sdrh               }
34627d10d5a6Sdrh             }else{
34637d10d5a6Sdrh               pExpr = pRight;
34647d10d5a6Sdrh             }
3465b7916a78Sdrh             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
3466b7916a78Sdrh             sColname.z = zColname;
3467b7916a78Sdrh             sColname.n = sqlite3Strlen30(zColname);
3468b7916a78Sdrh             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
3469b7916a78Sdrh             sqlite3DbFree(db, zToFree);
34707d10d5a6Sdrh           }
34717d10d5a6Sdrh         }
34727d10d5a6Sdrh         if( !tableSeen ){
34737d10d5a6Sdrh           if( zTName ){
34747d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
34757d10d5a6Sdrh           }else{
34767d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no tables specified");
34777d10d5a6Sdrh           }
34787d10d5a6Sdrh         }
34797d10d5a6Sdrh       }
34807d10d5a6Sdrh     }
34817d10d5a6Sdrh     sqlite3ExprListDelete(db, pEList);
34827d10d5a6Sdrh     p->pEList = pNew;
34837d10d5a6Sdrh   }
34847d10d5a6Sdrh #if SQLITE_MAX_COLUMN
34857d10d5a6Sdrh   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
34867d10d5a6Sdrh     sqlite3ErrorMsg(pParse, "too many columns in result set");
34877d10d5a6Sdrh   }
34887d10d5a6Sdrh #endif
34897d10d5a6Sdrh   return WRC_Continue;
34907d10d5a6Sdrh }
34917d10d5a6Sdrh 
34927d10d5a6Sdrh /*
34937d10d5a6Sdrh ** No-op routine for the parse-tree walker.
34947d10d5a6Sdrh **
34957d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees
34967d10d5a6Sdrh ** are walked without any actions being taken at each node.  Presumably,
34977d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then
34987d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every
34997d10d5a6Sdrh ** subquery in the parser tree.
35007d10d5a6Sdrh */
350162c14b34Sdanielk1977 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
350262c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
35037d10d5a6Sdrh   return WRC_Continue;
35047d10d5a6Sdrh }
35057d10d5a6Sdrh 
35067d10d5a6Sdrh /*
35077d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries.
35087d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT
35097d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above.
35107d10d5a6Sdrh **
35117d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a
35127d10d5a6Sdrh ** SELECT statement.  The SELECT statement must be expanded before
35137d10d5a6Sdrh ** name resolution is performed.
35147d10d5a6Sdrh **
35157d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse.
35167d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr
35177d10d5a6Sdrh ** and/or pParse->db->mallocFailed.
35187d10d5a6Sdrh */
35197d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
35207d10d5a6Sdrh   Walker w;
35217d10d5a6Sdrh   w.xSelectCallback = selectExpander;
35227d10d5a6Sdrh   w.xExprCallback = exprWalkNoop;
35237d10d5a6Sdrh   w.pParse = pParse;
35247d10d5a6Sdrh   sqlite3WalkSelect(&w, pSelect);
35257d10d5a6Sdrh }
35267d10d5a6Sdrh 
35277d10d5a6Sdrh 
35287d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
35297d10d5a6Sdrh /*
35307d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
35317d10d5a6Sdrh ** interface.
35327d10d5a6Sdrh **
35337d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl
35347d10d5a6Sdrh ** information to the Table structure that represents the result set
35357d10d5a6Sdrh ** of that subquery.
35367d10d5a6Sdrh **
35377d10d5a6Sdrh ** The Table structure that represents the result set was constructed
35387d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted
35397d10d5a6Sdrh ** at that point because identifiers had not yet been resolved.  This
35407d10d5a6Sdrh ** routine is called after identifier resolution.
35417d10d5a6Sdrh */
35427d10d5a6Sdrh static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
35437d10d5a6Sdrh   Parse *pParse;
35447d10d5a6Sdrh   int i;
35457d10d5a6Sdrh   SrcList *pTabList;
35467d10d5a6Sdrh   struct SrcList_item *pFrom;
35477d10d5a6Sdrh 
35489d8b3072Sdrh   assert( p->selFlags & SF_Resolved );
35495a29d9cbSdrh   if( (p->selFlags & SF_HasTypeInfo)==0 ){
35507d10d5a6Sdrh     p->selFlags |= SF_HasTypeInfo;
35517d10d5a6Sdrh     pParse = pWalker->pParse;
35527d10d5a6Sdrh     pTabList = p->pSrc;
35537d10d5a6Sdrh     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
35547d10d5a6Sdrh       Table *pTab = pFrom->pTab;
355543152cf8Sdrh       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
35567d10d5a6Sdrh         /* A sub-query in the FROM clause of a SELECT */
35577d10d5a6Sdrh         Select *pSel = pFrom->pSelect;
35587d10d5a6Sdrh         assert( pSel );
35597d10d5a6Sdrh         while( pSel->pPrior ) pSel = pSel->pPrior;
35607d10d5a6Sdrh         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
35617d10d5a6Sdrh       }
35627d10d5a6Sdrh     }
35635a29d9cbSdrh   }
35647d10d5a6Sdrh   return WRC_Continue;
35657d10d5a6Sdrh }
35667d10d5a6Sdrh #endif
35677d10d5a6Sdrh 
35687d10d5a6Sdrh 
35697d10d5a6Sdrh /*
35707d10d5a6Sdrh ** This routine adds datatype and collating sequence information to
35717d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a
35727d10d5a6Sdrh ** SELECT statement.
35737d10d5a6Sdrh **
35747d10d5a6Sdrh ** Use this routine after name resolution.
35757d10d5a6Sdrh */
35767d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
35777d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
35787d10d5a6Sdrh   Walker w;
35797d10d5a6Sdrh   w.xSelectCallback = selectAddSubqueryTypeInfo;
35807d10d5a6Sdrh   w.xExprCallback = exprWalkNoop;
35817d10d5a6Sdrh   w.pParse = pParse;
35827d10d5a6Sdrh   sqlite3WalkSelect(&w, pSelect);
35837d10d5a6Sdrh #endif
35847d10d5a6Sdrh }
35857d10d5a6Sdrh 
35867d10d5a6Sdrh 
35877d10d5a6Sdrh /*
3588030796dfSdrh ** This routine sets up a SELECT statement for processing.  The
35897d10d5a6Sdrh ** following is accomplished:
35907d10d5a6Sdrh **
35917d10d5a6Sdrh **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
35927d10d5a6Sdrh **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
35937d10d5a6Sdrh **     *  ON and USING clauses are shifted into WHERE statements
35947d10d5a6Sdrh **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
35957d10d5a6Sdrh **     *  Identifiers in expression are matched to tables.
35967d10d5a6Sdrh **
35977d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT.
35987d10d5a6Sdrh */
35997d10d5a6Sdrh void sqlite3SelectPrep(
3600b3bce662Sdanielk1977   Parse *pParse,         /* The parser context */
3601b3bce662Sdanielk1977   Select *p,             /* The SELECT statement being coded. */
36027d10d5a6Sdrh   NameContext *pOuterNC  /* Name context for container */
3603b3bce662Sdanielk1977 ){
36047d10d5a6Sdrh   sqlite3 *db;
360543152cf8Sdrh   if( NEVER(p==0) ) return;
36067d10d5a6Sdrh   db = pParse->db;
36077d10d5a6Sdrh   if( p->selFlags & SF_HasTypeInfo ) return;
36087d10d5a6Sdrh   sqlite3SelectExpand(pParse, p);
36097d10d5a6Sdrh   if( pParse->nErr || db->mallocFailed ) return;
36107d10d5a6Sdrh   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
36117d10d5a6Sdrh   if( pParse->nErr || db->mallocFailed ) return;
36127d10d5a6Sdrh   sqlite3SelectAddTypeInfo(pParse, p);
3613f6bbe022Sdrh }
3614b3bce662Sdanielk1977 
3615b3bce662Sdanielk1977 /*
361613449892Sdrh ** Reset the aggregate accumulator.
361713449892Sdrh **
361813449892Sdrh ** The aggregate accumulator is a set of memory cells that hold
361913449892Sdrh ** intermediate results while calculating an aggregate.  This
3620030796dfSdrh ** routine generates code that stores NULLs in all of those memory
3621030796dfSdrh ** cells.
3622b3bce662Sdanielk1977 */
362313449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
362413449892Sdrh   Vdbe *v = pParse->pVdbe;
362513449892Sdrh   int i;
3626c99130fdSdrh   struct AggInfo_func *pFunc;
362713449892Sdrh   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
362813449892Sdrh     return;
362913449892Sdrh   }
363013449892Sdrh   for(i=0; i<pAggInfo->nColumn; i++){
36314c583128Sdrh     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
363213449892Sdrh   }
3633c99130fdSdrh   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
36344c583128Sdrh     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
3635c99130fdSdrh     if( pFunc->iDistinct>=0 ){
3636c99130fdSdrh       Expr *pE = pFunc->pExpr;
36376ab3a2ecSdanielk1977       assert( !ExprHasProperty(pE, EP_xIsSelect) );
36386ab3a2ecSdanielk1977       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
36390daa002cSdrh         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
36400daa002cSdrh            "argument");
3641c99130fdSdrh         pFunc->iDistinct = -1;
3642c99130fdSdrh       }else{
36436ab3a2ecSdanielk1977         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
364466a5167bSdrh         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
364566a5167bSdrh                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
3646c99130fdSdrh       }
3647c99130fdSdrh     }
364813449892Sdrh   }
3649b3bce662Sdanielk1977 }
3650b3bce662Sdanielk1977 
3651b3bce662Sdanielk1977 /*
365213449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function
365313449892Sdrh ** in the AggInfo structure.
3654b3bce662Sdanielk1977 */
365513449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
365613449892Sdrh   Vdbe *v = pParse->pVdbe;
365713449892Sdrh   int i;
365813449892Sdrh   struct AggInfo_func *pF;
365913449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
36606ab3a2ecSdanielk1977     ExprList *pList = pF->pExpr->x.pList;
36616ab3a2ecSdanielk1977     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
366266a5167bSdrh     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
366366a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
3664b3bce662Sdanielk1977   }
366513449892Sdrh }
366613449892Sdrh 
366713449892Sdrh /*
366813449892Sdrh ** Update the accumulator memory cells for an aggregate based on
366913449892Sdrh ** the current cursor position.
367013449892Sdrh */
367113449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
367213449892Sdrh   Vdbe *v = pParse->pVdbe;
367313449892Sdrh   int i;
36747a95789cSdrh   int regHit = 0;
36757a95789cSdrh   int addrHitTest = 0;
367613449892Sdrh   struct AggInfo_func *pF;
367713449892Sdrh   struct AggInfo_col *pC;
367813449892Sdrh 
367913449892Sdrh   pAggInfo->directMode = 1;
3680ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
368113449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
368213449892Sdrh     int nArg;
3683c99130fdSdrh     int addrNext = 0;
368498757157Sdrh     int regAgg;
36856ab3a2ecSdanielk1977     ExprList *pList = pF->pExpr->x.pList;
36866ab3a2ecSdanielk1977     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
368713449892Sdrh     if( pList ){
368813449892Sdrh       nArg = pList->nExpr;
3689892d3179Sdrh       regAgg = sqlite3GetTempRange(pParse, nArg);
36907153d1fbSdrh       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
369113449892Sdrh     }else{
369213449892Sdrh       nArg = 0;
369398757157Sdrh       regAgg = 0;
369413449892Sdrh     }
3695c99130fdSdrh     if( pF->iDistinct>=0 ){
3696c99130fdSdrh       addrNext = sqlite3VdbeMakeLabel(v);
3697c99130fdSdrh       assert( nArg==1 );
36982dcef11bSdrh       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
3699c99130fdSdrh     }
3700e82f5d04Sdrh     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
370113449892Sdrh       CollSeq *pColl = 0;
370213449892Sdrh       struct ExprList_item *pItem;
370313449892Sdrh       int j;
3704e82f5d04Sdrh       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
370543617e9aSdrh       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
370613449892Sdrh         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
370713449892Sdrh       }
370813449892Sdrh       if( !pColl ){
370913449892Sdrh         pColl = pParse->db->pDfltColl;
371013449892Sdrh       }
37117a95789cSdrh       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
37127a95789cSdrh       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
371313449892Sdrh     }
371498757157Sdrh     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
371566a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
3716ea678832Sdrh     sqlite3VdbeChangeP5(v, (u8)nArg);
3717da250ea5Sdrh     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
3718f49f3523Sdrh     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
3719c99130fdSdrh     if( addrNext ){
3720c99130fdSdrh       sqlite3VdbeResolveLabel(v, addrNext);
3721ceea3321Sdrh       sqlite3ExprCacheClear(pParse);
3722c99130fdSdrh     }
372313449892Sdrh   }
372467a6a40cSdan 
372567a6a40cSdan   /* Before populating the accumulator registers, clear the column cache.
372667a6a40cSdan   ** Otherwise, if any of the required column values are already present
372767a6a40cSdan   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
372867a6a40cSdan   ** to pC->iMem. But by the time the value is used, the original register
372967a6a40cSdan   ** may have been used, invalidating the underlying buffer holding the
373067a6a40cSdan   ** text or blob value. See ticket [883034dcb5].
373167a6a40cSdan   **
373267a6a40cSdan   ** Another solution would be to change the OP_SCopy used to copy cached
373367a6a40cSdan   ** values to an OP_Copy.
373467a6a40cSdan   */
37357a95789cSdrh   if( regHit ){
37367a95789cSdrh     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
37377a95789cSdrh   }
373867a6a40cSdan   sqlite3ExprCacheClear(pParse);
373913449892Sdrh   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
3740389a1adbSdrh     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
374113449892Sdrh   }
374213449892Sdrh   pAggInfo->directMode = 0;
3743ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
37447a95789cSdrh   if( addrHitTest ){
37457a95789cSdrh     sqlite3VdbeJumpHere(v, addrHitTest);
37467a95789cSdrh   }
374713449892Sdrh }
374813449892Sdrh 
3749b3bce662Sdanielk1977 /*
3750ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple
3751ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab").
3752ef7075deSdan */
3753ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN
3754ef7075deSdan static void explainSimpleCount(
3755ef7075deSdan   Parse *pParse,                  /* Parse context */
3756ef7075deSdan   Table *pTab,                    /* Table being queried */
3757ef7075deSdan   Index *pIdx                     /* Index used to optimize scan, or NULL */
3758ef7075deSdan ){
3759ef7075deSdan   if( pParse->explain==2 ){
3760ef7075deSdan     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
3761ef7075deSdan         pTab->zName,
3762ef7075deSdan         pIdx ? "USING COVERING INDEX " : "",
3763ef7075deSdan         pIdx ? pIdx->zName : "",
3764ef7075deSdan         pTab->nRowEst
3765ef7075deSdan     );
3766ef7075deSdan     sqlite3VdbeAddOp4(
3767ef7075deSdan         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
3768ef7075deSdan     );
3769ef7075deSdan   }
3770ef7075deSdan }
3771ef7075deSdan #else
3772ef7075deSdan # define explainSimpleCount(a,b,c)
3773ef7075deSdan #endif
3774ef7075deSdan 
3775ef7075deSdan /*
37767d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument.
37779bb61fe7Sdrh **
3778fef5208cSdrh ** The results are distributed in various ways depending on the
37796c8c8ce0Sdanielk1977 ** contents of the SelectDest structure pointed to by argument pDest
37806c8c8ce0Sdanielk1977 ** as follows:
3781fef5208cSdrh **
37826c8c8ce0Sdanielk1977 **     pDest->eDest    Result
3783fef5208cSdrh **     ------------    -------------------------------------------
37847d10d5a6Sdrh **     SRT_Output      Generate a row of output (using the OP_ResultRow
37857d10d5a6Sdrh **                     opcode) for each row in the result set.
3786fef5208cSdrh **
37877d10d5a6Sdrh **     SRT_Mem         Only valid if the result is a single column.
37887d10d5a6Sdrh **                     Store the first column of the first result row
37892b596da8Sdrh **                     in register pDest->iSDParm then abandon the rest
37907d10d5a6Sdrh **                     of the query.  This destination implies "LIMIT 1".
3791fef5208cSdrh **
37927d10d5a6Sdrh **     SRT_Set         The result must be a single column.  Store each
37932b596da8Sdrh **                     row of result as the key in table pDest->iSDParm.
3794c041c16cSdrh **                     Apply the affinity pDest->affSdst before storing
37957d10d5a6Sdrh **                     results.  Used to implement "IN (SELECT ...)".
3796fef5208cSdrh **
37972b596da8Sdrh **     SRT_Union       Store results as a key in a temporary table
37982b596da8Sdrh **                     identified by pDest->iSDParm.
379982c3d636Sdrh **
38002b596da8Sdrh **     SRT_Except      Remove results from the temporary table pDest->iSDParm.
3801c4a3c779Sdrh **
38022b596da8Sdrh **     SRT_Table       Store results in temporary table pDest->iSDParm.
38037d10d5a6Sdrh **                     This is like SRT_EphemTab except that the table
38047d10d5a6Sdrh **                     is assumed to already be open.
38059bb61fe7Sdrh **
38062b596da8Sdrh **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
38076c8c8ce0Sdanielk1977 **                     the result there. The cursor is left open after
38087d10d5a6Sdrh **                     returning.  This is like SRT_Table except that
38097d10d5a6Sdrh **                     this destination uses OP_OpenEphemeral to create
38107d10d5a6Sdrh **                     the table first.
38116c8c8ce0Sdanielk1977 **
38127d10d5a6Sdrh **     SRT_Coroutine   Generate a co-routine that returns a new row of
38137d10d5a6Sdrh **                     results each time it is invoked.  The entry point
38142b596da8Sdrh **                     of the co-routine is stored in register pDest->iSDParm.
38156c8c8ce0Sdanielk1977 **
38162b596da8Sdrh **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
38176c8c8ce0Sdanielk1977 **                     set is not empty.
38186c8c8ce0Sdanielk1977 **
38197d10d5a6Sdrh **     SRT_Discard     Throw the results away.  This is used by SELECT
38207d10d5a6Sdrh **                     statements within triggers whose only purpose is
38217d10d5a6Sdrh **                     the side-effects of functions.
3822e78e8284Sdrh **
38239bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
38249bb61fe7Sdrh ** encountered, then an appropriate error message is left in
38259bb61fe7Sdrh ** pParse->zErrMsg.
38269bb61fe7Sdrh **
38279bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
38289bb61fe7Sdrh ** calling function needs to do that.
38299bb61fe7Sdrh */
38304adee20fSdanielk1977 int sqlite3Select(
3831cce7d176Sdrh   Parse *pParse,         /* The parser context */
38329bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
38337d10d5a6Sdrh   SelectDest *pDest      /* What to do with the query results */
3834cce7d176Sdrh ){
383513449892Sdrh   int i, j;              /* Loop counters */
383613449892Sdrh   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
383713449892Sdrh   Vdbe *v;               /* The virtual machine under construction */
3838b3bce662Sdanielk1977   int isAgg;             /* True for select lists like "count(*)" */
3839a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
3840ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
38419bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
38429bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
38432282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
38442282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
38451d83f052Sdrh   int rc = 1;            /* Value to return from this function */
3846b9bb7c18Sdrh   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
3847e8e4af76Sdrh   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
384813449892Sdrh   AggInfo sAggInfo;      /* Information used by aggregate queries */
3849ec7429aeSdrh   int iEnd;              /* Address of the end of the query */
385017435752Sdrh   sqlite3 *db;           /* The database connection */
38519bb61fe7Sdrh 
38522ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN
38532ce22453Sdan   int iRestoreSelectId = pParse->iSelectId;
38542ce22453Sdan   pParse->iSelectId = pParse->iNextSelectId++;
38552ce22453Sdan #endif
38562ce22453Sdan 
385717435752Sdrh   db = pParse->db;
385817435752Sdrh   if( p==0 || db->mallocFailed || pParse->nErr ){
38596f7adc8aSdrh     return 1;
38606f7adc8aSdrh   }
38614adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
386213449892Sdrh   memset(&sAggInfo, 0, sizeof(sAggInfo));
3863daffd0e5Sdrh 
38646c8c8ce0Sdanielk1977   if( IgnorableOrderby(pDest) ){
38659ed1dfa8Sdanielk1977     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
38669ed1dfa8Sdanielk1977            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
3867ccfcbceaSdrh     /* If ORDER BY makes no difference in the output then neither does
3868ccfcbceaSdrh     ** DISTINCT so it can be removed too. */
3869ccfcbceaSdrh     sqlite3ExprListDelete(db, p->pOrderBy);
3870ccfcbceaSdrh     p->pOrderBy = 0;
38717d10d5a6Sdrh     p->selFlags &= ~SF_Distinct;
38729a99334dSdrh   }
38737d10d5a6Sdrh   sqlite3SelectPrep(pParse, p, 0);
3874ccfcbceaSdrh   pOrderBy = p->pOrderBy;
3875b27b7f5dSdrh   pTabList = p->pSrc;
3876b27b7f5dSdrh   pEList = p->pEList;
3877956f4319Sdanielk1977   if( pParse->nErr || db->mallocFailed ){
38789a99334dSdrh     goto select_end;
38799a99334dSdrh   }
38807d10d5a6Sdrh   isAgg = (p->selFlags & SF_Aggregate)!=0;
388143152cf8Sdrh   assert( pEList!=0 );
3882cce7d176Sdrh 
3883d820cb1bSdrh   /* Begin generating code.
3884d820cb1bSdrh   */
38854adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
3886d820cb1bSdrh   if( v==0 ) goto select_end;
3887d820cb1bSdrh 
388874b617b2Sdan   /* If writing to memory or generating a set
388974b617b2Sdan   ** only a single column may be output.
389074b617b2Sdan   */
389174b617b2Sdan #ifndef SQLITE_OMIT_SUBQUERY
389274b617b2Sdan   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
389374b617b2Sdan     goto select_end;
389474b617b2Sdan   }
389574b617b2Sdan #endif
389674b617b2Sdan 
3897d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
3898d820cb1bSdrh   */
389951522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3900f23329a2Sdanielk1977   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
390113449892Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
39021013c932Sdrh     SelectDest dest;
3903daf79acbSdanielk1977     Select *pSub = pItem->pSelect;
3904f23329a2Sdanielk1977     int isAggSub;
3905c31c2eb8Sdrh 
39065b6a9ed4Sdrh     if( pSub==0 ) continue;
390721172c4cSdrh 
390821172c4cSdrh     /* Sometimes the code for a subquery will be generated more than
390921172c4cSdrh     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
391021172c4cSdrh     ** for example.  In that case, do not regenerate the code to manifest
391121172c4cSdrh     ** a view or the co-routine to implement a view.  The first instance
391221172c4cSdrh     ** is sufficient, though the subroutine to manifest the view does need
391321172c4cSdrh     ** to be invoked again. */
39145b6a9ed4Sdrh     if( pItem->addrFillSub ){
391521172c4cSdrh       if( pItem->viaCoroutine==0 ){
39165b6a9ed4Sdrh         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
391721172c4cSdrh       }
39185b6a9ed4Sdrh       continue;
39195b6a9ed4Sdrh     }
3920daf79acbSdanielk1977 
3921fc976065Sdanielk1977     /* Increment Parse.nHeight by the height of the largest expression
3922fc976065Sdanielk1977     ** tree refered to by this, the parent select. The child select
3923fc976065Sdanielk1977     ** may contain expression trees of at most
3924fc976065Sdanielk1977     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
3925fc976065Sdanielk1977     ** more conservative than necessary, but much easier than enforcing
3926fc976065Sdanielk1977     ** an exact limit.
3927fc976065Sdanielk1977     */
3928fc976065Sdanielk1977     pParse->nHeight += sqlite3SelectExprHeight(p);
3929daf79acbSdanielk1977 
39307d10d5a6Sdrh     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
3931524cc21eSdanielk1977     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
39325b6a9ed4Sdrh       /* This subquery can be absorbed into its parent. */
3933f23329a2Sdanielk1977       if( isAggSub ){
39347d10d5a6Sdrh         isAgg = 1;
39357d10d5a6Sdrh         p->selFlags |= SF_Aggregate;
3936daf79acbSdanielk1977       }
3937daf79acbSdanielk1977       i = -1;
3938a5759677Sdrh     }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0
3939a5759677Sdrh       && OptimizationEnabled(db, SQLITE_SubqCoroutine)
3940a5759677Sdrh     ){
394121172c4cSdrh       /* Implement a co-routine that will return a single row of the result
394221172c4cSdrh       ** set on each invocation.
394321172c4cSdrh       */
394421172c4cSdrh       int addrTop;
394521172c4cSdrh       int addrEof;
394621172c4cSdrh       pItem->regReturn = ++pParse->nMem;
394721172c4cSdrh       addrEof = ++pParse->nMem;
394821172c4cSdrh       sqlite3VdbeAddOp0(v, OP_Goto);
394921172c4cSdrh       addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
395021172c4cSdrh       sqlite3VdbeChangeP5(v, 1);
395121172c4cSdrh       VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
395221172c4cSdrh       pItem->addrFillSub = addrTop;
395321172c4cSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
395421172c4cSdrh       sqlite3VdbeChangeP5(v, 1);
395521172c4cSdrh       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
395621172c4cSdrh       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
395721172c4cSdrh       sqlite3Select(pParse, pSub, &dest);
395821172c4cSdrh       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
395921172c4cSdrh       pItem->viaCoroutine = 1;
396021172c4cSdrh       sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
396121172c4cSdrh       sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
396221172c4cSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
396321172c4cSdrh       sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
396421172c4cSdrh       VdbeComment((v, "end %s", pItem->pTab->zName));
396521172c4cSdrh       sqlite3VdbeJumpHere(v, addrTop-1);
396621172c4cSdrh       sqlite3ClearTempRegCache(pParse);
3967daf79acbSdanielk1977     }else{
39685b6a9ed4Sdrh       /* Generate a subroutine that will fill an ephemeral table with
39695b6a9ed4Sdrh       ** the content of this subquery.  pItem->addrFillSub will point
39705b6a9ed4Sdrh       ** to the address of the generated subroutine.  pItem->regReturn
39715b6a9ed4Sdrh       ** is a register allocated to hold the subroutine return address
39725b6a9ed4Sdrh       */
39737157e8eaSdrh       int topAddr;
397448f2d3b1Sdrh       int onceAddr = 0;
39757157e8eaSdrh       int retAddr;
39765b6a9ed4Sdrh       assert( pItem->addrFillSub==0 );
39775b6a9ed4Sdrh       pItem->regReturn = ++pParse->nMem;
39787157e8eaSdrh       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
39797157e8eaSdrh       pItem->addrFillSub = topAddr+1;
39807157e8eaSdrh       VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
39811d8cb21fSdan       if( pItem->isCorrelated==0 ){
39825b6a9ed4Sdrh         /* If the subquery is no correlated and if we are not inside of
39835b6a9ed4Sdrh         ** a trigger, then we only need to compute the value of the subquery
39845b6a9ed4Sdrh         ** once. */
39851d8cb21fSdan         onceAddr = sqlite3CodeOnce(pParse);
39865b6a9ed4Sdrh       }
39871013c932Sdrh       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
3988ce7e189dSdan       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
39897d10d5a6Sdrh       sqlite3Select(pParse, pSub, &dest);
399095aa47b1Sdrh       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
399148f2d3b1Sdrh       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
39927157e8eaSdrh       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
39937157e8eaSdrh       VdbeComment((v, "end %s", pItem->pTab->zName));
39947157e8eaSdrh       sqlite3VdbeChangeP1(v, topAddr, retAddr);
3995cdc69557Sdrh       sqlite3ClearTempRegCache(pParse);
3996daf79acbSdanielk1977     }
399743152cf8Sdrh     if( /*pParse->nErr ||*/ db->mallocFailed ){
3998cfa063b3Sdrh       goto select_end;
3999cfa063b3Sdrh     }
4000fc976065Sdanielk1977     pParse->nHeight -= sqlite3SelectExprHeight(p);
4001832508b7Sdrh     pTabList = p->pSrc;
40026c8c8ce0Sdanielk1977     if( !IgnorableOrderby(pDest) ){
4003832508b7Sdrh       pOrderBy = p->pOrderBy;
4004acd4c695Sdrh     }
4005daf79acbSdanielk1977   }
4006daf79acbSdanielk1977   pEList = p->pEList;
4007daf79acbSdanielk1977 #endif
4008daf79acbSdanielk1977   pWhere = p->pWhere;
4009832508b7Sdrh   pGroupBy = p->pGroupBy;
4010832508b7Sdrh   pHaving = p->pHaving;
4011e8e4af76Sdrh   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
4012832508b7Sdrh 
4013f23329a2Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
4014f23329a2Sdanielk1977   /* If there is are a sequence of queries, do the earlier ones first.
4015f23329a2Sdanielk1977   */
4016f23329a2Sdanielk1977   if( p->pPrior ){
4017f23329a2Sdanielk1977     if( p->pRightmost==0 ){
4018f23329a2Sdanielk1977       Select *pLoop, *pRight = 0;
4019f23329a2Sdanielk1977       int cnt = 0;
4020f23329a2Sdanielk1977       int mxSelect;
4021f23329a2Sdanielk1977       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
4022f23329a2Sdanielk1977         pLoop->pRightmost = p;
4023f23329a2Sdanielk1977         pLoop->pNext = pRight;
4024f23329a2Sdanielk1977         pRight = pLoop;
4025f23329a2Sdanielk1977       }
4026f23329a2Sdanielk1977       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
4027f23329a2Sdanielk1977       if( mxSelect && cnt>mxSelect ){
4028f23329a2Sdanielk1977         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
40292ce22453Sdan         goto select_end;
4030f23329a2Sdanielk1977       }
4031f23329a2Sdanielk1977     }
40327f61e92cSdan     rc = multiSelect(pParse, p, pDest);
403317c0bc0cSdan     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
40347f61e92cSdan     return rc;
4035f23329a2Sdanielk1977   }
4036f23329a2Sdanielk1977 #endif
4037f23329a2Sdanielk1977 
40388c6f666bSdrh   /* If there is both a GROUP BY and an ORDER BY clause and they are
40398c6f666bSdrh   ** identical, then disable the ORDER BY clause since the GROUP BY
40408c6f666bSdrh   ** will cause elements to come out in the correct order.  This is
40418c6f666bSdrh   ** an optimization - the correct answer should result regardless.
40428c6f666bSdrh   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
40438c6f666bSdrh   ** to disable this optimization for testing purposes.
40448c6f666bSdrh   */
40458c6f666bSdrh   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
40467e5418e4Sdrh          && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
40478c6f666bSdrh     pOrderBy = 0;
40488c6f666bSdrh   }
40498c6f666bSdrh 
405050118cdfSdan   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
405150118cdfSdan   ** if the select-list is the same as the ORDER BY list, then this query
405250118cdfSdan   ** can be rewritten as a GROUP BY. In other words, this:
405350118cdfSdan   **
405450118cdfSdan   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
405550118cdfSdan   **
405650118cdfSdan   ** is transformed to:
405750118cdfSdan   **
405850118cdfSdan   **     SELECT xyz FROM ... GROUP BY xyz
405950118cdfSdan   **
406050118cdfSdan   ** The second form is preferred as a single index (or temp-table) may be
406150118cdfSdan   ** used for both the ORDER BY and DISTINCT processing. As originally
406250118cdfSdan   ** written the query must use a temp-table for at least one of the ORDER
406350118cdfSdan   ** BY and DISTINCT, and an index or separate temp-table for the other.
406450118cdfSdan   */
406550118cdfSdan   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
406650118cdfSdan    && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
406750118cdfSdan   ){
406850118cdfSdan     p->selFlags &= ~SF_Distinct;
406950118cdfSdan     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
407050118cdfSdan     pGroupBy = p->pGroupBy;
407150118cdfSdan     pOrderBy = 0;
4072e8e4af76Sdrh     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
4073e8e4af76Sdrh     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
4074e8e4af76Sdrh     ** original setting of the SF_Distinct flag, not the current setting */
4075e8e4af76Sdrh     assert( sDistinct.isTnct );
407650118cdfSdan   }
407750118cdfSdan 
40788b4c40d8Sdrh   /* If there is an ORDER BY clause, then this sorting
40798b4c40d8Sdrh   ** index might end up being unused if the data can be
40809d2985c7Sdrh   ** extracted in pre-sorted order.  If that is the case, then the
4081b9bb7c18Sdrh   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
40829d2985c7Sdrh   ** we figure out that the sorting index is not needed.  The addrSortIndex
40839d2985c7Sdrh   ** variable is used to facilitate that change.
40847cedc8d4Sdanielk1977   */
40857cedc8d4Sdanielk1977   if( pOrderBy ){
40860342b1f5Sdrh     KeyInfo *pKeyInfo;
40870342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
40889d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
4089b9bb7c18Sdrh     p->addrOpenEphm[2] = addrSortIndex =
409066a5167bSdrh       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
409166a5167bSdrh                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
409266a5167bSdrh                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
40939d2985c7Sdrh   }else{
40949d2985c7Sdrh     addrSortIndex = -1;
40957cedc8d4Sdanielk1977   }
40967cedc8d4Sdanielk1977 
40972d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
40982d0794e3Sdrh   */
40996c8c8ce0Sdanielk1977   if( pDest->eDest==SRT_EphemTab ){
41002b596da8Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
41012d0794e3Sdrh   }
41022d0794e3Sdrh 
4103f42bacc2Sdrh   /* Set the limiter.
4104f42bacc2Sdrh   */
4105f42bacc2Sdrh   iEnd = sqlite3VdbeMakeLabel(v);
410695aa47b1Sdrh   p->nSelectRow = (double)LARGEST_INT64;
4107f42bacc2Sdrh   computeLimitRegisters(pParse, p, iEnd);
4108c6aff30cSdrh   if( p->iLimit==0 && addrSortIndex>=0 ){
4109c6aff30cSdrh     sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
4110c6aff30cSdrh     p->selFlags |= SF_UseSorter;
4111c6aff30cSdrh   }
4112f42bacc2Sdrh 
4113dece1a84Sdrh   /* Open a virtual index to use for the distinct set.
4114cce7d176Sdrh   */
41152ce22453Sdan   if( p->selFlags & SF_Distinct ){
4116e8e4af76Sdrh     sDistinct.tabTnct = pParse->nTab++;
4117e8e4af76Sdrh     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
4118e8e4af76Sdrh                                 sDistinct.tabTnct, 0, 0,
4119e8e4af76Sdrh                                 (char*)keyInfoFromExprList(pParse, p->pEList),
4120e8e4af76Sdrh                                 P4_KEYINFO_HANDOFF);
4121d4187c71Sdrh     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
4122e8e4af76Sdrh     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
4123832508b7Sdrh   }else{
4124e8e4af76Sdrh     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
4125efb7251dSdrh   }
4126832508b7Sdrh 
412713449892Sdrh   if( !isAgg && pGroupBy==0 ){
4128e8e4af76Sdrh     /* No aggregate functions and no GROUP BY clause */
4129e8e4af76Sdrh     ExprList *pDist = (sDistinct.isTnct ? p->pEList : 0);
413038cc40c2Sdan 
413138cc40c2Sdan     /* Begin the database scan. */
413246ec5b63Sdrh     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, pDist, 0,0);
41331d83f052Sdrh     if( pWInfo==0 ) goto select_end;
413495aa47b1Sdrh     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
4135e8e4af76Sdrh     if( pWInfo->eDistinct ) sDistinct.eTnctType = pWInfo->eDistinct;
413646ec5b63Sdrh     if( pOrderBy && pWInfo->nOBSat==pOrderBy->nExpr ) pOrderBy = 0;
4137cce7d176Sdrh 
4138b9bb7c18Sdrh     /* If sorting index that was created by a prior OP_OpenEphemeral
4139b9bb7c18Sdrh     ** instruction ended up not being needed, then change the OP_OpenEphemeral
41409d2985c7Sdrh     ** into an OP_Noop.
41419d2985c7Sdrh     */
41429d2985c7Sdrh     if( addrSortIndex>=0 && pOrderBy==0 ){
414348f2d3b1Sdrh       sqlite3VdbeChangeToNoop(v, addrSortIndex);
4144b9bb7c18Sdrh       p->addrOpenEphm[2] = -1;
41459d2985c7Sdrh     }
41469d2985c7Sdrh 
414738cc40c2Sdan     /* Use the standard inner loop. */
4148e8e4af76Sdrh     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
4149a9671a22Sdrh                     pWInfo->iContinue, pWInfo->iBreak);
41502282792aSdrh 
4151cce7d176Sdrh     /* End the database scan loop.
4152cce7d176Sdrh     */
41534adee20fSdanielk1977     sqlite3WhereEnd(pWInfo);
415413449892Sdrh   }else{
4155e8e4af76Sdrh     /* This case when there exist aggregate functions or a GROUP BY clause
4156e8e4af76Sdrh     ** or both */
415713449892Sdrh     NameContext sNC;    /* Name context for processing aggregate information */
415813449892Sdrh     int iAMem;          /* First Mem address for storing current GROUP BY */
415913449892Sdrh     int iBMem;          /* First Mem address for previous GROUP BY */
416013449892Sdrh     int iUseFlag;       /* Mem address holding flag indicating that at least
416113449892Sdrh                         ** one row of the input to the aggregator has been
416213449892Sdrh                         ** processed */
416313449892Sdrh     int iAbortFlag;     /* Mem address which causes query abort if positive */
416413449892Sdrh     int groupBySort;    /* Rows come from source in GROUP BY order */
4165d176611bSdrh     int addrEnd;        /* End of processing for this SELECT */
41661c9d835dSdrh     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
41671c9d835dSdrh     int sortOut = 0;    /* Output register from the sorter */
4168d176611bSdrh 
4169d176611bSdrh     /* Remove any and all aliases between the result set and the
4170d176611bSdrh     ** GROUP BY clause.
4171d176611bSdrh     */
4172d176611bSdrh     if( pGroupBy ){
4173dc5ea5c7Sdrh       int k;                        /* Loop counter */
4174d176611bSdrh       struct ExprList_item *pItem;  /* For looping over expression in a list */
4175d176611bSdrh 
4176dc5ea5c7Sdrh       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
4177d176611bSdrh         pItem->iAlias = 0;
4178d176611bSdrh       }
4179dc5ea5c7Sdrh       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
4180d176611bSdrh         pItem->iAlias = 0;
4181d176611bSdrh       }
418295aa47b1Sdrh       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
418395aa47b1Sdrh     }else{
418495aa47b1Sdrh       p->nSelectRow = (double)1;
4185d176611bSdrh     }
4186cce7d176Sdrh 
418713449892Sdrh 
4188d176611bSdrh     /* Create a label to jump to when we want to abort the query */
418913449892Sdrh     addrEnd = sqlite3VdbeMakeLabel(v);
419013449892Sdrh 
419113449892Sdrh     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
419213449892Sdrh     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
419313449892Sdrh     ** SELECT statement.
41942282792aSdrh     */
419513449892Sdrh     memset(&sNC, 0, sizeof(sNC));
419613449892Sdrh     sNC.pParse = pParse;
419713449892Sdrh     sNC.pSrcList = pTabList;
419813449892Sdrh     sNC.pAggInfo = &sAggInfo;
419913449892Sdrh     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
42009d2985c7Sdrh     sAggInfo.pGroupBy = pGroupBy;
4201d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pEList);
4202d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
4203d2b3e23bSdrh     if( pHaving ){
4204d2b3e23bSdrh       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
420513449892Sdrh     }
420613449892Sdrh     sAggInfo.nAccumulator = sAggInfo.nColumn;
420713449892Sdrh     for(i=0; i<sAggInfo.nFunc; i++){
42086ab3a2ecSdanielk1977       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
42093a8c4be7Sdrh       sNC.ncFlags |= NC_InAggFunc;
42106ab3a2ecSdanielk1977       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
42113a8c4be7Sdrh       sNC.ncFlags &= ~NC_InAggFunc;
421213449892Sdrh     }
421317435752Sdrh     if( db->mallocFailed ) goto select_end;
421413449892Sdrh 
421513449892Sdrh     /* Processing for aggregates with GROUP BY is very different and
42163c4809a2Sdanielk1977     ** much more complex than aggregates without a GROUP BY.
421713449892Sdrh     */
421813449892Sdrh     if( pGroupBy ){
421913449892Sdrh       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
4220d176611bSdrh       int j1;             /* A-vs-B comparision jump */
4221d176611bSdrh       int addrOutputRow;  /* Start of subroutine that outputs a result row */
4222d176611bSdrh       int regOutputRow;   /* Return address register for output subroutine */
4223d176611bSdrh       int addrSetAbort;   /* Set the abort flag and return */
4224d176611bSdrh       int addrTopOfLoop;  /* Top of the input loop */
4225d176611bSdrh       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
4226d176611bSdrh       int addrReset;      /* Subroutine for resetting the accumulator */
4227d176611bSdrh       int regReset;       /* Return address register for reset subroutine */
422813449892Sdrh 
422913449892Sdrh       /* If there is a GROUP BY clause we might need a sorting index to
423013449892Sdrh       ** implement it.  Allocate that sorting index now.  If it turns out
42311c9d835dSdrh       ** that we do not need it after all, the OP_SorterOpen instruction
423213449892Sdrh       ** will be converted into a Noop.
423313449892Sdrh       */
423413449892Sdrh       sAggInfo.sortingIdx = pParse->nTab++;
423513449892Sdrh       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
42361c9d835dSdrh       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
4237cd3e8f7cSdanielk1977           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
4238cd3e8f7cSdanielk1977           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
423913449892Sdrh 
424013449892Sdrh       /* Initialize memory locations used by GROUP BY aggregate processing
424113449892Sdrh       */
42420a07c107Sdrh       iUseFlag = ++pParse->nMem;
42430a07c107Sdrh       iAbortFlag = ++pParse->nMem;
4244d176611bSdrh       regOutputRow = ++pParse->nMem;
4245d176611bSdrh       addrOutputRow = sqlite3VdbeMakeLabel(v);
4246d176611bSdrh       regReset = ++pParse->nMem;
4247d176611bSdrh       addrReset = sqlite3VdbeMakeLabel(v);
42480a07c107Sdrh       iAMem = pParse->nMem + 1;
424913449892Sdrh       pParse->nMem += pGroupBy->nExpr;
42500a07c107Sdrh       iBMem = pParse->nMem + 1;
425113449892Sdrh       pParse->nMem += pGroupBy->nExpr;
42524c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
4253d4e70ebdSdrh       VdbeComment((v, "clear abort flag"));
42544c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
4255d4e70ebdSdrh       VdbeComment((v, "indicate accumulator empty"));
4256b8475df8Sdrh       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
4257e313382eSdrh 
425813449892Sdrh       /* Begin a loop that will extract all source rows in GROUP BY order.
425913449892Sdrh       ** This might involve two separate loops with an OP_Sort in between, or
426013449892Sdrh       ** it might be a single loop that uses an index to extract information
426113449892Sdrh       ** in the right order to begin with.
426213449892Sdrh       */
42632eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
426446ec5b63Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 0, 0);
42655360ad34Sdrh       if( pWInfo==0 ) goto select_end;
426646ec5b63Sdrh       if( pWInfo->nOBSat==pGroupBy->nExpr ){
426713449892Sdrh         /* The optimizer is able to deliver rows in group by order so
4268b9bb7c18Sdrh         ** we do not have to sort.  The OP_OpenEphemeral table will be
426913449892Sdrh         ** cancelled later because we still need to use the pKeyInfo
427013449892Sdrh         */
427113449892Sdrh         groupBySort = 0;
427213449892Sdrh       }else{
427313449892Sdrh         /* Rows are coming out in undetermined order.  We have to push
427413449892Sdrh         ** each row into a sorting index, terminate the first loop,
427513449892Sdrh         ** then loop over the sorting index in order to get the output
427613449892Sdrh         ** in sorted order
427713449892Sdrh         */
4278892d3179Sdrh         int regBase;
4279892d3179Sdrh         int regRecord;
4280892d3179Sdrh         int nCol;
4281892d3179Sdrh         int nGroupBy;
4282892d3179Sdrh 
42832ce22453Sdan         explainTempTable(pParse,
4284e8e4af76Sdrh             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
4285e8e4af76Sdrh                     "DISTINCT" : "GROUP BY");
42862ce22453Sdan 
428713449892Sdrh         groupBySort = 1;
4288892d3179Sdrh         nGroupBy = pGroupBy->nExpr;
4289892d3179Sdrh         nCol = nGroupBy + 1;
4290892d3179Sdrh         j = nGroupBy+1;
429113449892Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
4292892d3179Sdrh           if( sAggInfo.aCol[i].iSorterColumn>=j ){
4293892d3179Sdrh             nCol++;
429413449892Sdrh             j++;
429513449892Sdrh           }
4296892d3179Sdrh         }
4297892d3179Sdrh         regBase = sqlite3GetTempRange(pParse, nCol);
4298ceea3321Sdrh         sqlite3ExprCacheClear(pParse);
4299191b54cbSdrh         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
4300892d3179Sdrh         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
4301892d3179Sdrh         j = nGroupBy+1;
4302892d3179Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
4303892d3179Sdrh           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
4304892d3179Sdrh           if( pCol->iSorterColumn>=j ){
4305e55cbd72Sdrh             int r1 = j + regBase;
43066a012f04Sdrh             int r2;
4307701bb3b4Sdrh 
43086a012f04Sdrh             r2 = sqlite3ExprCodeGetColumn(pParse,
4309a748fdccSdrh                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
43106a012f04Sdrh             if( r1!=r2 ){
43116a012f04Sdrh               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
43126a012f04Sdrh             }
43136a012f04Sdrh             j++;
4314892d3179Sdrh           }
4315892d3179Sdrh         }
4316892d3179Sdrh         regRecord = sqlite3GetTempReg(pParse);
43171db639ceSdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
43181c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
4319892d3179Sdrh         sqlite3ReleaseTempReg(pParse, regRecord);
4320892d3179Sdrh         sqlite3ReleaseTempRange(pParse, regBase, nCol);
432113449892Sdrh         sqlite3WhereEnd(pWInfo);
43225134d135Sdan         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
43231c9d835dSdrh         sortOut = sqlite3GetTempReg(pParse);
43241c9d835dSdrh         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
43251c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
4326d4e70ebdSdrh         VdbeComment((v, "GROUP BY sort"));
432713449892Sdrh         sAggInfo.useSortingIdx = 1;
4328ceea3321Sdrh         sqlite3ExprCacheClear(pParse);
432913449892Sdrh       }
433013449892Sdrh 
433113449892Sdrh       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
433213449892Sdrh       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
433313449892Sdrh       ** Then compare the current GROUP BY terms against the GROUP BY terms
433413449892Sdrh       ** from the previous row currently stored in a0, a1, a2...
433513449892Sdrh       */
433613449892Sdrh       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
4337ceea3321Sdrh       sqlite3ExprCacheClear(pParse);
43381c9d835dSdrh       if( groupBySort ){
43391c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
43401c9d835dSdrh       }
434113449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
434213449892Sdrh         if( groupBySort ){
43431c9d835dSdrh           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
43441c9d835dSdrh           if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
434513449892Sdrh         }else{
434613449892Sdrh           sAggInfo.directMode = 1;
43472dcef11bSdrh           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
434813449892Sdrh         }
434913449892Sdrh       }
435016ee60ffSdrh       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
4351b21e7c70Sdrh                           (char*)pKeyInfo, P4_KEYINFO);
435216ee60ffSdrh       j1 = sqlite3VdbeCurrentAddr(v);
435316ee60ffSdrh       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
435413449892Sdrh 
435513449892Sdrh       /* Generate code that runs whenever the GROUP BY changes.
4356e00ee6ebSdrh       ** Changes in the GROUP BY are detected by the previous code
435713449892Sdrh       ** block.  If there were no changes, this block is skipped.
435813449892Sdrh       **
435913449892Sdrh       ** This code copies current group by terms in b0,b1,b2,...
436013449892Sdrh       ** over to a0,a1,a2.  It then calls the output subroutine
436113449892Sdrh       ** and resets the aggregate accumulator registers in preparation
436213449892Sdrh       ** for the next GROUP BY batch.
436313449892Sdrh       */
4364b21e7c70Sdrh       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
43652eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
4366d4e70ebdSdrh       VdbeComment((v, "output one row"));
43673c84ddffSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
4368d4e70ebdSdrh       VdbeComment((v, "check abort flag"));
43692eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
4370d4e70ebdSdrh       VdbeComment((v, "reset accumulator"));
437113449892Sdrh 
437213449892Sdrh       /* Update the aggregate accumulators based on the content of
437313449892Sdrh       ** the current row
437413449892Sdrh       */
437516ee60ffSdrh       sqlite3VdbeJumpHere(v, j1);
437613449892Sdrh       updateAccumulator(pParse, &sAggInfo);
43774c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
4378d4e70ebdSdrh       VdbeComment((v, "indicate data in accumulator"));
437913449892Sdrh 
438013449892Sdrh       /* End of the loop
438113449892Sdrh       */
438213449892Sdrh       if( groupBySort ){
43831c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
438413449892Sdrh       }else{
438513449892Sdrh         sqlite3WhereEnd(pWInfo);
438648f2d3b1Sdrh         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
438713449892Sdrh       }
438813449892Sdrh 
438913449892Sdrh       /* Output the final row of result
439013449892Sdrh       */
43912eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
4392d4e70ebdSdrh       VdbeComment((v, "output final row"));
439313449892Sdrh 
4394d176611bSdrh       /* Jump over the subroutines
4395d176611bSdrh       */
4396d176611bSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
4397d176611bSdrh 
4398d176611bSdrh       /* Generate a subroutine that outputs a single row of the result
4399d176611bSdrh       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
4400d176611bSdrh       ** is less than or equal to zero, the subroutine is a no-op.  If
4401d176611bSdrh       ** the processing calls for the query to abort, this subroutine
4402d176611bSdrh       ** increments the iAbortFlag memory location before returning in
4403d176611bSdrh       ** order to signal the caller to abort.
4404d176611bSdrh       */
4405d176611bSdrh       addrSetAbort = sqlite3VdbeCurrentAddr(v);
4406d176611bSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
4407d176611bSdrh       VdbeComment((v, "set abort flag"));
4408d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
4409d176611bSdrh       sqlite3VdbeResolveLabel(v, addrOutputRow);
4410d176611bSdrh       addrOutputRow = sqlite3VdbeCurrentAddr(v);
4411d176611bSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
4412d176611bSdrh       VdbeComment((v, "Groupby result generator entry point"));
4413d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
4414d176611bSdrh       finalizeAggFunctions(pParse, &sAggInfo);
4415d176611bSdrh       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
4416d176611bSdrh       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
4417e8e4af76Sdrh                       &sDistinct, pDest,
4418d176611bSdrh                       addrOutputRow+1, addrSetAbort);
4419d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
4420d176611bSdrh       VdbeComment((v, "end groupby result generator"));
4421d176611bSdrh 
4422d176611bSdrh       /* Generate a subroutine that will reset the group-by accumulator
4423d176611bSdrh       */
4424d176611bSdrh       sqlite3VdbeResolveLabel(v, addrReset);
4425d176611bSdrh       resetAccumulator(pParse, &sAggInfo);
4426d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regReset);
4427d176611bSdrh 
442843152cf8Sdrh     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
442913449892Sdrh     else {
4430dba0137eSdanielk1977       ExprList *pDel = 0;
4431a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT
4432a5533162Sdanielk1977       Table *pTab;
4433a5533162Sdanielk1977       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
4434a5533162Sdanielk1977         /* If isSimpleCount() returns a pointer to a Table structure, then
4435a5533162Sdanielk1977         ** the SQL statement is of the form:
4436a5533162Sdanielk1977         **
4437a5533162Sdanielk1977         **   SELECT count(*) FROM <tbl>
4438a5533162Sdanielk1977         **
4439a5533162Sdanielk1977         ** where the Table structure returned represents table <tbl>.
4440a5533162Sdanielk1977         **
4441a5533162Sdanielk1977         ** This statement is so common that it is optimized specially. The
4442a5533162Sdanielk1977         ** OP_Count instruction is executed either on the intkey table that
4443a5533162Sdanielk1977         ** contains the data for table <tbl> or on one of its indexes. It
4444a5533162Sdanielk1977         ** is better to execute the op on an index, as indexes are almost
4445a5533162Sdanielk1977         ** always spread across less pages than their corresponding tables.
4446a5533162Sdanielk1977         */
4447a5533162Sdanielk1977         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4448a5533162Sdanielk1977         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
4449a5533162Sdanielk1977         Index *pIdx;                         /* Iterator variable */
4450a5533162Sdanielk1977         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
4451a5533162Sdanielk1977         Index *pBest = 0;                    /* Best index found so far */
4452a5533162Sdanielk1977         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
4453a9d1ccb9Sdanielk1977 
4454a5533162Sdanielk1977         sqlite3CodeVerifySchema(pParse, iDb);
4455a5533162Sdanielk1977         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
4456a5533162Sdanielk1977 
4457a5533162Sdanielk1977         /* Search for the index that has the least amount of columns. If
4458a5533162Sdanielk1977         ** there is such an index, and it has less columns than the table
4459a5533162Sdanielk1977         ** does, then we can assume that it consumes less space on disk and
4460a5533162Sdanielk1977         ** will therefore be cheaper to scan to determine the query result.
4461a5533162Sdanielk1977         ** In this case set iRoot to the root page number of the index b-tree
4462a5533162Sdanielk1977         ** and pKeyInfo to the KeyInfo structure required to navigate the
4463a5533162Sdanielk1977         ** index.
4464a5533162Sdanielk1977         **
44653e9548b3Sdrh         ** (2011-04-15) Do not do a full scan of an unordered index.
44663e9548b3Sdrh         **
4467a5533162Sdanielk1977         ** In practice the KeyInfo structure will not be used. It is only
4468a5533162Sdanielk1977         ** passed to keep OP_OpenRead happy.
4469a5533162Sdanielk1977         */
4470a5533162Sdanielk1977         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
44713e9548b3Sdrh           if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
4472a5533162Sdanielk1977             pBest = pIdx;
4473a5533162Sdanielk1977           }
4474a5533162Sdanielk1977         }
4475a5533162Sdanielk1977         if( pBest && pBest->nColumn<pTab->nCol ){
4476a5533162Sdanielk1977           iRoot = pBest->tnum;
4477a5533162Sdanielk1977           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
4478a5533162Sdanielk1977         }
4479a5533162Sdanielk1977 
4480a5533162Sdanielk1977         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
4481a5533162Sdanielk1977         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
4482a5533162Sdanielk1977         if( pKeyInfo ){
4483a5533162Sdanielk1977           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
4484a5533162Sdanielk1977         }
4485a5533162Sdanielk1977         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
4486a5533162Sdanielk1977         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
4487ef7075deSdan         explainSimpleCount(pParse, pTab, pBest);
4488a5533162Sdanielk1977       }else
4489a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */
4490a5533162Sdanielk1977       {
4491738bdcfbSdanielk1977         /* Check if the query is of one of the following forms:
4492738bdcfbSdanielk1977         **
4493738bdcfbSdanielk1977         **   SELECT min(x) FROM ...
4494738bdcfbSdanielk1977         **   SELECT max(x) FROM ...
4495738bdcfbSdanielk1977         **
4496738bdcfbSdanielk1977         ** If it is, then ask the code in where.c to attempt to sort results
4497738bdcfbSdanielk1977         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
4498738bdcfbSdanielk1977         ** If where.c is able to produce results sorted in this order, then
4499738bdcfbSdanielk1977         ** add vdbe code to break out of the processing loop after the
4500738bdcfbSdanielk1977         ** first iteration (since the first iteration of the loop is
4501738bdcfbSdanielk1977         ** guaranteed to operate on the row with the minimum or maximum
4502738bdcfbSdanielk1977         ** value of x, the only row required).
4503738bdcfbSdanielk1977         **
4504738bdcfbSdanielk1977         ** A special flag must be passed to sqlite3WhereBegin() to slightly
4505738bdcfbSdanielk1977         ** modify behaviour as follows:
4506738bdcfbSdanielk1977         **
4507738bdcfbSdanielk1977         **   + If the query is a "SELECT min(x)", then the loop coded by
4508738bdcfbSdanielk1977         **     where.c should not iterate over any values with a NULL value
4509738bdcfbSdanielk1977         **     for x.
4510738bdcfbSdanielk1977         **
4511738bdcfbSdanielk1977         **   + The optimizer code in where.c (the thing that decides which
4512738bdcfbSdanielk1977         **     index or indices to use) should place a different priority on
4513738bdcfbSdanielk1977         **     satisfying the 'ORDER BY' clause than it does in other cases.
4514738bdcfbSdanielk1977         **     Refer to code and comments in where.c for details.
4515738bdcfbSdanielk1977         */
4516a5533162Sdanielk1977         ExprList *pMinMax = 0;
4517a5533162Sdanielk1977         u8 flag = minMaxQuery(p);
4518a9d1ccb9Sdanielk1977         if( flag ){
45196ab3a2ecSdanielk1977           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
452046ec5b63Sdrh           assert( p->pEList->a[0].pExpr->x.pList->nExpr==1 );
45216ab3a2ecSdanielk1977           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
45226ab3a2ecSdanielk1977           pDel = pMinMax;
45230e359b30Sdrh           if( pMinMax && !db->mallocFailed ){
4524ea678832Sdrh             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
4525a9d1ccb9Sdanielk1977             pMinMax->a[0].pExpr->op = TK_COLUMN;
4526a9d1ccb9Sdanielk1977           }
45271013c932Sdrh         }
4528a9d1ccb9Sdanielk1977 
452913449892Sdrh         /* This case runs if the aggregate has no GROUP BY clause.  The
453013449892Sdrh         ** processing is much simpler since there is only a single row
453113449892Sdrh         ** of output.
453213449892Sdrh         */
453313449892Sdrh         resetAccumulator(pParse, &sAggInfo);
453446ec5b63Sdrh         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
4535dba0137eSdanielk1977         if( pWInfo==0 ){
4536633e6d57Sdrh           sqlite3ExprListDelete(db, pDel);
4537dba0137eSdanielk1977           goto select_end;
4538dba0137eSdanielk1977         }
453913449892Sdrh         updateAccumulator(pParse, &sAggInfo);
454046c35f9bSdrh         assert( pMinMax==0 || pMinMax->nExpr==1 );
454146ec5b63Sdrh         if( pWInfo->nOBSat>0 ){
4542a9d1ccb9Sdanielk1977           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
4543a5533162Sdanielk1977           VdbeComment((v, "%s() by index",
4544a5533162Sdanielk1977                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
4545a9d1ccb9Sdanielk1977         }
454613449892Sdrh         sqlite3WhereEnd(pWInfo);
454713449892Sdrh         finalizeAggFunctions(pParse, &sAggInfo);
45487a895a80Sdanielk1977       }
45497a895a80Sdanielk1977 
455013449892Sdrh       pOrderBy = 0;
455135573356Sdrh       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
4552e8e4af76Sdrh       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0,
4553a9671a22Sdrh                       pDest, addrEnd, addrEnd);
4554633e6d57Sdrh       sqlite3ExprListDelete(db, pDel);
455513449892Sdrh     }
455613449892Sdrh     sqlite3VdbeResolveLabel(v, addrEnd);
455713449892Sdrh 
455813449892Sdrh   } /* endif aggregate query */
45592282792aSdrh 
4560e8e4af76Sdrh   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
45612ce22453Sdan     explainTempTable(pParse, "DISTINCT");
45622ce22453Sdan   }
45632ce22453Sdan 
4564cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
4565cce7d176Sdrh   ** and send them to the callback one by one.
4566cce7d176Sdrh   */
4567cce7d176Sdrh   if( pOrderBy ){
45682ce22453Sdan     explainTempTable(pParse, "ORDER BY");
45696c8c8ce0Sdanielk1977     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
4570cce7d176Sdrh   }
45716a535340Sdrh 
4572ec7429aeSdrh   /* Jump here to skip this query
4573ec7429aeSdrh   */
4574ec7429aeSdrh   sqlite3VdbeResolveLabel(v, iEnd);
4575ec7429aeSdrh 
45761d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
45771d83f052Sdrh   ** to indicate no errors.
45781d83f052Sdrh   */
45791d83f052Sdrh   rc = 0;
45801d83f052Sdrh 
45811d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
45821d83f052Sdrh   ** successful coding of the SELECT.
45831d83f052Sdrh   */
45841d83f052Sdrh select_end:
458517c0bc0cSdan   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
4586955de52cSdanielk1977 
45877d10d5a6Sdrh   /* Identify column names if results of the SELECT are to be output.
4588955de52cSdanielk1977   */
45897d10d5a6Sdrh   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
4590955de52cSdanielk1977     generateColumnNames(pParse, pTabList, pEList);
4591955de52cSdanielk1977   }
4592955de52cSdanielk1977 
4593633e6d57Sdrh   sqlite3DbFree(db, sAggInfo.aCol);
4594633e6d57Sdrh   sqlite3DbFree(db, sAggInfo.aFunc);
45951d83f052Sdrh   return rc;
4596cce7d176Sdrh }
4597485f0039Sdrh 
4598678a9aa7Sdrh #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
4599485f0039Sdrh /*
46007e02e5e6Sdrh ** Generate a human-readable description of a the Select object.
4601485f0039Sdrh */
4602a84203a0Sdrh static void explainOneSelect(Vdbe *pVdbe, Select *p){
46037e02e5e6Sdrh   sqlite3ExplainPrintf(pVdbe, "SELECT ");
46044e2a9c32Sdrh   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
46054e2a9c32Sdrh     if( p->selFlags & SF_Distinct ){
46064e2a9c32Sdrh       sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
4607485f0039Sdrh     }
46084e2a9c32Sdrh     if( p->selFlags & SF_Aggregate ){
46094e2a9c32Sdrh       sqlite3ExplainPrintf(pVdbe, "agg_flag ");
4610485f0039Sdrh     }
46114e2a9c32Sdrh     sqlite3ExplainNL(pVdbe);
46124e2a9c32Sdrh     sqlite3ExplainPrintf(pVdbe, "   ");
4613485f0039Sdrh   }
46147e02e5e6Sdrh   sqlite3ExplainExprList(pVdbe, p->pEList);
46157e02e5e6Sdrh   sqlite3ExplainNL(pVdbe);
46167e02e5e6Sdrh   if( p->pSrc && p->pSrc->nSrc ){
4617485f0039Sdrh     int i;
46187e02e5e6Sdrh     sqlite3ExplainPrintf(pVdbe, "FROM ");
46197e02e5e6Sdrh     sqlite3ExplainPush(pVdbe);
4620485f0039Sdrh     for(i=0; i<p->pSrc->nSrc; i++){
4621485f0039Sdrh       struct SrcList_item *pItem = &p->pSrc->a[i];
462204b8342bSdrh       sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
4623485f0039Sdrh       if( pItem->pSelect ){
46247e02e5e6Sdrh         sqlite3ExplainSelect(pVdbe, pItem->pSelect);
4625485f0039Sdrh         if( pItem->pTab ){
462604b8342bSdrh           sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
462704b8342bSdrh         }
4628485f0039Sdrh       }else if( pItem->zName ){
46297e02e5e6Sdrh         sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
4630485f0039Sdrh       }
4631485f0039Sdrh       if( pItem->zAlias ){
463204b8342bSdrh         sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
4633485f0039Sdrh       }
4634a84203a0Sdrh       if( pItem->jointype & JT_LEFT ){
4635a84203a0Sdrh         sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
4636485f0039Sdrh       }
46377e02e5e6Sdrh       sqlite3ExplainNL(pVdbe);
4638485f0039Sdrh     }
46397e02e5e6Sdrh     sqlite3ExplainPop(pVdbe);
4640485f0039Sdrh   }
4641485f0039Sdrh   if( p->pWhere ){
46427e02e5e6Sdrh     sqlite3ExplainPrintf(pVdbe, "WHERE ");
46437e02e5e6Sdrh     sqlite3ExplainExpr(pVdbe, p->pWhere);
46447e02e5e6Sdrh     sqlite3ExplainNL(pVdbe);
4645485f0039Sdrh   }
4646485f0039Sdrh   if( p->pGroupBy ){
46477e02e5e6Sdrh     sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
46487e02e5e6Sdrh     sqlite3ExplainExprList(pVdbe, p->pGroupBy);
46497e02e5e6Sdrh     sqlite3ExplainNL(pVdbe);
4650485f0039Sdrh   }
4651485f0039Sdrh   if( p->pHaving ){
46527e02e5e6Sdrh     sqlite3ExplainPrintf(pVdbe, "HAVING ");
46537e02e5e6Sdrh     sqlite3ExplainExpr(pVdbe, p->pHaving);
46547e02e5e6Sdrh     sqlite3ExplainNL(pVdbe);
4655485f0039Sdrh   }
4656485f0039Sdrh   if( p->pOrderBy ){
46577e02e5e6Sdrh     sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
46587e02e5e6Sdrh     sqlite3ExplainExprList(pVdbe, p->pOrderBy);
46597e02e5e6Sdrh     sqlite3ExplainNL(pVdbe);
4660485f0039Sdrh   }
4661a84203a0Sdrh   if( p->pLimit ){
4662a84203a0Sdrh     sqlite3ExplainPrintf(pVdbe, "LIMIT ");
4663a84203a0Sdrh     sqlite3ExplainExpr(pVdbe, p->pLimit);
4664a84203a0Sdrh     sqlite3ExplainNL(pVdbe);
4665a84203a0Sdrh   }
4666a84203a0Sdrh   if( p->pOffset ){
4667a84203a0Sdrh     sqlite3ExplainPrintf(pVdbe, "OFFSET ");
4668a84203a0Sdrh     sqlite3ExplainExpr(pVdbe, p->pOffset);
4669a84203a0Sdrh     sqlite3ExplainNL(pVdbe);
4670485f0039Sdrh   }
4671485f0039Sdrh }
4672a84203a0Sdrh void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
4673a84203a0Sdrh   if( p==0 ){
4674a84203a0Sdrh     sqlite3ExplainPrintf(pVdbe, "(null-select)");
4675a84203a0Sdrh     return;
4676a84203a0Sdrh   }
4677a84203a0Sdrh   while( p->pPrior ) p = p->pPrior;
4678a84203a0Sdrh   sqlite3ExplainPush(pVdbe);
4679a84203a0Sdrh   while( p ){
4680a84203a0Sdrh     explainOneSelect(pVdbe, p);
4681a84203a0Sdrh     p = p->pNext;
4682a84203a0Sdrh     if( p==0 ) break;
4683a84203a0Sdrh     sqlite3ExplainNL(pVdbe);
4684a84203a0Sdrh     sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
4685a84203a0Sdrh   }
46867e02e5e6Sdrh   sqlite3ExplainPrintf(pVdbe, "END");
4687a84203a0Sdrh   sqlite3ExplainPop(pVdbe);
4688485f0039Sdrh }
46897e02e5e6Sdrh 
4690485f0039Sdrh /* End of the structure debug printing code
4691485f0039Sdrh *****************************************************************************/
469214a55b71Smistachkin #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
4693