xref: /sqlite-3.40.0/src/select.c (revision ee06c99b)
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);
324e9119d9Sdan   sqlite3WithDelete(db, p->pWith);
33eda639e1Sdrh }
34eda639e1Sdrh 
351013c932Sdrh /*
361013c932Sdrh ** Initialize a SelectDest structure.
371013c932Sdrh */
381013c932Sdrh void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
39ea678832Sdrh   pDest->eDest = (u8)eDest;
402b596da8Sdrh   pDest->iSDParm = iParm;
412b596da8Sdrh   pDest->affSdst = 0;
422b596da8Sdrh   pDest->iSdst = 0;
432b596da8Sdrh   pDest->nSdst = 0;
441013c932Sdrh }
451013c932Sdrh 
46eda639e1Sdrh 
47eda639e1Sdrh /*
489bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that
499bb61fe7Sdrh ** structure.
50cce7d176Sdrh */
514adee20fSdanielk1977 Select *sqlite3SelectNew(
5217435752Sdrh   Parse *pParse,        /* Parsing context */
53daffd0e5Sdrh   ExprList *pEList,     /* which columns to include in the result */
54ad3cab52Sdrh   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
55daffd0e5Sdrh   Expr *pWhere,         /* the WHERE clause */
56daffd0e5Sdrh   ExprList *pGroupBy,   /* the GROUP BY clause */
57daffd0e5Sdrh   Expr *pHaving,        /* the HAVING clause */
58daffd0e5Sdrh   ExprList *pOrderBy,   /* the ORDER BY clause */
59832ee3d4Sdrh   u16 selFlags,         /* Flag parameters, such as SF_Distinct */
60a2dc3b1aSdanielk1977   Expr *pLimit,         /* LIMIT value.  NULL means not used */
61a2dc3b1aSdanielk1977   Expr *pOffset         /* OFFSET value.  NULL means no offset */
629bb61fe7Sdrh ){
639bb61fe7Sdrh   Select *pNew;
64eda639e1Sdrh   Select standin;
6517435752Sdrh   sqlite3 *db = pParse->db;
6617435752Sdrh   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
67d72a276eSdrh   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
68daffd0e5Sdrh   if( pNew==0 ){
69338ec3e1Sdrh     assert( db->mallocFailed );
70eda639e1Sdrh     pNew = &standin;
71eda639e1Sdrh     memset(pNew, 0, sizeof(*pNew));
72eda639e1Sdrh   }
73b733d037Sdrh   if( pEList==0 ){
74b7916a78Sdrh     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
75b733d037Sdrh   }
769bb61fe7Sdrh   pNew->pEList = pEList;
777b113babSdrh   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
789bb61fe7Sdrh   pNew->pSrc = pSrc;
799bb61fe7Sdrh   pNew->pWhere = pWhere;
809bb61fe7Sdrh   pNew->pGroupBy = pGroupBy;
819bb61fe7Sdrh   pNew->pHaving = pHaving;
829bb61fe7Sdrh   pNew->pOrderBy = pOrderBy;
83832ee3d4Sdrh   pNew->selFlags = selFlags;
8482c3d636Sdrh   pNew->op = TK_SELECT;
85a2dc3b1aSdanielk1977   pNew->pLimit = pLimit;
86a2dc3b1aSdanielk1977   pNew->pOffset = pOffset;
87373cc2ddSdrh   assert( pOffset==0 || pLimit!=0 );
88b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
89b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
90b9bb7c18Sdrh   pNew->addrOpenEphm[2] = -1;
910a846f96Sdrh   if( db->mallocFailed ) {
92633e6d57Sdrh     clearSelect(db, pNew);
930a846f96Sdrh     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
94eda639e1Sdrh     pNew = 0;
95a464c234Sdrh   }else{
96a464c234Sdrh     assert( pNew->pSrc!=0 || pParse->nErr>0 );
97daffd0e5Sdrh   }
98338ec3e1Sdrh   assert( pNew!=&standin );
999bb61fe7Sdrh   return pNew;
1009bb61fe7Sdrh }
1019bb61fe7Sdrh 
1029bb61fe7Sdrh /*
103eda639e1Sdrh ** Delete the given Select structure and all of its substructures.
104eda639e1Sdrh */
105633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){
106eda639e1Sdrh   if( p ){
107633e6d57Sdrh     clearSelect(db, p);
108633e6d57Sdrh     sqlite3DbFree(db, p);
109eda639e1Sdrh   }
110eda639e1Sdrh }
111eda639e1Sdrh 
112eda639e1Sdrh /*
113f7b5496eSdrh ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
11401f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
11501f3f253Sdrh ** in terms of the following bit values:
11601f3f253Sdrh **
11701f3f253Sdrh **     JT_INNER
1183dec223cSdrh **     JT_CROSS
11901f3f253Sdrh **     JT_OUTER
12001f3f253Sdrh **     JT_NATURAL
12101f3f253Sdrh **     JT_LEFT
12201f3f253Sdrh **     JT_RIGHT
12301f3f253Sdrh **
12401f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
12501f3f253Sdrh **
12601f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
12701f3f253Sdrh ** a join type, but put an error in the pParse structure.
12801f3f253Sdrh */
1294adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
13001f3f253Sdrh   int jointype = 0;
13101f3f253Sdrh   Token *apAll[3];
13201f3f253Sdrh   Token *p;
133373cc2ddSdrh                              /*   0123456789 123456789 123456789 123 */
134373cc2ddSdrh   static const char zKeyText[] = "naturaleftouterightfullinnercross";
1355719628aSdrh   static const struct {
136373cc2ddSdrh     u8 i;        /* Beginning of keyword text in zKeyText[] */
137373cc2ddSdrh     u8 nChar;    /* Length of the keyword in characters */
138373cc2ddSdrh     u8 code;     /* Join type mask */
139373cc2ddSdrh   } aKeyword[] = {
140373cc2ddSdrh     /* natural */ { 0,  7, JT_NATURAL                },
141373cc2ddSdrh     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
142373cc2ddSdrh     /* outer   */ { 10, 5, JT_OUTER                  },
143373cc2ddSdrh     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
144373cc2ddSdrh     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
145373cc2ddSdrh     /* inner   */ { 23, 5, JT_INNER                  },
146373cc2ddSdrh     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
14701f3f253Sdrh   };
14801f3f253Sdrh   int i, j;
14901f3f253Sdrh   apAll[0] = pA;
15001f3f253Sdrh   apAll[1] = pB;
15101f3f253Sdrh   apAll[2] = pC;
152195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
15301f3f253Sdrh     p = apAll[i];
154373cc2ddSdrh     for(j=0; j<ArraySize(aKeyword); j++){
155373cc2ddSdrh       if( p->n==aKeyword[j].nChar
156373cc2ddSdrh           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
157373cc2ddSdrh         jointype |= aKeyword[j].code;
15801f3f253Sdrh         break;
15901f3f253Sdrh       }
16001f3f253Sdrh     }
161373cc2ddSdrh     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
162373cc2ddSdrh     if( j>=ArraySize(aKeyword) ){
16301f3f253Sdrh       jointype |= JT_ERROR;
16401f3f253Sdrh       break;
16501f3f253Sdrh     }
16601f3f253Sdrh   }
167ad2d8307Sdrh   if(
168ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
169195e6967Sdrh      (jointype & JT_ERROR)!=0
170ad2d8307Sdrh   ){
171a9671a22Sdrh     const char *zSp = " ";
172a9671a22Sdrh     assert( pB!=0 );
173a9671a22Sdrh     if( pC==0 ){ zSp++; }
174ae29ffbeSdrh     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
175a9671a22Sdrh        "%T %T%s%T", pA, pB, zSp, pC);
17601f3f253Sdrh     jointype = JT_INNER;
177373cc2ddSdrh   }else if( (jointype & JT_OUTER)!=0
178373cc2ddSdrh          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
1794adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
180da93d238Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported");
181195e6967Sdrh     jointype = JT_INNER;
18201f3f253Sdrh   }
18301f3f253Sdrh   return jointype;
18401f3f253Sdrh }
18501f3f253Sdrh 
18601f3f253Sdrh /*
187ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
188ad2d8307Sdrh ** is not contained in the table.
189ad2d8307Sdrh */
190ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
191ad2d8307Sdrh   int i;
192ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
1934adee20fSdanielk1977     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
194ad2d8307Sdrh   }
195ad2d8307Sdrh   return -1;
196ad2d8307Sdrh }
197ad2d8307Sdrh 
198ad2d8307Sdrh /*
1992179b434Sdrh ** Search the first N tables in pSrc, from left to right, looking for a
2002179b434Sdrh ** table that has a column named zCol.
2012179b434Sdrh **
2022179b434Sdrh ** When found, set *piTab and *piCol to the table index and column index
2032179b434Sdrh ** of the matching column and return TRUE.
2042179b434Sdrh **
2052179b434Sdrh ** If not found, return FALSE.
2062179b434Sdrh */
2072179b434Sdrh static int tableAndColumnIndex(
2082179b434Sdrh   SrcList *pSrc,       /* Array of tables to search */
2092179b434Sdrh   int N,               /* Number of tables in pSrc->a[] to search */
2102179b434Sdrh   const char *zCol,    /* Name of the column we are looking for */
2112179b434Sdrh   int *piTab,          /* Write index of pSrc->a[] here */
2122179b434Sdrh   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
2132179b434Sdrh ){
2142179b434Sdrh   int i;               /* For looping over tables in pSrc */
2152179b434Sdrh   int iCol;            /* Index of column matching zCol */
2162179b434Sdrh 
2172179b434Sdrh   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
2182179b434Sdrh   for(i=0; i<N; i++){
2192179b434Sdrh     iCol = columnIndex(pSrc->a[i].pTab, zCol);
2202179b434Sdrh     if( iCol>=0 ){
2212179b434Sdrh       if( piTab ){
2222179b434Sdrh         *piTab = i;
2232179b434Sdrh         *piCol = iCol;
2242179b434Sdrh       }
2252179b434Sdrh       return 1;
2262179b434Sdrh     }
2272179b434Sdrh   }
2282179b434Sdrh   return 0;
2292179b434Sdrh }
2302179b434Sdrh 
2312179b434Sdrh /*
232f7b0b0adSdan ** This function is used to add terms implied by JOIN syntax to the
233f7b0b0adSdan ** WHERE clause expression of a SELECT statement. The new term, which
234f7b0b0adSdan ** is ANDed with the existing WHERE clause, is of the form:
235f7b0b0adSdan **
236f7b0b0adSdan **    (tab1.col1 = tab2.col2)
237f7b0b0adSdan **
238f7b0b0adSdan ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
239f7b0b0adSdan ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
240f7b0b0adSdan ** column iColRight of tab2.
241ad2d8307Sdrh */
242ad2d8307Sdrh static void addWhereTerm(
24317435752Sdrh   Parse *pParse,                  /* Parsing context */
244f7b0b0adSdan   SrcList *pSrc,                  /* List of tables in FROM clause */
2452179b434Sdrh   int iLeft,                      /* Index of first table to join in pSrc */
246f7b0b0adSdan   int iColLeft,                   /* Index of column in first table */
2472179b434Sdrh   int iRight,                     /* Index of second table in pSrc */
248f7b0b0adSdan   int iColRight,                  /* Index of column in second table */
249f7b0b0adSdan   int isOuterJoin,                /* True if this is an OUTER join */
250f7b0b0adSdan   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
251ad2d8307Sdrh ){
252f7b0b0adSdan   sqlite3 *db = pParse->db;
253f7b0b0adSdan   Expr *pE1;
254f7b0b0adSdan   Expr *pE2;
255f7b0b0adSdan   Expr *pEq;
256ad2d8307Sdrh 
2572179b434Sdrh   assert( iLeft<iRight );
2582179b434Sdrh   assert( pSrc->nSrc>iRight );
2592179b434Sdrh   assert( pSrc->a[iLeft].pTab );
2602179b434Sdrh   assert( pSrc->a[iRight].pTab );
261f7b0b0adSdan 
2622179b434Sdrh   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
2632179b434Sdrh   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
264f7b0b0adSdan 
265f7b0b0adSdan   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
266f7b0b0adSdan   if( pEq && isOuterJoin ){
267f7b0b0adSdan     ExprSetProperty(pEq, EP_FromJoin);
268c5cd1249Sdrh     assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
269ebb6a65dSdrh     ExprSetVVAProperty(pEq, EP_NoReduce);
270f7b0b0adSdan     pEq->iRightJoinTable = (i16)pE2->iTable;
271030530deSdrh   }
272f7b0b0adSdan   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
273ad2d8307Sdrh }
274ad2d8307Sdrh 
275ad2d8307Sdrh /*
2761f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
27722d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the
27822d6a53aSdrh ** expression.
2791cc093c2Sdrh **
280e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
2811cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
2821f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
2831f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
2841f16230bSdrh ** WHERE clause during join processing but we need to remember that they
2851f16230bSdrh ** originated in the ON or USING clause.
28622d6a53aSdrh **
28722d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the
28822d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not
28922d6a53aSdrh ** explicitly mentioned in the expression.  That information is needed
29022d6a53aSdrh ** for cases like this:
29122d6a53aSdrh **
29222d6a53aSdrh **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
29322d6a53aSdrh **
29422d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5
29522d6a53aSdrh ** term until after the t2 loop of the join.  In that way, a
29622d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
29722d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately
29822d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in
29922d6a53aSdrh ** the output, which is incorrect.
3001cc093c2Sdrh */
30122d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){
3021cc093c2Sdrh   while( p ){
3031f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
304c5cd1249Sdrh     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
305ebb6a65dSdrh     ExprSetVVAProperty(p, EP_NoReduce);
306cf697396Sshane     p->iRightJoinTable = (i16)iTable;
30722d6a53aSdrh     setJoinExpr(p->pLeft, iTable);
3081cc093c2Sdrh     p = p->pRight;
3091cc093c2Sdrh   }
3101cc093c2Sdrh }
3111cc093c2Sdrh 
3121cc093c2Sdrh /*
313ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
314ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
315ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
316ad2d8307Sdrh **
31791bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure.
31891bb0eedSdrh ** The left most table is the first entry in Select.pSrc.  The right-most
31991bb0eedSdrh ** table is the last entry.  The join operator is held in the entry to
32091bb0eedSdrh ** the left.  Thus entry 0 contains the join operator for the join between
32191bb0eedSdrh ** entries 0 and 1.  Any ON or USING clauses associated with the join are
32291bb0eedSdrh ** also attached to the left entry.
32391bb0eedSdrh **
324ad2d8307Sdrh ** This routine returns the number of errors encountered.
325ad2d8307Sdrh */
326ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
32791bb0eedSdrh   SrcList *pSrc;                  /* All tables in the FROM clause */
32891bb0eedSdrh   int i, j;                       /* Loop counters */
32991bb0eedSdrh   struct SrcList_item *pLeft;     /* Left table being joined */
33091bb0eedSdrh   struct SrcList_item *pRight;    /* Right table being joined */
331ad2d8307Sdrh 
33291bb0eedSdrh   pSrc = p->pSrc;
33391bb0eedSdrh   pLeft = &pSrc->a[0];
33491bb0eedSdrh   pRight = &pLeft[1];
33591bb0eedSdrh   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
33691bb0eedSdrh     Table *pLeftTab = pLeft->pTab;
33791bb0eedSdrh     Table *pRightTab = pRight->pTab;
338ad27e761Sdrh     int isOuter;
33991bb0eedSdrh 
3401c767f0dSdrh     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
341ad27e761Sdrh     isOuter = (pRight->jointype & JT_OUTER)!=0;
342ad2d8307Sdrh 
343ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
344ad2d8307Sdrh     ** every column that the two tables have in common.
345ad2d8307Sdrh     */
34661dfc31dSdrh     if( pRight->jointype & JT_NATURAL ){
34761dfc31dSdrh       if( pRight->pOn || pRight->pUsing ){
3484adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
349ad2d8307Sdrh            "an ON or USING clause", 0);
350ad2d8307Sdrh         return 1;
351ad2d8307Sdrh       }
3522179b434Sdrh       for(j=0; j<pRightTab->nCol; j++){
3532179b434Sdrh         char *zName;   /* Name of column in the right table */
3542179b434Sdrh         int iLeft;     /* Matching left table */
3552179b434Sdrh         int iLeftCol;  /* Matching column in the left table */
3562179b434Sdrh 
3572179b434Sdrh         zName = pRightTab->aCol[j].zName;
3582179b434Sdrh         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
3592179b434Sdrh           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
3602179b434Sdrh                        isOuter, &p->pWhere);
361ad2d8307Sdrh         }
362ad2d8307Sdrh       }
363ad2d8307Sdrh     }
364ad2d8307Sdrh 
365ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
366ad2d8307Sdrh     */
36761dfc31dSdrh     if( pRight->pOn && pRight->pUsing ){
3684adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
369da93d238Sdrh         "clauses in the same join");
370ad2d8307Sdrh       return 1;
371ad2d8307Sdrh     }
372ad2d8307Sdrh 
373ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
37491bb0eedSdrh     ** an AND operator.
375ad2d8307Sdrh     */
37661dfc31dSdrh     if( pRight->pOn ){
377ad27e761Sdrh       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
37817435752Sdrh       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
37961dfc31dSdrh       pRight->pOn = 0;
380ad2d8307Sdrh     }
381ad2d8307Sdrh 
382ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
383ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
384ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
385ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
386ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
387ad2d8307Sdrh     ** not contained in both tables to be joined.
388ad2d8307Sdrh     */
38961dfc31dSdrh     if( pRight->pUsing ){
39061dfc31dSdrh       IdList *pList = pRight->pUsing;
391ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
3922179b434Sdrh         char *zName;     /* Name of the term in the USING clause */
3932179b434Sdrh         int iLeft;       /* Table on the left with matching column name */
3942179b434Sdrh         int iLeftCol;    /* Column number of matching column on the left */
3952179b434Sdrh         int iRightCol;   /* Column number of matching column on the right */
3962179b434Sdrh 
3972179b434Sdrh         zName = pList->a[j].zName;
3982179b434Sdrh         iRightCol = columnIndex(pRightTab, zName);
3992179b434Sdrh         if( iRightCol<0
4002179b434Sdrh          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
4012179b434Sdrh         ){
4024adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
40391bb0eedSdrh             "not present in both tables", zName);
404ad2d8307Sdrh           return 1;
405ad2d8307Sdrh         }
4062179b434Sdrh         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
4072179b434Sdrh                      isOuter, &p->pWhere);
408ad2d8307Sdrh       }
409ad2d8307Sdrh     }
410ad2d8307Sdrh   }
411ad2d8307Sdrh   return 0;
412ad2d8307Sdrh }
413ad2d8307Sdrh 
414ad2d8307Sdrh /*
415c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
416c926afbcSdrh ** stack into the sorter.
417c926afbcSdrh */
418d59ba6ceSdrh static void pushOntoSorter(
419d59ba6ceSdrh   Parse *pParse,         /* Parser context */
420d59ba6ceSdrh   ExprList *pOrderBy,    /* The ORDER BY clause */
421b7654111Sdrh   Select *pSelect,       /* The whole SELECT statement */
422b7654111Sdrh   int regData            /* Register holding data to be sorted */
423d59ba6ceSdrh ){
424d59ba6ceSdrh   Vdbe *v = pParse->pVdbe;
425892d3179Sdrh   int nExpr = pOrderBy->nExpr;
426892d3179Sdrh   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
427892d3179Sdrh   int regRecord = sqlite3GetTempReg(pParse);
428c6aff30cSdrh   int op;
429ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
430191b54cbSdrh   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
431892d3179Sdrh   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
432b21e7c70Sdrh   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
4331db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
434c6aff30cSdrh   if( pSelect->selFlags & SF_UseSorter ){
435c6aff30cSdrh     op = OP_SorterInsert;
436c6aff30cSdrh   }else{
437c6aff30cSdrh     op = OP_IdxInsert;
438c6aff30cSdrh   }
439c6aff30cSdrh   sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
440892d3179Sdrh   sqlite3ReleaseTempReg(pParse, regRecord);
441892d3179Sdrh   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
44292b01d53Sdrh   if( pSelect->iLimit ){
44315007a99Sdrh     int addr1, addr2;
444b7654111Sdrh     int iLimit;
4450acb7e48Sdrh     if( pSelect->iOffset ){
446b7654111Sdrh       iLimit = pSelect->iOffset+1;
447b7654111Sdrh     }else{
448b7654111Sdrh       iLimit = pSelect->iLimit;
449b7654111Sdrh     }
450b7654111Sdrh     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
451b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
4523c84ddffSdrh     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
453d59ba6ceSdrh     sqlite3VdbeJumpHere(v, addr1);
4543c84ddffSdrh     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
4553c84ddffSdrh     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
45615007a99Sdrh     sqlite3VdbeJumpHere(v, addr2);
457d59ba6ceSdrh   }
458c926afbcSdrh }
459c926afbcSdrh 
460c926afbcSdrh /*
461ec7429aeSdrh ** Add code to implement the OFFSET
462ea48eb2eSdrh */
463ec7429aeSdrh static void codeOffset(
464bab39e13Sdrh   Vdbe *v,          /* Generate code into this VM */
465aa9ce707Sdrh   int iOffset,      /* Register holding the offset counter */
466b7654111Sdrh   int iContinue     /* Jump here to skip the current record */
467ea48eb2eSdrh ){
468aa9ce707Sdrh   if( iOffset>0 && iContinue!=0 ){
46915007a99Sdrh     int addr;
470aa9ce707Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, iOffset, -1);
471aa9ce707Sdrh     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, iOffset);
47266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
473d4e70ebdSdrh     VdbeComment((v, "skip OFFSET records"));
47415007a99Sdrh     sqlite3VdbeJumpHere(v, addr);
475ea48eb2eSdrh   }
476ea48eb2eSdrh }
477ea48eb2eSdrh 
478ea48eb2eSdrh /*
47998757157Sdrh ** Add code that will check to make sure the N registers starting at iMem
48098757157Sdrh ** form a distinct entry.  iTab is a sorting index that holds previously
481a2a49dc9Sdrh ** seen combinations of the N values.  A new entry is made in iTab
482a2a49dc9Sdrh ** if the current N values are new.
483a2a49dc9Sdrh **
484a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the
485a2a49dc9Sdrh ** stack if the top N elements are not distinct.
486a2a49dc9Sdrh */
487a2a49dc9Sdrh static void codeDistinct(
4882dcef11bSdrh   Parse *pParse,     /* Parsing and code generating context */
489a2a49dc9Sdrh   int iTab,          /* A sorting index used to test for distinctness */
490a2a49dc9Sdrh   int addrRepeat,    /* Jump to here if not distinct */
491477df4b3Sdrh   int N,             /* Number of elements */
492a2a49dc9Sdrh   int iMem           /* First element */
493a2a49dc9Sdrh ){
4942dcef11bSdrh   Vdbe *v;
4952dcef11bSdrh   int r1;
4962dcef11bSdrh 
4972dcef11bSdrh   v = pParse->pVdbe;
4982dcef11bSdrh   r1 = sqlite3GetTempReg(pParse);
49991fc4a0cSdrh   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
5001db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
5012dcef11bSdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
5022dcef11bSdrh   sqlite3ReleaseTempReg(pParse, r1);
503a2a49dc9Sdrh }
504a2a49dc9Sdrh 
505bb7dd683Sdrh #ifndef SQLITE_OMIT_SUBQUERY
506a2a49dc9Sdrh /*
507e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression
508e305f43fSdrh ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
509bb7dd683Sdrh ** column.  We do this in a subroutine because the error used to occur
510bb7dd683Sdrh ** in multiple places.  (The error only occurs in one place now, but we
511bb7dd683Sdrh ** retain the subroutine to minimize code disruption.)
512e305f43fSdrh */
5136c8c8ce0Sdanielk1977 static int checkForMultiColumnSelectError(
5146c8c8ce0Sdanielk1977   Parse *pParse,       /* Parse context. */
5156c8c8ce0Sdanielk1977   SelectDest *pDest,   /* Destination of SELECT results */
5166c8c8ce0Sdanielk1977   int nExpr            /* Number of result columns returned by SELECT */
5176c8c8ce0Sdanielk1977 ){
5186c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
519e305f43fSdrh   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
520e305f43fSdrh     sqlite3ErrorMsg(pParse, "only a single result allowed for "
521e305f43fSdrh        "a SELECT that is part of an expression");
522e305f43fSdrh     return 1;
523e305f43fSdrh   }else{
524e305f43fSdrh     return 0;
525e305f43fSdrh   }
526e305f43fSdrh }
527bb7dd683Sdrh #endif
528c99130fdSdrh 
529c99130fdSdrh /*
530e8e4af76Sdrh ** An instance of the following object is used to record information about
531e8e4af76Sdrh ** how to process the DISTINCT keyword, to simplify passing that information
532e8e4af76Sdrh ** into the selectInnerLoop() routine.
533e8e4af76Sdrh */
534e8e4af76Sdrh typedef struct DistinctCtx DistinctCtx;
535e8e4af76Sdrh struct DistinctCtx {
536e8e4af76Sdrh   u8 isTnct;      /* True if the DISTINCT keyword is present */
537e8e4af76Sdrh   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
538e8e4af76Sdrh   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
539e8e4af76Sdrh   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
540e8e4af76Sdrh };
541e8e4af76Sdrh 
542e8e4af76Sdrh /*
5432282792aSdrh ** This routine generates the code for the inside of the inner loop
5442282792aSdrh ** of a SELECT.
54582c3d636Sdrh **
546340309fdSdrh ** If srcTab is negative, then the pEList expressions
547340309fdSdrh ** are evaluated in order to get the data for this row.  If srcTab is
548340309fdSdrh ** zero or more, then data is pulled from srcTab and pEList is used only
549340309fdSdrh ** to get number columns and the datatype for each column.
5502282792aSdrh */
551d2b3e23bSdrh static void selectInnerLoop(
5522282792aSdrh   Parse *pParse,          /* The parser context */
553df199a25Sdrh   Select *p,              /* The complete select statement being coded */
5542282792aSdrh   ExprList *pEList,       /* List of values being extracted */
55582c3d636Sdrh   int srcTab,             /* Pull data from this 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 );
57138640e15Sdrh   assert( pEList!=0 );
572e8e4af76Sdrh   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
573ea48eb2eSdrh   if( pOrderBy==0 && !hasDistinct ){
574aa9ce707Sdrh     codeOffset(v, p->iOffset, iContinue);
575df199a25Sdrh   }
576df199a25Sdrh 
577967e8b73Sdrh   /* Pull the requested columns.
5782282792aSdrh   */
579d847eaadSdrh   nResultCol = pEList->nExpr;
5802b596da8Sdrh   if( pDest->iSdst==0 ){
5812b596da8Sdrh     pDest->iSdst = pParse->nMem+1;
5822b596da8Sdrh     pDest->nSdst = nResultCol;
5830acb7e48Sdrh     pParse->nMem += nResultCol;
5841c767f0dSdrh   }else{
5852b596da8Sdrh     assert( pDest->nSdst==nResultCol );
5861013c932Sdrh   }
5872b596da8Sdrh   regResult = pDest->iSdst;
588340309fdSdrh   if( srcTab>=0 ){
589340309fdSdrh     for(i=0; i<nResultCol; i++){
590d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
591340309fdSdrh       VdbeComment((v, "%s", pEList->a[i].zName));
59282c3d636Sdrh     }
5939ed1dfa8Sdanielk1977   }else if( eDest!=SRT_Exists ){
5949ed1dfa8Sdanielk1977     /* If the destination is an EXISTS(...) expression, the actual
5959ed1dfa8Sdanielk1977     ** values returned by the SELECT are not required.
5969ed1dfa8Sdanielk1977     */
597d1a01edaSdrh     sqlite3ExprCodeExprList(pParse, pEList, regResult,
598d1a01edaSdrh                             (eDest==SRT_Output)?SQLITE_ECEL_DUP:0);
599a2a49dc9Sdrh   }
6002282792aSdrh 
601daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
602daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
603daffd0e5Sdrh   ** part of the result.
6042282792aSdrh   */
605ea48eb2eSdrh   if( hasDistinct ){
606e8e4af76Sdrh     switch( pDistinct->eTnctType ){
607e8e4af76Sdrh       case WHERE_DISTINCT_ORDERED: {
608e8e4af76Sdrh         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
609e8e4af76Sdrh         int iJump;              /* Jump destination */
610e8e4af76Sdrh         int regPrev;            /* Previous row content */
611e8e4af76Sdrh 
612e8e4af76Sdrh         /* Allocate space for the previous row */
613e8e4af76Sdrh         regPrev = pParse->nMem+1;
614340309fdSdrh         pParse->nMem += nResultCol;
615e8e4af76Sdrh 
616e8e4af76Sdrh         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
617e8e4af76Sdrh         ** sets the MEM_Cleared bit on the first register of the
618e8e4af76Sdrh         ** previous value.  This will cause the OP_Ne below to always
619e8e4af76Sdrh         ** fail on the first iteration of the loop even if the first
620e8e4af76Sdrh         ** row is all NULLs.
621e8e4af76Sdrh         */
622e8e4af76Sdrh         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
623e8e4af76Sdrh         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
624e8e4af76Sdrh         pOp->opcode = OP_Null;
625e8e4af76Sdrh         pOp->p1 = 1;
626e8e4af76Sdrh         pOp->p2 = regPrev;
627e8e4af76Sdrh 
628340309fdSdrh         iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
629340309fdSdrh         for(i=0; i<nResultCol; i++){
630e8e4af76Sdrh           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
631340309fdSdrh           if( i<nResultCol-1 ){
632e8e4af76Sdrh             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
633e8e4af76Sdrh           }else{
634e8e4af76Sdrh             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
635e8e4af76Sdrh           }
636e8e4af76Sdrh           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
637e8e4af76Sdrh           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
638e8e4af76Sdrh         }
639e8e4af76Sdrh         assert( sqlite3VdbeCurrentAddr(v)==iJump );
640340309fdSdrh         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
641e8e4af76Sdrh         break;
642e8e4af76Sdrh       }
643e8e4af76Sdrh 
644e8e4af76Sdrh       case WHERE_DISTINCT_UNIQUE: {
645e8e4af76Sdrh         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
646e8e4af76Sdrh         break;
647e8e4af76Sdrh       }
648e8e4af76Sdrh 
649e8e4af76Sdrh       default: {
650e8e4af76Sdrh         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
651340309fdSdrh         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult);
652e8e4af76Sdrh         break;
653e8e4af76Sdrh       }
654e8e4af76Sdrh     }
655ea48eb2eSdrh     if( pOrderBy==0 ){
656aa9ce707Sdrh       codeOffset(v, p->iOffset, iContinue);
657ea48eb2eSdrh     }
6582282792aSdrh   }
65982c3d636Sdrh 
660c926afbcSdrh   switch( eDest ){
66182c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
66282c3d636Sdrh     ** table iParm.
6632282792aSdrh     */
66413449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
665c926afbcSdrh     case SRT_Union: {
6669cbf3425Sdrh       int r1;
6679cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
668340309fdSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
6699cbf3425Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
6709cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
671c926afbcSdrh       break;
672c926afbcSdrh     }
67382c3d636Sdrh 
67482c3d636Sdrh     /* Construct a record from the query result, but instead of
67582c3d636Sdrh     ** saving that record, use it as a key to delete elements from
67682c3d636Sdrh     ** the temporary table iParm.
67782c3d636Sdrh     */
678c926afbcSdrh     case SRT_Except: {
679340309fdSdrh       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
680c926afbcSdrh       break;
681c926afbcSdrh     }
682781def29Sdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
6835338a5f7Sdanielk1977 
6845338a5f7Sdanielk1977     /* Store the result as data using a unique key.
6855338a5f7Sdanielk1977     */
6868ce7184bSdan     case SRT_DistTable:
6875338a5f7Sdanielk1977     case SRT_Table:
688b9bb7c18Sdrh     case SRT_EphemTab: {
689b7654111Sdrh       int r1 = sqlite3GetTempReg(pParse);
690373cc2ddSdrh       testcase( eDest==SRT_Table );
691373cc2ddSdrh       testcase( eDest==SRT_EphemTab );
692340309fdSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
6938ce7184bSdan #ifndef SQLITE_OMIT_CTE
6948ce7184bSdan       if( eDest==SRT_DistTable ){
6958ce7184bSdan         /* If the destination is DistTable, then cursor (iParm+1) is open
6968ce7184bSdan         ** on an ephemeral index. If the current row is already present
6978ce7184bSdan         ** in the index, do not write it to the output. If not, add the
6988ce7184bSdan         ** current row to the index and proceed with writing it to the
6998ce7184bSdan         ** output table as well.  */
7008ce7184bSdan         int addr = sqlite3VdbeCurrentAddr(v) + 4;
7018ce7184bSdan         sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
7028ce7184bSdan         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
7038ce7184bSdan         assert( pOrderBy==0 );
7048ce7184bSdan       }
7058ce7184bSdan #endif
7065338a5f7Sdanielk1977       if( pOrderBy ){
707b7654111Sdrh         pushOntoSorter(pParse, pOrderBy, p, r1);
7085338a5f7Sdanielk1977       }else{
709b7654111Sdrh         int r2 = sqlite3GetTempReg(pParse);
710b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
711b7654111Sdrh         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
712b7654111Sdrh         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
713b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r2);
7145338a5f7Sdanielk1977       }
715b7654111Sdrh       sqlite3ReleaseTempReg(pParse, r1);
7165338a5f7Sdanielk1977       break;
7175338a5f7Sdanielk1977     }
7182282792aSdrh 
71993758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
7202282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
7212282792aSdrh     ** then there should be a single item on the stack.  Write this
7222282792aSdrh     ** item into the set table with bogus data.
7232282792aSdrh     */
724c926afbcSdrh     case SRT_Set: {
725340309fdSdrh       assert( nResultCol==1 );
726634d81deSdrh       pDest->affSdst =
727634d81deSdrh                   sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
728c926afbcSdrh       if( pOrderBy ){
729de941c60Sdrh         /* At first glance you would think we could optimize out the
730de941c60Sdrh         ** ORDER BY in this case since the order of entries in the set
731de941c60Sdrh         ** does not matter.  But there might be a LIMIT clause, in which
732de941c60Sdrh         ** case the order does matter */
733d847eaadSdrh         pushOntoSorter(pParse, pOrderBy, p, regResult);
734c926afbcSdrh       }else{
735b7654111Sdrh         int r1 = sqlite3GetTempReg(pParse);
736634d81deSdrh         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
737da250ea5Sdrh         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
738b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
739b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r1);
740c926afbcSdrh       }
741c926afbcSdrh       break;
742c926afbcSdrh     }
74382c3d636Sdrh 
744504b6989Sdrh     /* If any row exist in the result set, record that fact and abort.
745ec7429aeSdrh     */
746ec7429aeSdrh     case SRT_Exists: {
7474c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
748ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
749ec7429aeSdrh       break;
750ec7429aeSdrh     }
751ec7429aeSdrh 
7522282792aSdrh     /* If this is a scalar select that is part of an expression, then
7532282792aSdrh     ** store the results in the appropriate memory cell and break out
7542282792aSdrh     ** of the scan loop.
7552282792aSdrh     */
756c926afbcSdrh     case SRT_Mem: {
757340309fdSdrh       assert( nResultCol==1 );
758c926afbcSdrh       if( pOrderBy ){
759d847eaadSdrh         pushOntoSorter(pParse, pOrderBy, p, regResult);
760c926afbcSdrh       }else{
761b21e7c70Sdrh         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
762ec7429aeSdrh         /* The LIMIT clause will jump out of the loop for us */
763c926afbcSdrh       }
764c926afbcSdrh       break;
765c926afbcSdrh     }
76693758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
7672282792aSdrh 
768c182d163Sdrh     /* Send the data to the callback function or to a subroutine.  In the
769c182d163Sdrh     ** case of a subroutine, the subroutine itself is responsible for
770c182d163Sdrh     ** popping the data from the stack.
771f46f905aSdrh     */
772e00ee6ebSdrh     case SRT_Coroutine:
7737d10d5a6Sdrh     case SRT_Output: {
774373cc2ddSdrh       testcase( eDest==SRT_Coroutine );
775373cc2ddSdrh       testcase( eDest==SRT_Output );
776f46f905aSdrh       if( pOrderBy ){
777b7654111Sdrh         int r1 = sqlite3GetTempReg(pParse);
778340309fdSdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
779b7654111Sdrh         pushOntoSorter(pParse, pOrderBy, p, r1);
780b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r1);
781e00ee6ebSdrh       }else if( eDest==SRT_Coroutine ){
7822b596da8Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
783c182d163Sdrh       }else{
784340309fdSdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
785340309fdSdrh         sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
786ac82fcf5Sdrh       }
787142e30dfSdrh       break;
788142e30dfSdrh     }
789142e30dfSdrh 
790fe1c6bb9Sdrh #ifndef SQLITE_OMIT_CTE
791fe1c6bb9Sdrh     /* Write the results into a priority queue that is order according to
792fe1c6bb9Sdrh     ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
793fe1c6bb9Sdrh     ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
794fe1c6bb9Sdrh     ** pSO->nExpr columns, then make sure all keys are unique by adding a
795fe1c6bb9Sdrh     ** final OP_Sequence column.  The last column is the record as a blob.
796fe1c6bb9Sdrh     */
797fe1c6bb9Sdrh     case SRT_DistQueue:
798fe1c6bb9Sdrh     case SRT_Queue: {
799fe1c6bb9Sdrh       int nKey;
800fe1c6bb9Sdrh       int r1, r2, r3;
801fe1c6bb9Sdrh       int addrTest = 0;
802fe1c6bb9Sdrh       ExprList *pSO;
803fe1c6bb9Sdrh       pSO = pDest->pOrderBy;
804fe1c6bb9Sdrh       assert( pSO );
805fe1c6bb9Sdrh       nKey = pSO->nExpr;
806fe1c6bb9Sdrh       r1 = sqlite3GetTempReg(pParse);
807fe1c6bb9Sdrh       r2 = sqlite3GetTempRange(pParse, nKey+2);
808fe1c6bb9Sdrh       r3 = r2+nKey+1;
809fe1c6bb9Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
810fe1c6bb9Sdrh       if( eDest==SRT_DistQueue ){
811fe1c6bb9Sdrh         /* If the destination is DistQueue, then cursor (iParm+1) is open
812fe1c6bb9Sdrh         ** on a second ephemeral index that holds all values every previously
813fe1c6bb9Sdrh         ** added to the queue.  Only add this new value if it has never before
814fe1c6bb9Sdrh         ** been added */
815fe1c6bb9Sdrh         addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, r3, 0);
816fe1c6bb9Sdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
817cfe24586Sdan         sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
818fe1c6bb9Sdrh       }
819fe1c6bb9Sdrh       for(i=0; i<nKey; i++){
820fe1c6bb9Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy,
821fe1c6bb9Sdrh                           regResult + pSO->a[i].u.x.iOrderByCol - 1,
822fe1c6bb9Sdrh                           r2+i);
823fe1c6bb9Sdrh       }
824fe1c6bb9Sdrh       sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
825fe1c6bb9Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
826fe1c6bb9Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
827fe1c6bb9Sdrh       if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
828fe1c6bb9Sdrh       sqlite3ReleaseTempReg(pParse, r1);
829fe1c6bb9Sdrh       sqlite3ReleaseTempRange(pParse, r2, nKey+2);
830fe1c6bb9Sdrh       break;
831fe1c6bb9Sdrh     }
832fe1c6bb9Sdrh #endif /* SQLITE_OMIT_CTE */
833fe1c6bb9Sdrh 
834fe1c6bb9Sdrh 
835fe1c6bb9Sdrh 
8366a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER)
837d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
838d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
839d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
840d7489c39Sdrh     ** about the actual results of the select.
841d7489c39Sdrh     */
842c926afbcSdrh     default: {
843f46f905aSdrh       assert( eDest==SRT_Discard );
844c926afbcSdrh       break;
845c926afbcSdrh     }
84693758c8dSdanielk1977 #endif
847c926afbcSdrh   }
848ec7429aeSdrh 
8495e87be87Sdrh   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
8505e87be87Sdrh   ** there is a sorter, in which case the sorter has already limited
8515e87be87Sdrh   ** the output for us.
852ec7429aeSdrh   */
8535e87be87Sdrh   if( pOrderBy==0 && p->iLimit ){
8549b918ed1Sdrh     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
855ec7429aeSdrh   }
85682c3d636Sdrh }
85782c3d636Sdrh 
85882c3d636Sdrh /*
859ad124329Sdrh ** Allocate a KeyInfo object sufficient for an index of N key columns and
860ad124329Sdrh ** X extra columns.
861323df790Sdrh */
862ad124329Sdrh KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
8632ec2fb22Sdrh   KeyInfo *p = sqlite3DbMallocZero(0,
864ad124329Sdrh                    sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
865323df790Sdrh   if( p ){
866ad124329Sdrh     p->aSortOrder = (u8*)&p->aColl[N+X];
867323df790Sdrh     p->nField = (u16)N;
868ad124329Sdrh     p->nXField = (u16)X;
869323df790Sdrh     p->enc = ENC(db);
870323df790Sdrh     p->db = db;
8712ec2fb22Sdrh     p->nRef = 1;
8722ec2fb22Sdrh   }else{
8732ec2fb22Sdrh     db->mallocFailed = 1;
874323df790Sdrh   }
875323df790Sdrh   return p;
876323df790Sdrh }
877323df790Sdrh 
878323df790Sdrh /*
8792ec2fb22Sdrh ** Deallocate a KeyInfo object
8802ec2fb22Sdrh */
8812ec2fb22Sdrh void sqlite3KeyInfoUnref(KeyInfo *p){
8822ec2fb22Sdrh   if( p ){
8832ec2fb22Sdrh     assert( p->nRef>0 );
8842ec2fb22Sdrh     p->nRef--;
885c6efe12dSmistachkin     if( p->nRef==0 ) sqlite3DbFree(0, p);
8862ec2fb22Sdrh   }
8872ec2fb22Sdrh }
8882ec2fb22Sdrh 
8892ec2fb22Sdrh /*
8902ec2fb22Sdrh ** Make a new pointer to a KeyInfo object
8912ec2fb22Sdrh */
8922ec2fb22Sdrh KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
8932ec2fb22Sdrh   if( p ){
8942ec2fb22Sdrh     assert( p->nRef>0 );
8952ec2fb22Sdrh     p->nRef++;
8962ec2fb22Sdrh   }
8972ec2fb22Sdrh   return p;
8982ec2fb22Sdrh }
8992ec2fb22Sdrh 
9002ec2fb22Sdrh #ifdef SQLITE_DEBUG
9012ec2fb22Sdrh /*
9022ec2fb22Sdrh ** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
9032ec2fb22Sdrh ** can only be changed if this is just a single reference to the object.
9042ec2fb22Sdrh **
9052ec2fb22Sdrh ** This routine is used only inside of assert() statements.
9062ec2fb22Sdrh */
9072ec2fb22Sdrh int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
9082ec2fb22Sdrh #endif /* SQLITE_DEBUG */
9092ec2fb22Sdrh 
9102ec2fb22Sdrh /*
911dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records
912dece1a84Sdrh ** the collating sequence for each expression in that expression list.
913dece1a84Sdrh **
9140342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
9150342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to
9160342b1f5Sdrh ** implement that clause.  If the ExprList is the result set of a SELECT
9170342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual
9180342b1f5Sdrh ** index to implement a DISTINCT test.
9190342b1f5Sdrh **
920dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
921dece1a84Sdrh ** function is responsible for seeing that this structure is eventually
9222ec2fb22Sdrh ** freed.
923dece1a84Sdrh */
924fe1c6bb9Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList, int nExtra){
925dece1a84Sdrh   int nExpr;
926dece1a84Sdrh   KeyInfo *pInfo;
927dece1a84Sdrh   struct ExprList_item *pItem;
928323df790Sdrh   sqlite3 *db = pParse->db;
929dece1a84Sdrh   int i;
930dece1a84Sdrh 
931dece1a84Sdrh   nExpr = pList->nExpr;
932fe1c6bb9Sdrh   pInfo = sqlite3KeyInfoAlloc(db, nExpr+nExtra, 1);
933dece1a84Sdrh   if( pInfo ){
9342ec2fb22Sdrh     assert( sqlite3KeyInfoIsWriteable(pInfo) );
935dece1a84Sdrh     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
936dece1a84Sdrh       CollSeq *pColl;
937dece1a84Sdrh       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
938323df790Sdrh       if( !pColl ) pColl = db->pDfltColl;
939dece1a84Sdrh       pInfo->aColl[i] = pColl;
940dece1a84Sdrh       pInfo->aSortOrder[i] = pItem->sortOrder;
941dece1a84Sdrh     }
942dece1a84Sdrh   }
943dece1a84Sdrh   return pInfo;
944dece1a84Sdrh }
945dece1a84Sdrh 
9467f61e92cSdan #ifndef SQLITE_OMIT_COMPOUND_SELECT
9477f61e92cSdan /*
9487f61e92cSdan ** Name of the connection operator, used for error messages.
9497f61e92cSdan */
9507f61e92cSdan static const char *selectOpName(int id){
9517f61e92cSdan   char *z;
9527f61e92cSdan   switch( id ){
9537f61e92cSdan     case TK_ALL:       z = "UNION ALL";   break;
9547f61e92cSdan     case TK_INTERSECT: z = "INTERSECT";   break;
9557f61e92cSdan     case TK_EXCEPT:    z = "EXCEPT";      break;
9567f61e92cSdan     default:           z = "UNION";       break;
9577f61e92cSdan   }
9587f61e92cSdan   return z;
9597f61e92cSdan }
9607f61e92cSdan #endif /* SQLITE_OMIT_COMPOUND_SELECT */
9617f61e92cSdan 
9622ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN
96317c0bc0cSdan /*
96417c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
96517c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
96617c0bc0cSdan ** where the caption is of the form:
96717c0bc0cSdan **
96817c0bc0cSdan **   "USE TEMP B-TREE FOR xxx"
96917c0bc0cSdan **
97017c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
97117c0bc0cSdan ** is determined by the zUsage argument.
97217c0bc0cSdan */
9732ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){
9742ce22453Sdan   if( pParse->explain==2 ){
9752ce22453Sdan     Vdbe *v = pParse->pVdbe;
9762ce22453Sdan     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
9772ce22453Sdan     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
9782ce22453Sdan   }
9792ce22453Sdan }
98017c0bc0cSdan 
98117c0bc0cSdan /*
982bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro
983bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
984bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that
985bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
986bb2b4418Sdan ** code with #ifndef directives.
987bb2b4418Sdan */
988bb2b4418Sdan # define explainSetInteger(a, b) a = b
989bb2b4418Sdan 
990bb2b4418Sdan #else
991bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */
992bb2b4418Sdan # define explainTempTable(y,z)
993bb2b4418Sdan # define explainSetInteger(y,z)
994bb2b4418Sdan #endif
995bb2b4418Sdan 
996bb2b4418Sdan #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
997bb2b4418Sdan /*
9987f61e92cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
9997f61e92cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
10007f61e92cSdan ** where the caption is of one of the two forms:
10017f61e92cSdan **
10027f61e92cSdan **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
10037f61e92cSdan **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
10047f61e92cSdan **
10057f61e92cSdan ** where iSub1 and iSub2 are the integers passed as the corresponding
10067f61e92cSdan ** function parameters, and op is the text representation of the parameter
10077f61e92cSdan ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
10087f61e92cSdan ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
10097f61e92cSdan ** false, or the second form if it is true.
10107f61e92cSdan */
10117f61e92cSdan static void explainComposite(
10127f61e92cSdan   Parse *pParse,                  /* Parse context */
10137f61e92cSdan   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
10147f61e92cSdan   int iSub1,                      /* Subquery id 1 */
10157f61e92cSdan   int iSub2,                      /* Subquery id 2 */
10167f61e92cSdan   int bUseTmp                     /* True if a temp table was used */
10177f61e92cSdan ){
10187f61e92cSdan   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
10197f61e92cSdan   if( pParse->explain==2 ){
10207f61e92cSdan     Vdbe *v = pParse->pVdbe;
10217f61e92cSdan     char *zMsg = sqlite3MPrintf(
102230969d3fSdan         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
10237f61e92cSdan         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
10247f61e92cSdan     );
10257f61e92cSdan     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
10267f61e92cSdan   }
10277f61e92cSdan }
10282ce22453Sdan #else
102917c0bc0cSdan /* No-op versions of the explainXXX() functions and macros. */
10307f61e92cSdan # define explainComposite(v,w,x,y,z)
10312ce22453Sdan #endif
1032dece1a84Sdrh 
1033dece1a84Sdrh /*
1034d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
1035d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
1036d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
1037d8bc7086Sdrh ** routine generates the code needed to do that.
1038d8bc7086Sdrh */
1039c926afbcSdrh static void generateSortTail(
1040cdd536f0Sdrh   Parse *pParse,    /* Parsing context */
1041c926afbcSdrh   Select *p,        /* The SELECT statement */
1042c926afbcSdrh   Vdbe *v,          /* Generate code into this VDBE */
1043c926afbcSdrh   int nColumn,      /* Number of columns of data */
10446c8c8ce0Sdanielk1977   SelectDest *pDest /* Write the sorted results here */
1045c926afbcSdrh ){
1046dc5ea5c7Sdrh   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
1047dc5ea5c7Sdrh   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
1048d8bc7086Sdrh   int addr;
10490342b1f5Sdrh   int iTab;
105061fc595fSdrh   int pseudoTab = 0;
10510342b1f5Sdrh   ExprList *pOrderBy = p->pOrderBy;
1052ffbc3088Sdrh 
10536c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
10542b596da8Sdrh   int iParm = pDest->iSDParm;
10556c8c8ce0Sdanielk1977 
10562d401ab8Sdrh   int regRow;
10572d401ab8Sdrh   int regRowid;
10582d401ab8Sdrh 
10599d2985c7Sdrh   iTab = pOrderBy->iECursor;
10603e9ca094Sdrh   regRow = sqlite3GetTempReg(pParse);
10617d10d5a6Sdrh   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
1062cdd536f0Sdrh     pseudoTab = pParse->nTab++;
10633e9ca094Sdrh     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
10643e9ca094Sdrh     regRowid = 0;
10653e9ca094Sdrh   }else{
10663e9ca094Sdrh     regRowid = sqlite3GetTempReg(pParse);
1067cdd536f0Sdrh   }
1068c6aff30cSdrh   if( p->selFlags & SF_UseSorter ){
1069c2bb3282Sdrh     int regSortOut = ++pParse->nMem;
1070c6aff30cSdrh     int ptab2 = pParse->nTab++;
1071c6aff30cSdrh     sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
1072c6aff30cSdrh     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
1073aa9ce707Sdrh     codeOffset(v, p->iOffset, addrContinue);
1074c6aff30cSdrh     sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
1075c6aff30cSdrh     sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
1076c6aff30cSdrh     sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
1077c6aff30cSdrh   }else{
1078dc5ea5c7Sdrh     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
1079aa9ce707Sdrh     codeOffset(v, p->iOffset, addrContinue);
10802d401ab8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
1081c6aff30cSdrh   }
1082c926afbcSdrh   switch( eDest ){
1083c926afbcSdrh     case SRT_Table:
1084b9bb7c18Sdrh     case SRT_EphemTab: {
10851c767f0dSdrh       testcase( eDest==SRT_Table );
10861c767f0dSdrh       testcase( eDest==SRT_EphemTab );
10872d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
10882d401ab8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
10892d401ab8Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1090c926afbcSdrh       break;
1091c926afbcSdrh     }
109293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
1093c926afbcSdrh     case SRT_Set: {
1094c926afbcSdrh       assert( nColumn==1 );
1095634d81deSdrh       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
1096634d81deSdrh                         &pDest->affSdst, 1);
1097da250ea5Sdrh       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
1098a7a8e14bSdanielk1977       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
1099c926afbcSdrh       break;
1100c926afbcSdrh     }
1101c926afbcSdrh     case SRT_Mem: {
1102c926afbcSdrh       assert( nColumn==1 );
1103b21e7c70Sdrh       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
1104ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
1105c926afbcSdrh       break;
1106c926afbcSdrh     }
110793758c8dSdanielk1977 #endif
1108373cc2ddSdrh     default: {
1109ac82fcf5Sdrh       int i;
1110373cc2ddSdrh       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
11111c767f0dSdrh       testcase( eDest==SRT_Output );
11121c767f0dSdrh       testcase( eDest==SRT_Coroutine );
1113ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
11142b596da8Sdrh         assert( regRow!=pDest->iSdst+i );
11152b596da8Sdrh         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
11163e9ca094Sdrh         if( i==0 ){
11173e9ca094Sdrh           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
11183e9ca094Sdrh         }
1119ac82fcf5Sdrh       }
11207d10d5a6Sdrh       if( eDest==SRT_Output ){
11212b596da8Sdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
11222b596da8Sdrh         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
1123a9671a22Sdrh       }else{
11242b596da8Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1125ce665cf6Sdrh       }
1126ac82fcf5Sdrh       break;
1127ac82fcf5Sdrh     }
1128c926afbcSdrh   }
11292d401ab8Sdrh   sqlite3ReleaseTempReg(pParse, regRow);
11302d401ab8Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
1131ec7429aeSdrh 
1132ec7429aeSdrh   /* The bottom of the loop
1133ec7429aeSdrh   */
1134dc5ea5c7Sdrh   sqlite3VdbeResolveLabel(v, addrContinue);
1135c6aff30cSdrh   if( p->selFlags & SF_UseSorter ){
1136c6aff30cSdrh     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
1137c6aff30cSdrh   }else{
113866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
1139c6aff30cSdrh   }
1140dc5ea5c7Sdrh   sqlite3VdbeResolveLabel(v, addrBreak);
11417d10d5a6Sdrh   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
114266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
1143cdd536f0Sdrh   }
1144d8bc7086Sdrh }
1145d8bc7086Sdrh 
1146d8bc7086Sdrh /*
1147517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
1148517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
1149e78e8284Sdrh **
11505f3e5e74Sdrh ** Also try to estimate the size of the returned value and return that
11515f3e5e74Sdrh ** result in *pEstWidth.
11525f3e5e74Sdrh **
1153955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the
1154955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The
1155955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
1156955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The
1157955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is
1158955de52cSdanielk1977 ** considered a column by this function.
1159e78e8284Sdrh **
1160955de52cSdanielk1977 **   SELECT col FROM tbl;
1161955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl;
1162955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl);
1163955de52cSdanielk1977 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
1164955de52cSdanielk1977 **
1165955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL.
11665f3e5e74Sdrh **
11675f3e5e74Sdrh ** This routine has either 3 or 6 parameters depending on whether or not
11685f3e5e74Sdrh ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
1169fcb78a49Sdrh */
11705f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
11715f3e5e74Sdrh # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
11725f3e5e74Sdrh static const char *columnTypeImpl(
1173955de52cSdanielk1977   NameContext *pNC,
1174955de52cSdanielk1977   Expr *pExpr,
11755f3e5e74Sdrh   const char **pzOrigDb,
11765f3e5e74Sdrh   const char **pzOrigTab,
11775f3e5e74Sdrh   const char **pzOrigCol,
11785f3e5e74Sdrh   u8 *pEstWidth
1179955de52cSdanielk1977 ){
11805f3e5e74Sdrh   char const *zOrigDb = 0;
11815f3e5e74Sdrh   char const *zOrigTab = 0;
11825f3e5e74Sdrh   char const *zOrigCol = 0;
11835f3e5e74Sdrh #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
11845f3e5e74Sdrh # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
11855f3e5e74Sdrh static const char *columnTypeImpl(
11865f3e5e74Sdrh   NameContext *pNC,
11875f3e5e74Sdrh   Expr *pExpr,
11885f3e5e74Sdrh   u8 *pEstWidth
11895f3e5e74Sdrh ){
11905f3e5e74Sdrh #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
1191955de52cSdanielk1977   char const *zType = 0;
1192517eb646Sdanielk1977   int j;
11935f3e5e74Sdrh   u8 estWidth = 1;
11945338a5f7Sdanielk1977 
11955f3e5e74Sdrh   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
119600e279d9Sdanielk1977   switch( pExpr->op ){
119730bcf5dbSdrh     case TK_AGG_COLUMN:
119800e279d9Sdanielk1977     case TK_COLUMN: {
1199955de52cSdanielk1977       /* The expression is a column. Locate the table the column is being
1200955de52cSdanielk1977       ** extracted from in NameContext.pSrcList. This table may be real
1201955de52cSdanielk1977       ** database table or a subquery.
1202955de52cSdanielk1977       */
1203955de52cSdanielk1977       Table *pTab = 0;            /* Table structure column is extracted from */
1204955de52cSdanielk1977       Select *pS = 0;             /* Select the column is extracted from */
1205955de52cSdanielk1977       int iCol = pExpr->iColumn;  /* Index of column in pTab */
1206373cc2ddSdrh       testcase( pExpr->op==TK_AGG_COLUMN );
1207373cc2ddSdrh       testcase( pExpr->op==TK_COLUMN );
120843bc88bbSdan       while( pNC && !pTab ){
1209b3bce662Sdanielk1977         SrcList *pTabList = pNC->pSrcList;
1210b3bce662Sdanielk1977         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
1211b3bce662Sdanielk1977         if( j<pTabList->nSrc ){
12126a3ea0e6Sdrh           pTab = pTabList->a[j].pTab;
1213955de52cSdanielk1977           pS = pTabList->a[j].pSelect;
1214b3bce662Sdanielk1977         }else{
1215b3bce662Sdanielk1977           pNC = pNC->pNext;
1216b3bce662Sdanielk1977         }
1217b3bce662Sdanielk1977       }
1218955de52cSdanielk1977 
121943bc88bbSdan       if( pTab==0 ){
1220417168adSdrh         /* At one time, code such as "SELECT new.x" within a trigger would
1221417168adSdrh         ** cause this condition to run.  Since then, we have restructured how
1222417168adSdrh         ** trigger code is generated and so this condition is no longer
122343bc88bbSdan         ** possible. However, it can still be true for statements like
122443bc88bbSdan         ** the following:
122543bc88bbSdan         **
122643bc88bbSdan         **   CREATE TABLE t1(col INTEGER);
122743bc88bbSdan         **   SELECT (SELECT t1.col) FROM FROM t1;
122843bc88bbSdan         **
122943bc88bbSdan         ** when columnType() is called on the expression "t1.col" in the
123043bc88bbSdan         ** sub-select. In this case, set the column type to NULL, even
123143bc88bbSdan         ** though it should really be "INTEGER".
123243bc88bbSdan         **
123343bc88bbSdan         ** This is not a problem, as the column type of "t1.col" is never
123443bc88bbSdan         ** used. When columnType() is called on the expression
123543bc88bbSdan         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
123643bc88bbSdan         ** branch below.  */
12377e62779aSdrh         break;
12387e62779aSdrh       }
1239955de52cSdanielk1977 
124043bc88bbSdan       assert( pTab && pExpr->pTab==pTab );
1241955de52cSdanielk1977       if( pS ){
1242955de52cSdanielk1977         /* The "table" is actually a sub-select or a view in the FROM clause
1243955de52cSdanielk1977         ** of the SELECT statement. Return the declaration type and origin
1244955de52cSdanielk1977         ** data for the result-set column of the sub-select.
1245955de52cSdanielk1977         */
12467b688edeSdrh         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
1247955de52cSdanielk1977           /* If iCol is less than zero, then the expression requests the
1248955de52cSdanielk1977           ** rowid of the sub-select or view. This expression is legal (see
1249955de52cSdanielk1977           ** test case misc2.2.2) - it always evaluates to NULL.
1250955de52cSdanielk1977           */
1251955de52cSdanielk1977           NameContext sNC;
1252955de52cSdanielk1977           Expr *p = pS->pEList->a[iCol].pExpr;
1253955de52cSdanielk1977           sNC.pSrcList = pS->pSrc;
125443bc88bbSdan           sNC.pNext = pNC;
1255955de52cSdanielk1977           sNC.pParse = pNC->pParse;
12565f3e5e74Sdrh           zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
1257955de52cSdanielk1977         }
125893c36bb3Sdrh       }else if( pTab->pSchema ){
1259955de52cSdanielk1977         /* A real table */
1260955de52cSdanielk1977         assert( !pS );
1261fcb78a49Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
1262fcb78a49Sdrh         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
12635f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1264fcb78a49Sdrh         if( iCol<0 ){
1265fcb78a49Sdrh           zType = "INTEGER";
12665f3e5e74Sdrh           zOrigCol = "rowid";
1267fcb78a49Sdrh         }else{
1268fcb78a49Sdrh           zType = pTab->aCol[iCol].zType;
12695f3e5e74Sdrh           zOrigCol = pTab->aCol[iCol].zName;
12705f3e5e74Sdrh           estWidth = pTab->aCol[iCol].szEst;
1271955de52cSdanielk1977         }
12725f3e5e74Sdrh         zOrigTab = pTab->zName;
1273955de52cSdanielk1977         if( pNC->pParse ){
1274955de52cSdanielk1977           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
12755f3e5e74Sdrh           zOrigDb = pNC->pParse->db->aDb[iDb].zName;
1276955de52cSdanielk1977         }
12775f3e5e74Sdrh #else
12785f3e5e74Sdrh         if( iCol<0 ){
12795f3e5e74Sdrh           zType = "INTEGER";
12805f3e5e74Sdrh         }else{
12815f3e5e74Sdrh           zType = pTab->aCol[iCol].zType;
12825f3e5e74Sdrh           estWidth = pTab->aCol[iCol].szEst;
12835f3e5e74Sdrh         }
12845f3e5e74Sdrh #endif
1285fcb78a49Sdrh       }
128600e279d9Sdanielk1977       break;
1287736c22b8Sdrh     }
128893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
128900e279d9Sdanielk1977     case TK_SELECT: {
1290955de52cSdanielk1977       /* The expression is a sub-select. Return the declaration type and
1291955de52cSdanielk1977       ** origin info for the single column in the result set of the SELECT
1292955de52cSdanielk1977       ** statement.
1293955de52cSdanielk1977       */
1294b3bce662Sdanielk1977       NameContext sNC;
12956ab3a2ecSdanielk1977       Select *pS = pExpr->x.pSelect;
1296955de52cSdanielk1977       Expr *p = pS->pEList->a[0].pExpr;
12976ab3a2ecSdanielk1977       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
1298955de52cSdanielk1977       sNC.pSrcList = pS->pSrc;
1299b3bce662Sdanielk1977       sNC.pNext = pNC;
1300955de52cSdanielk1977       sNC.pParse = pNC->pParse;
13015f3e5e74Sdrh       zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
130200e279d9Sdanielk1977       break;
1303fcb78a49Sdrh     }
130493758c8dSdanielk1977 #endif
130500e279d9Sdanielk1977   }
130600e279d9Sdanielk1977 
13075f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
13085f3e5e74Sdrh   if( pzOrigDb ){
13095f3e5e74Sdrh     assert( pzOrigTab && pzOrigCol );
13105f3e5e74Sdrh     *pzOrigDb = zOrigDb;
13115f3e5e74Sdrh     *pzOrigTab = zOrigTab;
13125f3e5e74Sdrh     *pzOrigCol = zOrigCol;
1313955de52cSdanielk1977   }
13145f3e5e74Sdrh #endif
13155f3e5e74Sdrh   if( pEstWidth ) *pEstWidth = estWidth;
1316517eb646Sdanielk1977   return zType;
1317517eb646Sdanielk1977 }
1318517eb646Sdanielk1977 
1319517eb646Sdanielk1977 /*
1320517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
1321517eb646Sdanielk1977 ** in the result set.
1322517eb646Sdanielk1977 */
1323517eb646Sdanielk1977 static void generateColumnTypes(
1324517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
1325517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
1326517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
1327517eb646Sdanielk1977 ){
13283f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE
1329517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
1330517eb646Sdanielk1977   int i;
1331b3bce662Sdanielk1977   NameContext sNC;
1332b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
1333955de52cSdanielk1977   sNC.pParse = pParse;
1334517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
1335517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
13363f913576Sdrh     const char *zType;
13373f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1338955de52cSdanielk1977     const char *zOrigDb = 0;
1339955de52cSdanielk1977     const char *zOrigTab = 0;
1340955de52cSdanielk1977     const char *zOrigCol = 0;
13415f3e5e74Sdrh     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
1342955de52cSdanielk1977 
134385b623f2Sdrh     /* The vdbe must make its own copy of the column-type and other
13444b1ae99dSdanielk1977     ** column specific strings, in case the schema is reset before this
13454b1ae99dSdanielk1977     ** virtual machine is deleted.
1346fbcd585fSdanielk1977     */
134710fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
134810fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
134910fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
13503f913576Sdrh #else
13515f3e5e74Sdrh     zType = columnType(&sNC, p, 0, 0, 0, 0);
13523f913576Sdrh #endif
135310fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
1354fcb78a49Sdrh   }
13555f3e5e74Sdrh #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
1356fcb78a49Sdrh }
1357fcb78a49Sdrh 
1358fcb78a49Sdrh /*
1359fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
1360fcb78a49Sdrh ** in the result set.  This information is used to provide the
1361fcabd464Sdrh ** azCol[] values in the callback.
136282c3d636Sdrh */
1363832508b7Sdrh static void generateColumnNames(
1364832508b7Sdrh   Parse *pParse,      /* Parser context */
1365ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
1366832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
1367832508b7Sdrh ){
1368d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
13696a3ea0e6Sdrh   int i, j;
13709bb575fdSdrh   sqlite3 *db = pParse->db;
1371fcabd464Sdrh   int fullNames, shortNames;
1372fcabd464Sdrh 
1373fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN
13743cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
13753cf86063Sdanielk1977   if( pParse->explain ){
137661de0d1bSdanielk1977     return;
13773cf86063Sdanielk1977   }
13785338a5f7Sdanielk1977 #endif
13793cf86063Sdanielk1977 
1380e2f02bacSdrh   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
1381d8bc7086Sdrh   pParse->colNamesSet = 1;
1382fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
1383fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
138422322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
138582c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
138682c3d636Sdrh     Expr *p;
13875a38705eSdrh     p = pEList->a[i].pExpr;
1388373cc2ddSdrh     if( NEVER(p==0) ) continue;
138982c3d636Sdrh     if( pEList->a[i].zName ){
139082c3d636Sdrh       char *zName = pEList->a[i].zName;
139110fb749bSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
1392f018cc2eSdrh     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
13936a3ea0e6Sdrh       Table *pTab;
139497665873Sdrh       char *zCol;
13958aff1015Sdrh       int iCol = p->iColumn;
1396e2f02bacSdrh       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
1397e2f02bacSdrh         if( pTabList->a[j].iCursor==p->iTable ) break;
1398e2f02bacSdrh       }
13996a3ea0e6Sdrh       assert( j<pTabList->nSrc );
14006a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
14018aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
140297665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1403b1363206Sdrh       if( iCol<0 ){
140447a6db2bSdrh         zCol = "rowid";
1405b1363206Sdrh       }else{
1406b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
1407b1363206Sdrh       }
1408e49b146fSdrh       if( !shortNames && !fullNames ){
140910fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
1410b7916a78Sdrh             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
14111c767f0dSdrh       }else if( fullNames ){
141282c3d636Sdrh         char *zName = 0;
14131c767f0dSdrh         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
141410fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
141582c3d636Sdrh       }else{
141610fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
141782c3d636Sdrh       }
14181bee3d7bSdrh     }else{
1419859bc542Sdrh       const char *z = pEList->a[i].zSpan;
1420859bc542Sdrh       z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
1421859bc542Sdrh       sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
142282c3d636Sdrh     }
142382c3d636Sdrh   }
142476d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
14255080aaa7Sdrh }
142682c3d636Sdrh 
1427d8bc7086Sdrh /*
14287d10d5a6Sdrh ** Given a an expression list (which is really the list of expressions
14297d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate
14307d10d5a6Sdrh ** column names for a table that would hold the expression list.
14317d10d5a6Sdrh **
14327d10d5a6Sdrh ** All column names will be unique.
14337d10d5a6Sdrh **
14347d10d5a6Sdrh ** Only the column names are computed.  Column.zType, Column.zColl,
14357d10d5a6Sdrh ** and other fields of Column are zeroed.
14367d10d5a6Sdrh **
14377d10d5a6Sdrh ** Return SQLITE_OK on success.  If a memory allocation error occurs,
14387d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
1439315555caSdrh */
14407d10d5a6Sdrh static int selectColumnsFromExprList(
14417d10d5a6Sdrh   Parse *pParse,          /* Parsing context */
14427d10d5a6Sdrh   ExprList *pEList,       /* Expr list from which to derive column names */
1443d815f17dSdrh   i16 *pnCol,             /* Write the number of columns here */
14447d10d5a6Sdrh   Column **paCol          /* Write the new column list here */
14457d10d5a6Sdrh ){
1446dc5ea5c7Sdrh   sqlite3 *db = pParse->db;   /* Database connection */
1447dc5ea5c7Sdrh   int i, j;                   /* Loop counters */
1448dc5ea5c7Sdrh   int cnt;                    /* Index added to make the name unique */
1449dc5ea5c7Sdrh   Column *aCol, *pCol;        /* For looping over result columns */
1450dc5ea5c7Sdrh   int nCol;                   /* Number of columns in the result set */
1451dc5ea5c7Sdrh   Expr *p;                    /* Expression for a single result column */
1452dc5ea5c7Sdrh   char *zName;                /* Column name */
1453dc5ea5c7Sdrh   int nName;                  /* Size of name in zName[] */
145479d5f63fSdrh 
14558c2e0f02Sdan   if( pEList ){
14568c2e0f02Sdan     nCol = pEList->nExpr;
14578c2e0f02Sdan     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
14588c2e0f02Sdan     testcase( aCol==0 );
14598c2e0f02Sdan   }else{
14608c2e0f02Sdan     nCol = 0;
14618c2e0f02Sdan     aCol = 0;
14628c2e0f02Sdan   }
14638c2e0f02Sdan   *pnCol = nCol;
14648c2e0f02Sdan   *paCol = aCol;
14658c2e0f02Sdan 
14667d10d5a6Sdrh   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
146779d5f63fSdrh     /* Get an appropriate name for the column
146879d5f63fSdrh     */
1469580c8c18Sdrh     p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
147091bb0eedSdrh     if( (zName = pEList->a[i].zName)!=0 ){
147179d5f63fSdrh       /* If the column contains an "AS <name>" phrase, use <name> as the name */
147217435752Sdrh       zName = sqlite3DbStrDup(db, zName);
14737d10d5a6Sdrh     }else{
1474dc5ea5c7Sdrh       Expr *pColExpr = p;  /* The expression that is the result column name */
1475dc5ea5c7Sdrh       Table *pTab;         /* Table associated with this expression */
1476b07028f7Sdrh       while( pColExpr->op==TK_DOT ){
1477b07028f7Sdrh         pColExpr = pColExpr->pRight;
1478b07028f7Sdrh         assert( pColExpr!=0 );
1479b07028f7Sdrh       }
1480373cc2ddSdrh       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
148193a960a0Sdrh         /* For columns use the column name name */
1482dc5ea5c7Sdrh         int iCol = pColExpr->iColumn;
1483373cc2ddSdrh         pTab = pColExpr->pTab;
1484f0209f74Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
1485f0209f74Sdrh         zName = sqlite3MPrintf(db, "%s",
1486f0209f74Sdrh                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
1487b7916a78Sdrh       }else if( pColExpr->op==TK_ID ){
148833e619fcSdrh         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
148933e619fcSdrh         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
149093a960a0Sdrh       }else{
149179d5f63fSdrh         /* Use the original text of the column expression as its name */
1492b7916a78Sdrh         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
14937d10d5a6Sdrh       }
149422f70c32Sdrh     }
14957ce72f69Sdrh     if( db->mallocFailed ){
1496633e6d57Sdrh       sqlite3DbFree(db, zName);
14977ce72f69Sdrh       break;
1498dd5b2fa5Sdrh     }
149979d5f63fSdrh 
150079d5f63fSdrh     /* Make sure the column name is unique.  If the name is not unique,
150179d5f63fSdrh     ** append a integer to the name so that it becomes unique.
150279d5f63fSdrh     */
1503ea678832Sdrh     nName = sqlite3Strlen30(zName);
150479d5f63fSdrh     for(j=cnt=0; j<i; j++){
150579d5f63fSdrh       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
1506633e6d57Sdrh         char *zNewName;
1507fb777327Sdrh         int k;
1508fb777327Sdrh         for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
1509fb777327Sdrh         if( zName[k]==':' ) nName = k;
15102564ef97Sdrh         zName[nName] = 0;
1511633e6d57Sdrh         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
1512633e6d57Sdrh         sqlite3DbFree(db, zName);
1513633e6d57Sdrh         zName = zNewName;
151479d5f63fSdrh         j = -1;
1515dd5b2fa5Sdrh         if( zName==0 ) break;
151679d5f63fSdrh       }
151779d5f63fSdrh     }
151891bb0eedSdrh     pCol->zName = zName;
15197d10d5a6Sdrh   }
15207d10d5a6Sdrh   if( db->mallocFailed ){
15217d10d5a6Sdrh     for(j=0; j<i; j++){
15227d10d5a6Sdrh       sqlite3DbFree(db, aCol[j].zName);
15237d10d5a6Sdrh     }
15247d10d5a6Sdrh     sqlite3DbFree(db, aCol);
15257d10d5a6Sdrh     *paCol = 0;
15267d10d5a6Sdrh     *pnCol = 0;
15277d10d5a6Sdrh     return SQLITE_NOMEM;
15287d10d5a6Sdrh   }
15297d10d5a6Sdrh   return SQLITE_OK;
15307d10d5a6Sdrh }
1531e014a838Sdanielk1977 
15327d10d5a6Sdrh /*
15337d10d5a6Sdrh ** Add type and collation information to a column list based on
15347d10d5a6Sdrh ** a SELECT statement.
15357d10d5a6Sdrh **
15367d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList().
15377d10d5a6Sdrh ** The column list has only names, not types or collations.  This
15387d10d5a6Sdrh ** routine goes through and adds the types and collations.
15397d10d5a6Sdrh **
1540b08a67a7Sshane ** This routine requires that all identifiers in the SELECT
15417d10d5a6Sdrh ** statement be resolved.
154279d5f63fSdrh */
15437d10d5a6Sdrh static void selectAddColumnTypeAndCollation(
15447d10d5a6Sdrh   Parse *pParse,        /* Parsing contexts */
1545186ad8ccSdrh   Table *pTab,          /* Add column type information to this table */
15467d10d5a6Sdrh   Select *pSelect       /* SELECT used to determine types and collations */
15477d10d5a6Sdrh ){
15487d10d5a6Sdrh   sqlite3 *db = pParse->db;
15497d10d5a6Sdrh   NameContext sNC;
15507d10d5a6Sdrh   Column *pCol;
15517d10d5a6Sdrh   CollSeq *pColl;
15527d10d5a6Sdrh   int i;
15537d10d5a6Sdrh   Expr *p;
15547d10d5a6Sdrh   struct ExprList_item *a;
1555186ad8ccSdrh   u64 szAll = 0;
15567d10d5a6Sdrh 
15577d10d5a6Sdrh   assert( pSelect!=0 );
15587d10d5a6Sdrh   assert( (pSelect->selFlags & SF_Resolved)!=0 );
1559186ad8ccSdrh   assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
15607d10d5a6Sdrh   if( db->mallocFailed ) return;
1561c43e8be8Sdrh   memset(&sNC, 0, sizeof(sNC));
1562b3bce662Sdanielk1977   sNC.pSrcList = pSelect->pSrc;
15637d10d5a6Sdrh   a = pSelect->pEList->a;
1564186ad8ccSdrh   for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
15657d10d5a6Sdrh     p = a[i].pExpr;
15665f3e5e74Sdrh     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
1567186ad8ccSdrh     szAll += pCol->szEst;
1568c60e9b82Sdanielk1977     pCol->affinity = sqlite3ExprAffinity(p);
1569c4a64facSdrh     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
1570b3bf556eSdanielk1977     pColl = sqlite3ExprCollSeq(pParse, p);
1571b3bf556eSdanielk1977     if( pColl ){
157217435752Sdrh       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
15730202b29eSdanielk1977     }
157422f70c32Sdrh   }
1575186ad8ccSdrh   pTab->szTabRow = sqlite3LogEst(szAll*4);
15767d10d5a6Sdrh }
15777d10d5a6Sdrh 
15787d10d5a6Sdrh /*
15797d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes
15807d10d5a6Sdrh ** the result set of that SELECT.
15817d10d5a6Sdrh */
15827d10d5a6Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
15837d10d5a6Sdrh   Table *pTab;
15847d10d5a6Sdrh   sqlite3 *db = pParse->db;
15857d10d5a6Sdrh   int savedFlags;
15867d10d5a6Sdrh 
15877d10d5a6Sdrh   savedFlags = db->flags;
15887d10d5a6Sdrh   db->flags &= ~SQLITE_FullColNames;
15897d10d5a6Sdrh   db->flags |= SQLITE_ShortColNames;
15907d10d5a6Sdrh   sqlite3SelectPrep(pParse, pSelect, 0);
15917d10d5a6Sdrh   if( pParse->nErr ) return 0;
15927d10d5a6Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
15937d10d5a6Sdrh   db->flags = savedFlags;
15947d10d5a6Sdrh   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
15957d10d5a6Sdrh   if( pTab==0 ){
15967d10d5a6Sdrh     return 0;
15977d10d5a6Sdrh   }
1598373cc2ddSdrh   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
1599b2468954Sdrh   ** is disabled */
1600373cc2ddSdrh   assert( db->lookaside.bEnabled==0 );
16017d10d5a6Sdrh   pTab->nRef = 1;
16027d10d5a6Sdrh   pTab->zName = 0;
1603186ad8ccSdrh   pTab->nRowEst = 1048576;
16047d10d5a6Sdrh   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
1605186ad8ccSdrh   selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
160622f70c32Sdrh   pTab->iPKey = -1;
16077ce72f69Sdrh   if( db->mallocFailed ){
16081feeaed2Sdan     sqlite3DeleteTable(db, pTab);
16097ce72f69Sdrh     return 0;
16107ce72f69Sdrh   }
161122f70c32Sdrh   return pTab;
161222f70c32Sdrh }
161322f70c32Sdrh 
161422f70c32Sdrh /*
1615d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1616d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1617d8bc7086Sdrh */
16184adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1619d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1620d8bc7086Sdrh   if( v==0 ){
16219ac7962aSdrh     v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
1622949f9cd5Sdrh #ifndef SQLITE_OMIT_TRACE
1623949f9cd5Sdrh     if( v ){
1624949f9cd5Sdrh       sqlite3VdbeAddOp0(v, OP_Trace);
1625949f9cd5Sdrh     }
1626949f9cd5Sdrh #endif
1627d8bc7086Sdrh   }
1628d8bc7086Sdrh   return v;
1629d8bc7086Sdrh }
1630d8bc7086Sdrh 
163115007a99Sdrh 
1632d8bc7086Sdrh /*
16337b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
1634ec7429aeSdrh ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
16357b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
1636a2dc3b1aSdanielk1977 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1637a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute
1638a2dc3b1aSdanielk1977 ** the limit and offset.  If there is no limit and/or offset, then
1639a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative.
16407b58daeaSdrh **
1641d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if
1642ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset.  iLimit and
1643aa9ce707Sdrh ** iOffset should have been preset to appropriate default values (zero)
1644aa9ce707Sdrh ** prior to calling this routine.
1645aa9ce707Sdrh **
1646aa9ce707Sdrh ** The iOffset register (if it exists) is initialized to the value
1647aa9ce707Sdrh ** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
1648aa9ce707Sdrh ** iOffset+1 is initialized to LIMIT+OFFSET.
1649aa9ce707Sdrh **
1650ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
16517b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
16527b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
16537b58daeaSdrh ** SELECT statements.
16547b58daeaSdrh */
1655ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
165602afc861Sdrh   Vdbe *v = 0;
165702afc861Sdrh   int iLimit = 0;
165815007a99Sdrh   int iOffset;
16599b918ed1Sdrh   int addr1, n;
16600acb7e48Sdrh   if( p->iLimit ) return;
166115007a99Sdrh 
16627b58daeaSdrh   /*
16637b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
1664f7b5496eSdrh   ** controversy about what the correct behavior should be.
16657b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
16667b58daeaSdrh   ** no rows.
16677b58daeaSdrh   */
1668ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
1669373cc2ddSdrh   assert( p->pOffset==0 || p->pLimit!=0 );
1670a2dc3b1aSdanielk1977   if( p->pLimit ){
16710a07c107Sdrh     p->iLimit = iLimit = ++pParse->nMem;
167215007a99Sdrh     v = sqlite3GetVdbe(pParse);
1673aa9ce707Sdrh     assert( v!=0 );
16749b918ed1Sdrh     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
16759b918ed1Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
16769b918ed1Sdrh       VdbeComment((v, "LIMIT counter"));
1677456e4e4fSdrh       if( n==0 ){
1678456e4e4fSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
1679613ba1eaSdrh       }else if( n>=0 && p->nSelectRow>(u64)n ){
1680613ba1eaSdrh         p->nSelectRow = n;
16819b918ed1Sdrh       }
16829b918ed1Sdrh     }else{
1683b7654111Sdrh       sqlite3ExprCode(pParse, p->pLimit, iLimit);
1684b7654111Sdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
1685d4e70ebdSdrh       VdbeComment((v, "LIMIT counter"));
16863c84ddffSdrh       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
16879b918ed1Sdrh     }
1688a2dc3b1aSdanielk1977     if( p->pOffset ){
16890a07c107Sdrh       p->iOffset = iOffset = ++pParse->nMem;
1690b7654111Sdrh       pParse->nMem++;   /* Allocate an extra register for limit+offset */
1691b7654111Sdrh       sqlite3ExprCode(pParse, p->pOffset, iOffset);
1692b7654111Sdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
1693d4e70ebdSdrh       VdbeComment((v, "OFFSET counter"));
16943c84ddffSdrh       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
1695b7654111Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
169615007a99Sdrh       sqlite3VdbeJumpHere(v, addr1);
1697b7654111Sdrh       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
1698d4e70ebdSdrh       VdbeComment((v, "LIMIT+OFFSET"));
1699b7654111Sdrh       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
1700b7654111Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
1701b7654111Sdrh       sqlite3VdbeJumpHere(v, addr1);
1702b7654111Sdrh     }
1703d59ba6ceSdrh   }
17047b58daeaSdrh }
17057b58daeaSdrh 
1706b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1707fbc4ee7bSdrh /*
1708fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
1709fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
1710fbc4ee7bSdrh ** the column has no default collating sequence.
1711fbc4ee7bSdrh **
1712fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
1713fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
1714fbc4ee7bSdrh */
1715dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1716fbc4ee7bSdrh   CollSeq *pRet;
1717dc1bdc4fSdanielk1977   if( p->pPrior ){
1718dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1719fbc4ee7bSdrh   }else{
1720fbc4ee7bSdrh     pRet = 0;
1721dc1bdc4fSdanielk1977   }
172210c081adSdrh   assert( iCol>=0 );
172310c081adSdrh   if( pRet==0 && iCol<p->pEList->nExpr ){
1724dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1725dc1bdc4fSdanielk1977   }
1726dc1bdc4fSdanielk1977   return pRet;
1727d3d39e93Sdrh }
172853bed45eSdan 
172953bed45eSdan /*
173053bed45eSdan ** The select statement passed as the second parameter is a compound SELECT
173153bed45eSdan ** with an ORDER BY clause. This function allocates and returns a KeyInfo
173253bed45eSdan ** structure suitable for implementing the ORDER BY.
173353bed45eSdan **
173453bed45eSdan ** Space to hold the KeyInfo structure is obtained from malloc. The calling
173553bed45eSdan ** function is responsible for ensuring that this structure is eventually
173653bed45eSdan ** freed.
173753bed45eSdan */
173853bed45eSdan static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
173953bed45eSdan   ExprList *pOrderBy = p->pOrderBy;
174053bed45eSdan   int nOrderBy = p->pOrderBy->nExpr;
174153bed45eSdan   sqlite3 *db = pParse->db;
174253bed45eSdan   KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
174353bed45eSdan   if( pRet ){
174453bed45eSdan     int i;
174553bed45eSdan     for(i=0; i<nOrderBy; i++){
174653bed45eSdan       struct ExprList_item *pItem = &pOrderBy->a[i];
174753bed45eSdan       Expr *pTerm = pItem->pExpr;
174853bed45eSdan       CollSeq *pColl;
174953bed45eSdan 
175053bed45eSdan       if( pTerm->flags & EP_Collate ){
175153bed45eSdan         pColl = sqlite3ExprCollSeq(pParse, pTerm);
175253bed45eSdan       }else{
175353bed45eSdan         pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
175453bed45eSdan         if( pColl==0 ) pColl = db->pDfltColl;
175553bed45eSdan         pOrderBy->a[i].pExpr =
175653bed45eSdan           sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
175753bed45eSdan       }
175853bed45eSdan       assert( sqlite3KeyInfoIsWriteable(pRet) );
175953bed45eSdan       pRet->aColl[i] = pColl;
176053bed45eSdan       pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
176153bed45eSdan     }
176253bed45eSdan   }
176353bed45eSdan 
176453bed45eSdan   return pRet;
176553bed45eSdan }
1766d3d39e93Sdrh 
1767781def29Sdrh #ifndef SQLITE_OMIT_CTE
1768781def29Sdrh /*
1769781def29Sdrh ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
1770781def29Sdrh ** query of the form:
1771781def29Sdrh **
1772781def29Sdrh **   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
1773781def29Sdrh **                         \___________/             \_______________/
1774781def29Sdrh **                           p->pPrior                      p
1775781def29Sdrh **
1776781def29Sdrh **
1777781def29Sdrh ** There is exactly one reference to the recursive-table in the FROM clause
1778781def29Sdrh ** of recursive-query, marked with the SrcList->a[].isRecursive flag.
1779781def29Sdrh **
1780781def29Sdrh ** The setup-query runs once to generate an initial set of rows that go
1781781def29Sdrh ** into a Queue table.  Rows are extracted from the Queue table one by
1782fe1c6bb9Sdrh ** one.  Each row extracted from Queue is output to pDest.  Then the single
1783fe1c6bb9Sdrh ** extracted row (now in the iCurrent table) becomes the content of the
1784fe1c6bb9Sdrh ** recursive-table for a recursive-query run.  The output of the recursive-query
1785781def29Sdrh ** is added back into the Queue table.  Then another row is extracted from Queue
1786781def29Sdrh ** and the iteration continues until the Queue table is empty.
1787781def29Sdrh **
1788781def29Sdrh ** If the compound query operator is UNION then no duplicate rows are ever
1789781def29Sdrh ** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
1790781def29Sdrh ** that have ever been inserted into Queue and causes duplicates to be
1791781def29Sdrh ** discarded.  If the operator is UNION ALL, then duplicates are allowed.
1792781def29Sdrh **
1793781def29Sdrh ** If the query has an ORDER BY, then entries in the Queue table are kept in
1794781def29Sdrh ** ORDER BY order and the first entry is extracted for each cycle.  Without
1795781def29Sdrh ** an ORDER BY, the Queue table is just a FIFO.
1796781def29Sdrh **
1797781def29Sdrh ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
1798781def29Sdrh ** have been output to pDest.  A LIMIT of zero means to output no rows and a
1799781def29Sdrh ** negative LIMIT means to output all rows.  If there is also an OFFSET clause
1800781def29Sdrh ** with a positive value, then the first OFFSET outputs are discarded rather
1801781def29Sdrh ** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
1802781def29Sdrh ** rows have been skipped.
1803781def29Sdrh */
1804781def29Sdrh static void generateWithRecursiveQuery(
1805781def29Sdrh   Parse *pParse,        /* Parsing context */
1806781def29Sdrh   Select *p,            /* The recursive SELECT to be coded */
1807781def29Sdrh   SelectDest *pDest     /* What to do with query results */
1808781def29Sdrh ){
1809781def29Sdrh   SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
1810781def29Sdrh   int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
1811781def29Sdrh   Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
1812781def29Sdrh   Select *pSetup = p->pPrior;   /* The setup query */
1813781def29Sdrh   int addrTop;                  /* Top of the loop */
1814781def29Sdrh   int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
1815edf83d1eSdrh   int iCurrent = 0;             /* The Current table */
1816781def29Sdrh   int regCurrent;               /* Register holding Current table */
1817781def29Sdrh   int iQueue;                   /* The Queue table */
1818781def29Sdrh   int iDistinct = 0;            /* To ensure unique results if UNION */
1819781def29Sdrh   int eDest = SRT_Table;        /* How to write to Queue */
1820781def29Sdrh   SelectDest destQueue;         /* SelectDest targetting the Queue table */
1821781def29Sdrh   int i;                        /* Loop counter */
1822781def29Sdrh   int rc;                       /* Result code */
1823fe1c6bb9Sdrh   ExprList *pOrderBy;           /* The ORDER BY clause */
1824aa9ce707Sdrh   Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
1825aa9ce707Sdrh   int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
1826781def29Sdrh 
1827781def29Sdrh   /* Obtain authorization to do a recursive query */
1828781def29Sdrh   if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
1829781def29Sdrh 
1830aa9ce707Sdrh   /* Process the LIMIT and OFFSET clauses, if they exist */
1831aa9ce707Sdrh   addrBreak = sqlite3VdbeMakeLabel(v);
1832aa9ce707Sdrh   computeLimitRegisters(pParse, p, addrBreak);
1833aa9ce707Sdrh   pLimit = p->pLimit;
1834aa9ce707Sdrh   pOffset = p->pOffset;
1835aa9ce707Sdrh   regLimit = p->iLimit;
1836aa9ce707Sdrh   regOffset = p->iOffset;
1837aa9ce707Sdrh   p->pLimit = p->pOffset = 0;
1838aa9ce707Sdrh   p->iLimit = p->iOffset = 0;
183953bed45eSdan   pOrderBy = p->pOrderBy;
1840781def29Sdrh 
1841781def29Sdrh   /* Locate the cursor number of the Current table */
1842781def29Sdrh   for(i=0; ALWAYS(i<pSrc->nSrc); i++){
1843781def29Sdrh     if( pSrc->a[i].isRecursive ){
1844781def29Sdrh       iCurrent = pSrc->a[i].iCursor;
1845781def29Sdrh       break;
1846781def29Sdrh     }
1847781def29Sdrh   }
1848781def29Sdrh 
1849fe1c6bb9Sdrh   /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
1850781def29Sdrh   ** the Distinct table must be exactly one greater than Queue in order
1851fe1c6bb9Sdrh   ** for the SRT_DistTable and SRT_DistQueue destinations to work. */
1852781def29Sdrh   iQueue = pParse->nTab++;
1853781def29Sdrh   if( p->op==TK_UNION ){
1854fe1c6bb9Sdrh     eDest = pOrderBy ? SRT_DistQueue : SRT_DistTable;
1855781def29Sdrh     iDistinct = pParse->nTab++;
1856fe1c6bb9Sdrh   }else{
1857fe1c6bb9Sdrh     eDest = pOrderBy ? SRT_Queue : SRT_Table;
1858781def29Sdrh   }
1859781def29Sdrh   sqlite3SelectDestInit(&destQueue, eDest, iQueue);
1860781def29Sdrh 
1861781def29Sdrh   /* Allocate cursors for Current, Queue, and Distinct. */
1862781def29Sdrh   regCurrent = ++pParse->nMem;
1863781def29Sdrh   sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
1864fe1c6bb9Sdrh   if( pOrderBy ){
186553bed45eSdan     KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
1866fe1c6bb9Sdrh     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
1867fe1c6bb9Sdrh                       (char*)pKeyInfo, P4_KEYINFO);
1868fe1c6bb9Sdrh     destQueue.pOrderBy = pOrderBy;
1869fe1c6bb9Sdrh   }else{
1870781def29Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
1871fe1c6bb9Sdrh   }
1872fe1c6bb9Sdrh   VdbeComment((v, "Queue table"));
1873781def29Sdrh   if( iDistinct ){
1874781def29Sdrh     p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
1875781def29Sdrh     p->selFlags |= SF_UsesEphemeral;
1876781def29Sdrh   }
1877781def29Sdrh 
187853bed45eSdan   /* Detach the ORDER BY clause from the compound SELECT */
187953bed45eSdan   p->pOrderBy = 0;
188053bed45eSdan 
1881781def29Sdrh   /* Store the results of the setup-query in Queue. */
1882781def29Sdrh   rc = sqlite3Select(pParse, pSetup, &destQueue);
1883fe1c6bb9Sdrh   if( rc ) goto end_of_recursive_query;
1884781def29Sdrh 
1885781def29Sdrh   /* Find the next row in the Queue and output that row */
1886781def29Sdrh   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak);
1887781def29Sdrh 
1888781def29Sdrh   /* Transfer the next row in Queue over to Current */
1889781def29Sdrh   sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
1890fe1c6bb9Sdrh   if( pOrderBy ){
1891fe1c6bb9Sdrh     sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
1892fe1c6bb9Sdrh   }else{
1893781def29Sdrh     sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
1894fe1c6bb9Sdrh   }
1895781def29Sdrh   sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
1896781def29Sdrh 
1897fe1c6bb9Sdrh   /* Output the single row in Current */
1898fe1c6bb9Sdrh   addrCont = sqlite3VdbeMakeLabel(v);
1899aa9ce707Sdrh   codeOffset(v, regOffset, addrCont);
1900fe1c6bb9Sdrh   selectInnerLoop(pParse, p, p->pEList, iCurrent,
1901fe1c6bb9Sdrh       0, 0, pDest, addrCont, addrBreak);
1902aa9ce707Sdrh   if( regLimit ) sqlite3VdbeAddOp3(v, OP_IfZero, regLimit, addrBreak, -1);
1903fe1c6bb9Sdrh   sqlite3VdbeResolveLabel(v, addrCont);
1904fe1c6bb9Sdrh 
1905781def29Sdrh   /* Execute the recursive SELECT taking the single row in Current as
1906781def29Sdrh   ** the value for the recursive-table. Store the results in the Queue.
1907781def29Sdrh   */
1908781def29Sdrh   p->pPrior = 0;
1909781def29Sdrh   sqlite3Select(pParse, p, &destQueue);
1910781def29Sdrh   assert( p->pPrior==0 );
1911781def29Sdrh   p->pPrior = pSetup;
1912781def29Sdrh 
1913781def29Sdrh   /* Keep running the loop until the Queue is empty */
1914781def29Sdrh   sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
1915781def29Sdrh   sqlite3VdbeResolveLabel(v, addrBreak);
1916fe1c6bb9Sdrh 
1917fe1c6bb9Sdrh end_of_recursive_query:
1918fe1c6bb9Sdrh   p->pOrderBy = pOrderBy;
1919aa9ce707Sdrh   p->pLimit = pLimit;
1920aa9ce707Sdrh   p->pOffset = pOffset;
1921fe1c6bb9Sdrh   return;
1922781def29Sdrh }
1923b68b9778Sdan #endif /* SQLITE_OMIT_CTE */
1924781def29Sdrh 
1925781def29Sdrh /* Forward references */
1926b21e7c70Sdrh static int multiSelectOrderBy(
1927b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
1928b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
1929a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
1930b21e7c70Sdrh );
1931b21e7c70Sdrh 
1932b21e7c70Sdrh 
1933d3d39e93Sdrh /*
193416ee60ffSdrh ** This routine is called to process a compound query form from
193516ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
193616ee60ffSdrh ** INTERSECT
1937c926afbcSdrh **
1938e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1939e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1940e78e8284Sdrh ** in which case this routine will be called recursively.
1941e78e8284Sdrh **
1942e78e8284Sdrh ** The results of the total query are to be written into a destination
1943e78e8284Sdrh ** of type eDest with parameter iParm.
1944e78e8284Sdrh **
1945e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1946e78e8284Sdrh **
1947e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1948e78e8284Sdrh **
1949e78e8284Sdrh ** This statement is parsed up as follows:
1950e78e8284Sdrh **
1951e78e8284Sdrh **     SELECT c FROM t3
1952e78e8284Sdrh **      |
1953e78e8284Sdrh **      `----->  SELECT b FROM t2
1954e78e8284Sdrh **                |
19554b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1956e78e8284Sdrh **
1957e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1958e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1959e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1960e78e8284Sdrh **
1961e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1962e78e8284Sdrh ** individual selects always group from left to right.
196382c3d636Sdrh */
196484ac9d02Sdanielk1977 static int multiSelect(
1965fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
1966fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
1967a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
196884ac9d02Sdanielk1977 ){
196984ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
197010e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
197110e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
19721013c932Sdrh   SelectDest dest;      /* Alternative data destination */
1973eca7e01aSdanielk1977   Select *pDelete = 0;  /* Chain of simple selects to delete */
1974633e6d57Sdrh   sqlite3 *db;          /* Database connection */
19757f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN
1976edf83d1eSdrh   int iSub1 = 0;        /* EQP id of left-hand query */
1977edf83d1eSdrh   int iSub2 = 0;        /* EQP id of right-hand query */
19787f61e92cSdan #endif
197982c3d636Sdrh 
19807b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1981fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
198282c3d636Sdrh   */
1983701bb3b4Sdrh   assert( p && p->pPrior );  /* Calling function guarantees this much */
1984eae73fbfSdan   assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
1985633e6d57Sdrh   db = pParse->db;
1986d8bc7086Sdrh   pPrior = p->pPrior;
19870342b1f5Sdrh   assert( pPrior->pRightmost!=pPrior );
19880342b1f5Sdrh   assert( pPrior->pRightmost==p->pRightmost );
1989bc10377aSdrh   dest = *pDest;
1990d8bc7086Sdrh   if( pPrior->pOrderBy ){
19914adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1992da93d238Sdrh       selectOpName(p->op));
199384ac9d02Sdanielk1977     rc = 1;
199484ac9d02Sdanielk1977     goto multi_select_end;
199582c3d636Sdrh   }
1996a2dc3b1aSdanielk1977   if( pPrior->pLimit ){
19974adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
19987b58daeaSdrh       selectOpName(p->op));
199984ac9d02Sdanielk1977     rc = 1;
200084ac9d02Sdanielk1977     goto multi_select_end;
20017b58daeaSdrh   }
200282c3d636Sdrh 
20034adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
2004701bb3b4Sdrh   assert( v!=0 );  /* The VDBE already created by calling function */
2005d8bc7086Sdrh 
20061cc3d75fSdrh   /* Create the destination temporary table if necessary
20071cc3d75fSdrh   */
20086c8c8ce0Sdanielk1977   if( dest.eDest==SRT_EphemTab ){
2009b4964b72Sdanielk1977     assert( p->pEList );
20102b596da8Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
2011d4187c71Sdrh     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
20126c8c8ce0Sdanielk1977     dest.eDest = SRT_Table;
20131cc3d75fSdrh   }
20141cc3d75fSdrh 
2015f6e369a1Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
2016f6e369a1Sdrh   ** in their result sets.
2017f6e369a1Sdrh   */
2018f6e369a1Sdrh   assert( p->pEList && pPrior->pEList );
2019f6e369a1Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
20207b113babSdrh     if( p->selFlags & SF_Values ){
20217b113babSdrh       sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
20227b113babSdrh     }else{
2023f6e369a1Sdrh       sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
2024f6e369a1Sdrh         " do not have the same number of result columns", selectOpName(p->op));
20257b113babSdrh     }
2026f6e369a1Sdrh     rc = 1;
2027f6e369a1Sdrh     goto multi_select_end;
2028f6e369a1Sdrh   }
2029f6e369a1Sdrh 
2030eede6a53Sdan #ifndef SQLITE_OMIT_CTE
2031eae73fbfSdan   if( p->selFlags & SF_Recursive ){
2032781def29Sdrh     generateWithRecursiveQuery(pParse, p, &dest);
20338ce7184bSdan   }else
20348ce7184bSdan #endif
20358ce7184bSdan 
2036a9671a22Sdrh   /* Compound SELECTs that have an ORDER BY clause are handled separately.
2037a9671a22Sdrh   */
2038f6e369a1Sdrh   if( p->pOrderBy ){
2039a9671a22Sdrh     return multiSelectOrderBy(pParse, p, pDest);
2040eede6a53Sdan   }else
2041f6e369a1Sdrh 
2042f46f905aSdrh   /* Generate code for the left and right SELECT statements.
2043d8bc7086Sdrh   */
204482c3d636Sdrh   switch( p->op ){
2045f46f905aSdrh     case TK_ALL: {
2046ec7429aeSdrh       int addr = 0;
204795aa47b1Sdrh       int nLimit;
2048a2dc3b1aSdanielk1977       assert( !pPrior->pLimit );
2049547180baSdrh       pPrior->iLimit = p->iLimit;
2050547180baSdrh       pPrior->iOffset = p->iOffset;
2051a2dc3b1aSdanielk1977       pPrior->pLimit = p->pLimit;
2052a2dc3b1aSdanielk1977       pPrior->pOffset = p->pOffset;
20537f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
20547d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &dest);
2055ad68cb6bSdanielk1977       p->pLimit = 0;
2056ad68cb6bSdanielk1977       p->pOffset = 0;
205784ac9d02Sdanielk1977       if( rc ){
205884ac9d02Sdanielk1977         goto multi_select_end;
205984ac9d02Sdanielk1977       }
2060f46f905aSdrh       p->pPrior = 0;
20617b58daeaSdrh       p->iLimit = pPrior->iLimit;
20627b58daeaSdrh       p->iOffset = pPrior->iOffset;
206392b01d53Sdrh       if( p->iLimit ){
20643c84ddffSdrh         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
2065d4e70ebdSdrh         VdbeComment((v, "Jump ahead if LIMIT reached"));
2066ec7429aeSdrh       }
20677f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
20687d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &dest);
2069373cc2ddSdrh       testcase( rc!=SQLITE_OK );
2070eca7e01aSdanielk1977       pDelete = p->pPrior;
2071f46f905aSdrh       p->pPrior = pPrior;
207295aa47b1Sdrh       p->nSelectRow += pPrior->nSelectRow;
207395aa47b1Sdrh       if( pPrior->pLimit
207495aa47b1Sdrh        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
2075613ba1eaSdrh        && nLimit>0 && p->nSelectRow > (u64)nLimit
207695aa47b1Sdrh       ){
2077c63367efSdrh         p->nSelectRow = nLimit;
207895aa47b1Sdrh       }
2079ec7429aeSdrh       if( addr ){
2080ec7429aeSdrh         sqlite3VdbeJumpHere(v, addr);
2081ec7429aeSdrh       }
2082f46f905aSdrh       break;
2083f46f905aSdrh     }
208482c3d636Sdrh     case TK_EXCEPT:
208582c3d636Sdrh     case TK_UNION: {
2086d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
2087ea678832Sdrh       u8 op = 0;       /* One of the SRT_ operations to apply to self */
2088d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
2089a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
2090dc1bdc4fSdanielk1977       int addr;
20916c8c8ce0Sdanielk1977       SelectDest uniondest;
209282c3d636Sdrh 
2093373cc2ddSdrh       testcase( p->op==TK_EXCEPT );
2094373cc2ddSdrh       testcase( p->op==TK_UNION );
209593a960a0Sdrh       priorOp = SRT_Union;
2096e2f02bacSdrh       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
2097d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
2098c926afbcSdrh         ** right.
2099d8bc7086Sdrh         */
2100e2f02bacSdrh         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
2101e2f02bacSdrh                                      ** of a 3-way or more compound */
2102e2f02bacSdrh         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
2103e2f02bacSdrh         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
21042b596da8Sdrh         unionTab = dest.iSDParm;
210582c3d636Sdrh       }else{
2106d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
2107d8bc7086Sdrh         ** intermediate results.
2108d8bc7086Sdrh         */
210982c3d636Sdrh         unionTab = pParse->nTab++;
211093a960a0Sdrh         assert( p->pOrderBy==0 );
211166a5167bSdrh         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
2112b9bb7c18Sdrh         assert( p->addrOpenEphm[0] == -1 );
2113b9bb7c18Sdrh         p->addrOpenEphm[0] = addr;
21147d10d5a6Sdrh         p->pRightmost->selFlags |= SF_UsesEphemeral;
211584ac9d02Sdanielk1977         assert( p->pEList );
2116d8bc7086Sdrh       }
2117d8bc7086Sdrh 
2118d8bc7086Sdrh       /* Code the SELECT statements to our left
2119d8bc7086Sdrh       */
2120b3bce662Sdanielk1977       assert( !pPrior->pOrderBy );
21211013c932Sdrh       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
21227f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
21237d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &uniondest);
212484ac9d02Sdanielk1977       if( rc ){
212584ac9d02Sdanielk1977         goto multi_select_end;
212684ac9d02Sdanielk1977       }
2127d8bc7086Sdrh 
2128d8bc7086Sdrh       /* Code the current SELECT statement
2129d8bc7086Sdrh       */
21304cfb22f7Sdrh       if( p->op==TK_EXCEPT ){
21314cfb22f7Sdrh         op = SRT_Except;
21324cfb22f7Sdrh       }else{
21334cfb22f7Sdrh         assert( p->op==TK_UNION );
21344cfb22f7Sdrh         op = SRT_Union;
2135d8bc7086Sdrh       }
213682c3d636Sdrh       p->pPrior = 0;
2137a2dc3b1aSdanielk1977       pLimit = p->pLimit;
2138a2dc3b1aSdanielk1977       p->pLimit = 0;
2139a2dc3b1aSdanielk1977       pOffset = p->pOffset;
2140a2dc3b1aSdanielk1977       p->pOffset = 0;
21416c8c8ce0Sdanielk1977       uniondest.eDest = op;
21427f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
21437d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &uniondest);
2144373cc2ddSdrh       testcase( rc!=SQLITE_OK );
21455bd1bf2eSdrh       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
21465bd1bf2eSdrh       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
2147633e6d57Sdrh       sqlite3ExprListDelete(db, p->pOrderBy);
2148eca7e01aSdanielk1977       pDelete = p->pPrior;
214982c3d636Sdrh       p->pPrior = pPrior;
2150a9671a22Sdrh       p->pOrderBy = 0;
215195aa47b1Sdrh       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
2152633e6d57Sdrh       sqlite3ExprDelete(db, p->pLimit);
2153a2dc3b1aSdanielk1977       p->pLimit = pLimit;
2154a2dc3b1aSdanielk1977       p->pOffset = pOffset;
215592b01d53Sdrh       p->iLimit = 0;
215692b01d53Sdrh       p->iOffset = 0;
2157d8bc7086Sdrh 
2158d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
2159d8bc7086Sdrh       ** it is that we currently need.
2160d8bc7086Sdrh       */
21612b596da8Sdrh       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
2162373cc2ddSdrh       if( dest.eDest!=priorOp ){
21636b56344dSdrh         int iCont, iBreak, iStart;
216482c3d636Sdrh         assert( p->pEList );
21657d10d5a6Sdrh         if( dest.eDest==SRT_Output ){
216692378253Sdrh           Select *pFirst = p;
216792378253Sdrh           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
216892378253Sdrh           generateColumnNames(pParse, 0, pFirst->pEList);
216941202ccaSdrh         }
21704adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
21714adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
2172ec7429aeSdrh         computeLimitRegisters(pParse, p, iBreak);
217366a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
21744adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
2175340309fdSdrh         selectInnerLoop(pParse, p, p->pEList, unionTab,
2176e8e4af76Sdrh                         0, 0, &dest, iCont, iBreak);
21774adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
217866a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
21794adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
218066a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
218182c3d636Sdrh       }
218282c3d636Sdrh       break;
218382c3d636Sdrh     }
2184373cc2ddSdrh     default: assert( p->op==TK_INTERSECT ); {
218582c3d636Sdrh       int tab1, tab2;
21866b56344dSdrh       int iCont, iBreak, iStart;
2187a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset;
2188dc1bdc4fSdanielk1977       int addr;
21891013c932Sdrh       SelectDest intersectdest;
21909cbf3425Sdrh       int r1;
219182c3d636Sdrh 
2192d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
21936206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
2194d8bc7086Sdrh       ** by allocating the tables we will need.
2195d8bc7086Sdrh       */
219682c3d636Sdrh       tab1 = pParse->nTab++;
219782c3d636Sdrh       tab2 = pParse->nTab++;
219893a960a0Sdrh       assert( p->pOrderBy==0 );
2199dc1bdc4fSdanielk1977 
220066a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
2201b9bb7c18Sdrh       assert( p->addrOpenEphm[0] == -1 );
2202b9bb7c18Sdrh       p->addrOpenEphm[0] = addr;
22037d10d5a6Sdrh       p->pRightmost->selFlags |= SF_UsesEphemeral;
220484ac9d02Sdanielk1977       assert( p->pEList );
2205d8bc7086Sdrh 
2206d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
2207d8bc7086Sdrh       */
22081013c932Sdrh       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
22097f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
22107d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &intersectdest);
221184ac9d02Sdanielk1977       if( rc ){
221284ac9d02Sdanielk1977         goto multi_select_end;
221384ac9d02Sdanielk1977       }
2214d8bc7086Sdrh 
2215d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
2216d8bc7086Sdrh       */
221766a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
2218b9bb7c18Sdrh       assert( p->addrOpenEphm[1] == -1 );
2219b9bb7c18Sdrh       p->addrOpenEphm[1] = addr;
222082c3d636Sdrh       p->pPrior = 0;
2221a2dc3b1aSdanielk1977       pLimit = p->pLimit;
2222a2dc3b1aSdanielk1977       p->pLimit = 0;
2223a2dc3b1aSdanielk1977       pOffset = p->pOffset;
2224a2dc3b1aSdanielk1977       p->pOffset = 0;
22252b596da8Sdrh       intersectdest.iSDParm = tab2;
22267f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
22277d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &intersectdest);
2228373cc2ddSdrh       testcase( rc!=SQLITE_OK );
2229eca7e01aSdanielk1977       pDelete = p->pPrior;
223082c3d636Sdrh       p->pPrior = pPrior;
223195aa47b1Sdrh       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
2232633e6d57Sdrh       sqlite3ExprDelete(db, p->pLimit);
2233a2dc3b1aSdanielk1977       p->pLimit = pLimit;
2234a2dc3b1aSdanielk1977       p->pOffset = pOffset;
2235d8bc7086Sdrh 
2236d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
2237d8bc7086Sdrh       ** tables.
2238d8bc7086Sdrh       */
223982c3d636Sdrh       assert( p->pEList );
22407d10d5a6Sdrh       if( dest.eDest==SRT_Output ){
224192378253Sdrh         Select *pFirst = p;
224292378253Sdrh         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
224392378253Sdrh         generateColumnNames(pParse, 0, pFirst->pEList);
224441202ccaSdrh       }
22454adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
22464adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
2247ec7429aeSdrh       computeLimitRegisters(pParse, p, iBreak);
224866a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
22499cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
22509cbf3425Sdrh       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
22518cff69dfSdrh       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
22529cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
2253340309fdSdrh       selectInnerLoop(pParse, p, p->pEList, tab1,
2254e8e4af76Sdrh                       0, 0, &dest, iCont, iBreak);
22554adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
225666a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
22574adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
225866a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
225966a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
226082c3d636Sdrh       break;
226182c3d636Sdrh     }
226282c3d636Sdrh   }
22638cdbf836Sdrh 
22647f61e92cSdan   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
22657f61e92cSdan 
2266a9671a22Sdrh   /* Compute collating sequences used by
2267a9671a22Sdrh   ** temporary tables needed to implement the compound select.
2268a9671a22Sdrh   ** Attach the KeyInfo structure to all temporary tables.
22698cdbf836Sdrh   **
22708cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
22718cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
22728cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
22738cdbf836Sdrh   ** no temp tables are required.
2274fbc4ee7bSdrh   */
22757d10d5a6Sdrh   if( p->selFlags & SF_UsesEphemeral ){
2276fbc4ee7bSdrh     int i;                        /* Loop counter */
2277fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
22780342b1f5Sdrh     Select *pLoop;                /* For looping through SELECT statements */
2279f68d7d17Sdrh     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
228093a960a0Sdrh     int nCol;                     /* Number of columns in result set */
2281fbc4ee7bSdrh 
22820342b1f5Sdrh     assert( p->pRightmost==p );
228393a960a0Sdrh     nCol = p->pEList->nExpr;
2284ad124329Sdrh     pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
2285dc1bdc4fSdanielk1977     if( !pKeyInfo ){
2286dc1bdc4fSdanielk1977       rc = SQLITE_NOMEM;
2287dc1bdc4fSdanielk1977       goto multi_select_end;
2288dc1bdc4fSdanielk1977     }
22890342b1f5Sdrh     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
22900342b1f5Sdrh       *apColl = multiSelectCollSeq(pParse, p, i);
22910342b1f5Sdrh       if( 0==*apColl ){
2292633e6d57Sdrh         *apColl = db->pDfltColl;
2293dc1bdc4fSdanielk1977       }
2294dc1bdc4fSdanielk1977     }
2295dc1bdc4fSdanielk1977 
22960342b1f5Sdrh     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
22970342b1f5Sdrh       for(i=0; i<2; i++){
2298b9bb7c18Sdrh         int addr = pLoop->addrOpenEphm[i];
22990342b1f5Sdrh         if( addr<0 ){
23000342b1f5Sdrh           /* If [0] is unused then [1] is also unused.  So we can
23010342b1f5Sdrh           ** always safely abort as soon as the first unused slot is found */
2302b9bb7c18Sdrh           assert( pLoop->addrOpenEphm[1]<0 );
23030342b1f5Sdrh           break;
23040342b1f5Sdrh         }
23050342b1f5Sdrh         sqlite3VdbeChangeP2(v, addr, nCol);
23062ec2fb22Sdrh         sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
23072ec2fb22Sdrh                             P4_KEYINFO);
23080ee5a1e7Sdrh         pLoop->addrOpenEphm[i] = -1;
23090342b1f5Sdrh       }
2310dc1bdc4fSdanielk1977     }
23112ec2fb22Sdrh     sqlite3KeyInfoUnref(pKeyInfo);
2312dc1bdc4fSdanielk1977   }
2313dc1bdc4fSdanielk1977 
2314dc1bdc4fSdanielk1977 multi_select_end:
23152b596da8Sdrh   pDest->iSdst = dest.iSdst;
23162b596da8Sdrh   pDest->nSdst = dest.nSdst;
2317633e6d57Sdrh   sqlite3SelectDelete(db, pDelete);
231884ac9d02Sdanielk1977   return rc;
23192282792aSdrh }
2320b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
23212282792aSdrh 
2322b21e7c70Sdrh /*
2323b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a
2324b21e7c70Sdrh ** SELECT statment.
23250acb7e48Sdrh **
23262b596da8Sdrh ** The data to be output is contained in pIn->iSdst.  There are
23272b596da8Sdrh ** pIn->nSdst columns to be output.  pDest is where the output should
23280acb7e48Sdrh ** be sent.
23290acb7e48Sdrh **
23300acb7e48Sdrh ** regReturn is the number of the register holding the subroutine
23310acb7e48Sdrh ** return address.
23320acb7e48Sdrh **
2333f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that
23340acb7e48Sdrh ** records the previous output.  mem[regPrev] is a flag that is false
23350acb7e48Sdrh ** if there has been no previous output.  If regPrev>0 then code is
23360acb7e48Sdrh ** generated to suppress duplicates.  pKeyInfo is used for comparing
23370acb7e48Sdrh ** keys.
23380acb7e48Sdrh **
23390acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to
23400acb7e48Sdrh ** iBreak.
2341b21e7c70Sdrh */
23420acb7e48Sdrh static int generateOutputSubroutine(
234392b01d53Sdrh   Parse *pParse,          /* Parsing context */
234492b01d53Sdrh   Select *p,              /* The SELECT statement */
234592b01d53Sdrh   SelectDest *pIn,        /* Coroutine supplying data */
234692b01d53Sdrh   SelectDest *pDest,      /* Where to send the data */
234792b01d53Sdrh   int regReturn,          /* The return address register */
23480acb7e48Sdrh   int regPrev,            /* Previous result register.  No uniqueness if 0 */
23490acb7e48Sdrh   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
235092b01d53Sdrh   int iBreak              /* Jump here if we hit the LIMIT */
2351b21e7c70Sdrh ){
2352b21e7c70Sdrh   Vdbe *v = pParse->pVdbe;
235392b01d53Sdrh   int iContinue;
235492b01d53Sdrh   int addr;
2355b21e7c70Sdrh 
235692b01d53Sdrh   addr = sqlite3VdbeCurrentAddr(v);
235792b01d53Sdrh   iContinue = sqlite3VdbeMakeLabel(v);
23580acb7e48Sdrh 
23590acb7e48Sdrh   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
23600acb7e48Sdrh   */
23610acb7e48Sdrh   if( regPrev ){
23620acb7e48Sdrh     int j1, j2;
2363ec86c724Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
23642b596da8Sdrh     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
23652ec2fb22Sdrh                               (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
23660acb7e48Sdrh     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
23670acb7e48Sdrh     sqlite3VdbeJumpHere(v, j1);
2368e8e4af76Sdrh     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
2369ec86c724Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
23700acb7e48Sdrh   }
23711f9caa41Sdanielk1977   if( pParse->db->mallocFailed ) return 0;
23720acb7e48Sdrh 
2373d5578433Smistachkin   /* Suppress the first OFFSET entries if there is an OFFSET clause
23740acb7e48Sdrh   */
2375aa9ce707Sdrh   codeOffset(v, p->iOffset, iContinue);
2376b21e7c70Sdrh 
2377b21e7c70Sdrh   switch( pDest->eDest ){
2378b21e7c70Sdrh     /* Store the result as data using a unique key.
2379b21e7c70Sdrh     */
2380b21e7c70Sdrh     case SRT_Table:
2381b21e7c70Sdrh     case SRT_EphemTab: {
2382b21e7c70Sdrh       int r1 = sqlite3GetTempReg(pParse);
2383b21e7c70Sdrh       int r2 = sqlite3GetTempReg(pParse);
2384373cc2ddSdrh       testcase( pDest->eDest==SRT_Table );
2385373cc2ddSdrh       testcase( pDest->eDest==SRT_EphemTab );
23862b596da8Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
23872b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
23882b596da8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
2389b21e7c70Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
2390b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r2);
2391b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
2392b21e7c70Sdrh       break;
2393b21e7c70Sdrh     }
2394b21e7c70Sdrh 
2395b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY
2396b21e7c70Sdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
2397b21e7c70Sdrh     ** then there should be a single item on the stack.  Write this
2398b21e7c70Sdrh     ** item into the set table with bogus data.
2399b21e7c70Sdrh     */
2400b21e7c70Sdrh     case SRT_Set: {
24016fccc35aSdrh       int r1;
24022b596da8Sdrh       assert( pIn->nSdst==1 );
2403634d81deSdrh       pDest->affSdst =
24042b596da8Sdrh          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
2405b21e7c70Sdrh       r1 = sqlite3GetTempReg(pParse);
2406634d81deSdrh       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
24072b596da8Sdrh       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
24082b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
2409b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
2410b21e7c70Sdrh       break;
2411b21e7c70Sdrh     }
2412b21e7c70Sdrh 
241385e9e22bSdrh #if 0  /* Never occurs on an ORDER BY query */
2414b21e7c70Sdrh     /* If any row exist in the result set, record that fact and abort.
2415b21e7c70Sdrh     */
2416b21e7c70Sdrh     case SRT_Exists: {
24172b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
2418b21e7c70Sdrh       /* The LIMIT clause will terminate the loop for us */
2419b21e7c70Sdrh       break;
2420b21e7c70Sdrh     }
242185e9e22bSdrh #endif
2422b21e7c70Sdrh 
2423b21e7c70Sdrh     /* If this is a scalar select that is part of an expression, then
2424b21e7c70Sdrh     ** store the results in the appropriate memory cell and break out
2425b21e7c70Sdrh     ** of the scan loop.
2426b21e7c70Sdrh     */
2427b21e7c70Sdrh     case SRT_Mem: {
24282b596da8Sdrh       assert( pIn->nSdst==1 );
24292b596da8Sdrh       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
2430b21e7c70Sdrh       /* The LIMIT clause will jump out of the loop for us */
2431b21e7c70Sdrh       break;
2432b21e7c70Sdrh     }
2433b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
2434b21e7c70Sdrh 
24357d10d5a6Sdrh     /* The results are stored in a sequence of registers
24362b596da8Sdrh     ** starting at pDest->iSdst.  Then the co-routine yields.
2437b21e7c70Sdrh     */
243892b01d53Sdrh     case SRT_Coroutine: {
24392b596da8Sdrh       if( pDest->iSdst==0 ){
24402b596da8Sdrh         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
24412b596da8Sdrh         pDest->nSdst = pIn->nSdst;
2442b21e7c70Sdrh       }
24432b596da8Sdrh       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
24442b596da8Sdrh       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
244592b01d53Sdrh       break;
244692b01d53Sdrh     }
244792b01d53Sdrh 
2448ccfcbceaSdrh     /* If none of the above, then the result destination must be
2449ccfcbceaSdrh     ** SRT_Output.  This routine is never called with any other
2450ccfcbceaSdrh     ** destination other than the ones handled above or SRT_Output.
2451ccfcbceaSdrh     **
2452ccfcbceaSdrh     ** For SRT_Output, results are stored in a sequence of registers.
2453ccfcbceaSdrh     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
2454ccfcbceaSdrh     ** return the next row of result.
24557d10d5a6Sdrh     */
2456ccfcbceaSdrh     default: {
2457ccfcbceaSdrh       assert( pDest->eDest==SRT_Output );
24582b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
24592b596da8Sdrh       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
2460b21e7c70Sdrh       break;
2461b21e7c70Sdrh     }
2462b21e7c70Sdrh   }
246392b01d53Sdrh 
246492b01d53Sdrh   /* Jump to the end of the loop if the LIMIT is reached.
246592b01d53Sdrh   */
246692b01d53Sdrh   if( p->iLimit ){
24679b918ed1Sdrh     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
246892b01d53Sdrh   }
246992b01d53Sdrh 
247092b01d53Sdrh   /* Generate the subroutine return
247192b01d53Sdrh   */
24720acb7e48Sdrh   sqlite3VdbeResolveLabel(v, iContinue);
247392b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
247492b01d53Sdrh 
247592b01d53Sdrh   return addr;
2476b21e7c70Sdrh }
2477b21e7c70Sdrh 
2478b21e7c70Sdrh /*
2479b21e7c70Sdrh ** Alternative compound select code generator for cases when there
2480b21e7c70Sdrh ** is an ORDER BY clause.
2481b21e7c70Sdrh **
2482b21e7c70Sdrh ** We assume a query of the following form:
2483b21e7c70Sdrh **
2484b21e7c70Sdrh **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
2485b21e7c70Sdrh **
2486b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
2487b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as
2488b21e7c70Sdrh ** co-routines.  Then run the co-routines in parallel and merge the results
2489b21e7c70Sdrh ** into the output.  In addition to the two coroutines (called selectA and
2490b21e7c70Sdrh ** selectB) there are 7 subroutines:
2491b21e7c70Sdrh **
2492b21e7c70Sdrh **    outA:    Move the output of the selectA coroutine into the output
2493b21e7c70Sdrh **             of the compound query.
2494b21e7c70Sdrh **
2495b21e7c70Sdrh **    outB:    Move the output of the selectB coroutine into the output
2496b21e7c70Sdrh **             of the compound query.  (Only generated for UNION and
2497b21e7c70Sdrh **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
2498b21e7c70Sdrh **             appears only in B.)
2499b21e7c70Sdrh **
2500b21e7c70Sdrh **    AltB:    Called when there is data from both coroutines and A<B.
2501b21e7c70Sdrh **
2502b21e7c70Sdrh **    AeqB:    Called when there is data from both coroutines and A==B.
2503b21e7c70Sdrh **
2504b21e7c70Sdrh **    AgtB:    Called when there is data from both coroutines and A>B.
2505b21e7c70Sdrh **
2506b21e7c70Sdrh **    EofA:    Called when data is exhausted from selectA.
2507b21e7c70Sdrh **
2508b21e7c70Sdrh **    EofB:    Called when data is exhausted from selectB.
2509b21e7c70Sdrh **
2510b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which
2511b21e7c70Sdrh ** <operator> is used:
2512b21e7c70Sdrh **
2513b21e7c70Sdrh **
2514b21e7c70Sdrh **             UNION ALL         UNION            EXCEPT          INTERSECT
2515b21e7c70Sdrh **          -------------  -----------------  --------------  -----------------
2516b21e7c70Sdrh **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
2517b21e7c70Sdrh **
25180acb7e48Sdrh **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
2519b21e7c70Sdrh **
2520b21e7c70Sdrh **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
2521b21e7c70Sdrh **
25220acb7e48Sdrh **   EofA:   outB, nextB      outB, nextB          halt             halt
2523b21e7c70Sdrh **
25240acb7e48Sdrh **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
25250acb7e48Sdrh **
25260acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
25270acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes
25280acb7e48Sdrh ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
25290acb7e48Sdrh ** following nextX causes a jump to the end of the select processing.
25300acb7e48Sdrh **
25310acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
25320acb7e48Sdrh ** within the output subroutine.  The regPrev register set holds the previously
25330acb7e48Sdrh ** output value.  A comparison is made against this value and the output
25340acb7e48Sdrh ** is skipped if the next results would be the same as the previous.
2535b21e7c70Sdrh **
2536b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven
2537b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom.  Like this:
2538b21e7c70Sdrh **
2539b21e7c70Sdrh **          goto Init
2540b21e7c70Sdrh **     coA: coroutine for left query (A)
2541b21e7c70Sdrh **     coB: coroutine for right query (B)
2542b21e7c70Sdrh **    outA: output one row of A
2543b21e7c70Sdrh **    outB: output one row of B (UNION and UNION ALL only)
2544b21e7c70Sdrh **    EofA: ...
2545b21e7c70Sdrh **    EofB: ...
2546b21e7c70Sdrh **    AltB: ...
2547b21e7c70Sdrh **    AeqB: ...
2548b21e7c70Sdrh **    AgtB: ...
2549b21e7c70Sdrh **    Init: initialize coroutine registers
2550b21e7c70Sdrh **          yield coA
2551b21e7c70Sdrh **          if eof(A) goto EofA
2552b21e7c70Sdrh **          yield coB
2553b21e7c70Sdrh **          if eof(B) goto EofB
2554b21e7c70Sdrh **    Cmpr: Compare A, B
2555b21e7c70Sdrh **          Jump AltB, AeqB, AgtB
2556b21e7c70Sdrh **     End: ...
2557b21e7c70Sdrh **
2558b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
2559b21e7c70Sdrh ** actually called using Gosub and they do not Return.  EofA and EofB loop
2560b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
2561b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB.
2562b21e7c70Sdrh */
2563de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
2564b21e7c70Sdrh static int multiSelectOrderBy(
2565b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
2566b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
2567a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
2568b21e7c70Sdrh ){
25690acb7e48Sdrh   int i, j;             /* Loop counters */
2570b21e7c70Sdrh   Select *pPrior;       /* Another SELECT immediately to our left */
2571b21e7c70Sdrh   Vdbe *v;              /* Generate code to this VDBE */
2572b21e7c70Sdrh   SelectDest destA;     /* Destination for coroutine A */
2573b21e7c70Sdrh   SelectDest destB;     /* Destination for coroutine B */
257492b01d53Sdrh   int regAddrA;         /* Address register for select-A coroutine */
257592b01d53Sdrh   int regEofA;          /* Flag to indicate when select-A is complete */
257692b01d53Sdrh   int regAddrB;         /* Address register for select-B coroutine */
257792b01d53Sdrh   int regEofB;          /* Flag to indicate when select-B is complete */
257892b01d53Sdrh   int addrSelectA;      /* Address of the select-A coroutine */
257992b01d53Sdrh   int addrSelectB;      /* Address of the select-B coroutine */
258092b01d53Sdrh   int regOutA;          /* Address register for the output-A subroutine */
258192b01d53Sdrh   int regOutB;          /* Address register for the output-B subroutine */
258292b01d53Sdrh   int addrOutA;         /* Address of the output-A subroutine */
2583b27b7f5dSdrh   int addrOutB = 0;     /* Address of the output-B subroutine */
258492b01d53Sdrh   int addrEofA;         /* Address of the select-A-exhausted subroutine */
258592b01d53Sdrh   int addrEofB;         /* Address of the select-B-exhausted subroutine */
258692b01d53Sdrh   int addrAltB;         /* Address of the A<B subroutine */
258792b01d53Sdrh   int addrAeqB;         /* Address of the A==B subroutine */
258892b01d53Sdrh   int addrAgtB;         /* Address of the A>B subroutine */
258992b01d53Sdrh   int regLimitA;        /* Limit register for select-A */
259092b01d53Sdrh   int regLimitB;        /* Limit register for select-A */
25910acb7e48Sdrh   int regPrev;          /* A range of registers to hold previous output */
259292b01d53Sdrh   int savedLimit;       /* Saved value of p->iLimit */
259392b01d53Sdrh   int savedOffset;      /* Saved value of p->iOffset */
259492b01d53Sdrh   int labelCmpr;        /* Label for the start of the merge algorithm */
259592b01d53Sdrh   int labelEnd;         /* Label for the end of the overall SELECT stmt */
25960acb7e48Sdrh   int j1;               /* Jump instructions that get retargetted */
259792b01d53Sdrh   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
259896067816Sdrh   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
25990acb7e48Sdrh   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
26000acb7e48Sdrh   sqlite3 *db;          /* Database connection */
26010acb7e48Sdrh   ExprList *pOrderBy;   /* The ORDER BY clause */
26020acb7e48Sdrh   int nOrderBy;         /* Number of terms in the ORDER BY clause */
26030acb7e48Sdrh   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
26047f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN
26057f61e92cSdan   int iSub1;            /* EQP id of left-hand query */
26067f61e92cSdan   int iSub2;            /* EQP id of right-hand query */
26077f61e92cSdan #endif
2608b21e7c70Sdrh 
260992b01d53Sdrh   assert( p->pOrderBy!=0 );
261096067816Sdrh   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
26110acb7e48Sdrh   db = pParse->db;
261292b01d53Sdrh   v = pParse->pVdbe;
2613ccfcbceaSdrh   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
261492b01d53Sdrh   labelEnd = sqlite3VdbeMakeLabel(v);
261592b01d53Sdrh   labelCmpr = sqlite3VdbeMakeLabel(v);
26160acb7e48Sdrh 
2617b21e7c70Sdrh 
261892b01d53Sdrh   /* Patch up the ORDER BY clause
261992b01d53Sdrh   */
262092b01d53Sdrh   op = p->op;
2621b21e7c70Sdrh   pPrior = p->pPrior;
262292b01d53Sdrh   assert( pPrior->pOrderBy==0 );
26230acb7e48Sdrh   pOrderBy = p->pOrderBy;
262493a960a0Sdrh   assert( pOrderBy );
26250acb7e48Sdrh   nOrderBy = pOrderBy->nExpr;
262693a960a0Sdrh 
26270acb7e48Sdrh   /* For operators other than UNION ALL we have to make sure that
26280acb7e48Sdrh   ** the ORDER BY clause covers every term of the result set.  Add
26290acb7e48Sdrh   ** terms to the ORDER BY clause as necessary.
26300acb7e48Sdrh   */
26310acb7e48Sdrh   if( op!=TK_ALL ){
26320acb7e48Sdrh     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
26337d10d5a6Sdrh       struct ExprList_item *pItem;
26347d10d5a6Sdrh       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
2635c2acc4e4Sdrh         assert( pItem->u.x.iOrderByCol>0 );
2636c2acc4e4Sdrh         if( pItem->u.x.iOrderByCol==i ) break;
26370acb7e48Sdrh       }
26380acb7e48Sdrh       if( j==nOrderBy ){
2639b7916a78Sdrh         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
26400acb7e48Sdrh         if( pNew==0 ) return SQLITE_NOMEM;
26410acb7e48Sdrh         pNew->flags |= EP_IntValue;
264233e619fcSdrh         pNew->u.iValue = i;
2643b7916a78Sdrh         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
2644c2acc4e4Sdrh         if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
26450acb7e48Sdrh       }
26460acb7e48Sdrh     }
26470acb7e48Sdrh   }
26480acb7e48Sdrh 
26490acb7e48Sdrh   /* Compute the comparison permutation and keyinfo that is used with
265010c081adSdrh   ** the permutation used to determine if the next
26510acb7e48Sdrh   ** row of results comes from selectA or selectB.  Also add explicit
26520acb7e48Sdrh   ** collations to the ORDER BY clause terms so that when the subqueries
26530acb7e48Sdrh   ** to the right and the left are evaluated, they use the correct
26540acb7e48Sdrh   ** collation.
26550acb7e48Sdrh   */
26560acb7e48Sdrh   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
26570acb7e48Sdrh   if( aPermute ){
26587d10d5a6Sdrh     struct ExprList_item *pItem;
26597d10d5a6Sdrh     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
2660c2acc4e4Sdrh       assert( pItem->u.x.iOrderByCol>0
2661c2acc4e4Sdrh           && pItem->u.x.iOrderByCol<=p->pEList->nExpr );
2662c2acc4e4Sdrh       aPermute[i] = pItem->u.x.iOrderByCol - 1;
26630acb7e48Sdrh     }
266453bed45eSdan     pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
26650acb7e48Sdrh   }else{
26660acb7e48Sdrh     pKeyMerge = 0;
26670acb7e48Sdrh   }
26680acb7e48Sdrh 
26690acb7e48Sdrh   /* Reattach the ORDER BY clause to the query.
26700acb7e48Sdrh   */
26710acb7e48Sdrh   p->pOrderBy = pOrderBy;
26726ab3a2ecSdanielk1977   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
26730acb7e48Sdrh 
26740acb7e48Sdrh   /* Allocate a range of temporary registers and the KeyInfo needed
26750acb7e48Sdrh   ** for the logic that removes duplicate result rows when the
26760acb7e48Sdrh   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
26770acb7e48Sdrh   */
26780acb7e48Sdrh   if( op==TK_ALL ){
26790acb7e48Sdrh     regPrev = 0;
26800acb7e48Sdrh   }else{
26810acb7e48Sdrh     int nExpr = p->pEList->nExpr;
26821c0dc825Sdrh     assert( nOrderBy>=nExpr || db->mallocFailed );
2683c8ac0d16Sdrh     regPrev = pParse->nMem+1;
2684c8ac0d16Sdrh     pParse->nMem += nExpr+1;
26850acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
2686ad124329Sdrh     pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
26870acb7e48Sdrh     if( pKeyDup ){
26882ec2fb22Sdrh       assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
26890acb7e48Sdrh       for(i=0; i<nExpr; i++){
26900acb7e48Sdrh         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
26910acb7e48Sdrh         pKeyDup->aSortOrder[i] = 0;
26920acb7e48Sdrh       }
26930acb7e48Sdrh     }
26940acb7e48Sdrh   }
269592b01d53Sdrh 
269692b01d53Sdrh   /* Separate the left and the right query from one another
269792b01d53Sdrh   */
269892b01d53Sdrh   p->pPrior = 0;
26997d10d5a6Sdrh   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
27000acb7e48Sdrh   if( pPrior->pPrior==0 ){
27017d10d5a6Sdrh     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
27020acb7e48Sdrh   }
270392b01d53Sdrh 
270492b01d53Sdrh   /* Compute the limit registers */
270592b01d53Sdrh   computeLimitRegisters(pParse, p, labelEnd);
27060acb7e48Sdrh   if( p->iLimit && op==TK_ALL ){
270792b01d53Sdrh     regLimitA = ++pParse->nMem;
270892b01d53Sdrh     regLimitB = ++pParse->nMem;
270992b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
271092b01d53Sdrh                                   regLimitA);
271192b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
271292b01d53Sdrh   }else{
271392b01d53Sdrh     regLimitA = regLimitB = 0;
271492b01d53Sdrh   }
2715633e6d57Sdrh   sqlite3ExprDelete(db, p->pLimit);
27160acb7e48Sdrh   p->pLimit = 0;
2717633e6d57Sdrh   sqlite3ExprDelete(db, p->pOffset);
27180acb7e48Sdrh   p->pOffset = 0;
271992b01d53Sdrh 
2720b21e7c70Sdrh   regAddrA = ++pParse->nMem;
2721b21e7c70Sdrh   regEofA = ++pParse->nMem;
2722b21e7c70Sdrh   regAddrB = ++pParse->nMem;
2723b21e7c70Sdrh   regEofB = ++pParse->nMem;
2724b21e7c70Sdrh   regOutA = ++pParse->nMem;
2725b21e7c70Sdrh   regOutB = ++pParse->nMem;
2726b21e7c70Sdrh   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
2727b21e7c70Sdrh   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
2728b21e7c70Sdrh 
272992b01d53Sdrh   /* Jump past the various subroutines and coroutines to the main
273092b01d53Sdrh   ** merge loop
273192b01d53Sdrh   */
2732b21e7c70Sdrh   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
2733b21e7c70Sdrh   addrSelectA = sqlite3VdbeCurrentAddr(v);
273492b01d53Sdrh 
27350acb7e48Sdrh 
273692b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement to the
27370acb7e48Sdrh   ** left of the compound operator - the "A" select.
27380acb7e48Sdrh   */
2739b21e7c70Sdrh   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
274092b01d53Sdrh   pPrior->iLimit = regLimitA;
27417f61e92cSdan   explainSetInteger(iSub1, pParse->iNextSelectId);
27427d10d5a6Sdrh   sqlite3Select(pParse, pPrior, &destA);
2743b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
274492b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2745b21e7c70Sdrh   VdbeNoopComment((v, "End coroutine for left SELECT"));
2746b21e7c70Sdrh 
274792b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement on
274892b01d53Sdrh   ** the right - the "B" select
274992b01d53Sdrh   */
2750b21e7c70Sdrh   addrSelectB = sqlite3VdbeCurrentAddr(v);
2751b21e7c70Sdrh   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
275292b01d53Sdrh   savedLimit = p->iLimit;
275392b01d53Sdrh   savedOffset = p->iOffset;
275492b01d53Sdrh   p->iLimit = regLimitB;
275592b01d53Sdrh   p->iOffset = 0;
27567f61e92cSdan   explainSetInteger(iSub2, pParse->iNextSelectId);
27577d10d5a6Sdrh   sqlite3Select(pParse, p, &destB);
275892b01d53Sdrh   p->iLimit = savedLimit;
275992b01d53Sdrh   p->iOffset = savedOffset;
2760b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
276192b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
2762b21e7c70Sdrh   VdbeNoopComment((v, "End coroutine for right SELECT"));
2763b21e7c70Sdrh 
276492b01d53Sdrh   /* Generate a subroutine that outputs the current row of the A
27650acb7e48Sdrh   ** select as the next output row of the compound select.
276692b01d53Sdrh   */
2767b21e7c70Sdrh   VdbeNoopComment((v, "Output routine for A"));
27680acb7e48Sdrh   addrOutA = generateOutputSubroutine(pParse,
27690acb7e48Sdrh                  p, &destA, pDest, regOutA,
27702ec2fb22Sdrh                  regPrev, pKeyDup, labelEnd);
2771b21e7c70Sdrh 
277292b01d53Sdrh   /* Generate a subroutine that outputs the current row of the B
27730acb7e48Sdrh   ** select as the next output row of the compound select.
277492b01d53Sdrh   */
27750acb7e48Sdrh   if( op==TK_ALL || op==TK_UNION ){
2776b21e7c70Sdrh     VdbeNoopComment((v, "Output routine for B"));
27770acb7e48Sdrh     addrOutB = generateOutputSubroutine(pParse,
27780acb7e48Sdrh                  p, &destB, pDest, regOutB,
27792ec2fb22Sdrh                  regPrev, pKeyDup, labelEnd);
27800acb7e48Sdrh   }
27812ec2fb22Sdrh   sqlite3KeyInfoUnref(pKeyDup);
2782b21e7c70Sdrh 
278392b01d53Sdrh   /* Generate a subroutine to run when the results from select A
278492b01d53Sdrh   ** are exhausted and only data in select B remains.
278592b01d53Sdrh   */
278692b01d53Sdrh   VdbeNoopComment((v, "eof-A subroutine"));
278792b01d53Sdrh   if( op==TK_EXCEPT || op==TK_INTERSECT ){
27880acb7e48Sdrh     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
278992b01d53Sdrh   }else{
27900acb7e48Sdrh     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
2791b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
279292b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
27930acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
279495aa47b1Sdrh     p->nSelectRow += pPrior->nSelectRow;
2795b21e7c70Sdrh   }
2796b21e7c70Sdrh 
279792b01d53Sdrh   /* Generate a subroutine to run when the results from select B
279892b01d53Sdrh   ** are exhausted and only data in select A remains.
279992b01d53Sdrh   */
2800b21e7c70Sdrh   if( op==TK_INTERSECT ){
280192b01d53Sdrh     addrEofB = addrEofA;
280295aa47b1Sdrh     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
2803b21e7c70Sdrh   }else{
280492b01d53Sdrh     VdbeNoopComment((v, "eof-B subroutine"));
28050acb7e48Sdrh     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
2806b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
280792b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
28080acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
2809b21e7c70Sdrh   }
2810b21e7c70Sdrh 
281192b01d53Sdrh   /* Generate code to handle the case of A<B
281292b01d53Sdrh   */
2813b21e7c70Sdrh   VdbeNoopComment((v, "A-lt-B subroutine"));
28140acb7e48Sdrh   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
281592b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2816b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
281792b01d53Sdrh   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2818b21e7c70Sdrh 
281992b01d53Sdrh   /* Generate code to handle the case of A==B
282092b01d53Sdrh   */
2821b21e7c70Sdrh   if( op==TK_ALL ){
2822b21e7c70Sdrh     addrAeqB = addrAltB;
28230acb7e48Sdrh   }else if( op==TK_INTERSECT ){
28240acb7e48Sdrh     addrAeqB = addrAltB;
28250acb7e48Sdrh     addrAltB++;
282692b01d53Sdrh   }else{
2827b21e7c70Sdrh     VdbeNoopComment((v, "A-eq-B subroutine"));
28280acb7e48Sdrh     addrAeqB =
282992b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
283092b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
283192b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
283292b01d53Sdrh   }
2833b21e7c70Sdrh 
283492b01d53Sdrh   /* Generate code to handle the case of A>B
283592b01d53Sdrh   */
2836b21e7c70Sdrh   VdbeNoopComment((v, "A-gt-B subroutine"));
2837b21e7c70Sdrh   addrAgtB = sqlite3VdbeCurrentAddr(v);
2838b21e7c70Sdrh   if( op==TK_ALL || op==TK_UNION ){
2839b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
284092b01d53Sdrh   }
28410acb7e48Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
2842b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
284392b01d53Sdrh   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2844b21e7c70Sdrh 
284592b01d53Sdrh   /* This code runs once to initialize everything.
284692b01d53Sdrh   */
2847b21e7c70Sdrh   sqlite3VdbeJumpHere(v, j1);
2848b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
2849b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
285092b01d53Sdrh   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
28510acb7e48Sdrh   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
2852b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
2853b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
285492b01d53Sdrh 
285592b01d53Sdrh   /* Implement the main merge loop
285692b01d53Sdrh   */
285792b01d53Sdrh   sqlite3VdbeResolveLabel(v, labelCmpr);
28580acb7e48Sdrh   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
28592b596da8Sdrh   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
28602ec2fb22Sdrh                          (char*)pKeyMerge, P4_KEYINFO);
2861953f7611Sdrh   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
2862b21e7c70Sdrh   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
286392b01d53Sdrh 
286492b01d53Sdrh   /* Jump to the this point in order to terminate the query.
286592b01d53Sdrh   */
2866b21e7c70Sdrh   sqlite3VdbeResolveLabel(v, labelEnd);
2867b21e7c70Sdrh 
286892b01d53Sdrh   /* Set the number of output columns
286992b01d53Sdrh   */
28707d10d5a6Sdrh   if( pDest->eDest==SRT_Output ){
28710acb7e48Sdrh     Select *pFirst = pPrior;
287292b01d53Sdrh     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
287392b01d53Sdrh     generateColumnNames(pParse, 0, pFirst->pEList);
2874b21e7c70Sdrh   }
287592b01d53Sdrh 
28760acb7e48Sdrh   /* Reassembly the compound query so that it will be freed correctly
28770acb7e48Sdrh   ** by the calling function */
28785e7ad508Sdanielk1977   if( p->pPrior ){
2879633e6d57Sdrh     sqlite3SelectDelete(db, p->pPrior);
28805e7ad508Sdanielk1977   }
28810acb7e48Sdrh   p->pPrior = pPrior;
288292b01d53Sdrh 
288392b01d53Sdrh   /*** TBD:  Insert subroutine calls to close cursors on incomplete
288492b01d53Sdrh   **** subqueries ****/
28857f61e92cSdan   explainComposite(pParse, p->op, iSub1, iSub2, 0);
288692b01d53Sdrh   return SQLITE_OK;
288792b01d53Sdrh }
2888de3e41e3Sdanielk1977 #endif
2889b21e7c70Sdrh 
28903514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
289117435752Sdrh /* Forward Declarations */
289217435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*);
289317435752Sdrh static void substSelect(sqlite3*, Select *, int, ExprList *);
289417435752Sdrh 
28952282792aSdrh /*
2896832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
28976a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
289884e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
28996a3ea0e6Sdrh ** unchanged.)
2900832508b7Sdrh **
2901832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
2902832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
2903832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
2904832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
2905832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
2906832508b7Sdrh ** of the subquery rather the result set of the subquery.
2907832508b7Sdrh */
2908b7916a78Sdrh static Expr *substExpr(
290917435752Sdrh   sqlite3 *db,        /* Report malloc errors to this connection */
291017435752Sdrh   Expr *pExpr,        /* Expr in which substitution occurs */
291117435752Sdrh   int iTable,         /* Table to be substituted */
291217435752Sdrh   ExprList *pEList    /* Substitute expressions */
291317435752Sdrh ){
2914b7916a78Sdrh   if( pExpr==0 ) return 0;
291550350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
291650350a15Sdrh     if( pExpr->iColumn<0 ){
291750350a15Sdrh       pExpr->op = TK_NULL;
291850350a15Sdrh     }else{
2919832508b7Sdrh       Expr *pNew;
292084e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
29216ab3a2ecSdanielk1977       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
2922b7916a78Sdrh       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
2923b7916a78Sdrh       sqlite3ExprDelete(db, pExpr);
2924b7916a78Sdrh       pExpr = pNew;
292550350a15Sdrh     }
2926832508b7Sdrh   }else{
2927b7916a78Sdrh     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
2928b7916a78Sdrh     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
29296ab3a2ecSdanielk1977     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
29306ab3a2ecSdanielk1977       substSelect(db, pExpr->x.pSelect, iTable, pEList);
29316ab3a2ecSdanielk1977     }else{
29326ab3a2ecSdanielk1977       substExprList(db, pExpr->x.pList, iTable, pEList);
29336ab3a2ecSdanielk1977     }
2934832508b7Sdrh   }
2935b7916a78Sdrh   return pExpr;
2936832508b7Sdrh }
293717435752Sdrh static void substExprList(
293817435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
293917435752Sdrh   ExprList *pList,     /* List to scan and in which to make substitutes */
294017435752Sdrh   int iTable,          /* Table to be substituted */
294117435752Sdrh   ExprList *pEList     /* Substitute values */
294217435752Sdrh ){
2943832508b7Sdrh   int i;
2944832508b7Sdrh   if( pList==0 ) return;
2945832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
2946b7916a78Sdrh     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
2947832508b7Sdrh   }
2948832508b7Sdrh }
294917435752Sdrh static void substSelect(
295017435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
295117435752Sdrh   Select *p,           /* SELECT statement in which to make substitutions */
295217435752Sdrh   int iTable,          /* Table to be replaced */
295317435752Sdrh   ExprList *pEList     /* Substitute values */
295417435752Sdrh ){
2955588a9a1aSdrh   SrcList *pSrc;
2956588a9a1aSdrh   struct SrcList_item *pItem;
2957588a9a1aSdrh   int i;
2958b3bce662Sdanielk1977   if( !p ) return;
295917435752Sdrh   substExprList(db, p->pEList, iTable, pEList);
296017435752Sdrh   substExprList(db, p->pGroupBy, iTable, pEList);
296117435752Sdrh   substExprList(db, p->pOrderBy, iTable, pEList);
2962b7916a78Sdrh   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
2963b7916a78Sdrh   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
296417435752Sdrh   substSelect(db, p->pPrior, iTable, pEList);
2965588a9a1aSdrh   pSrc = p->pSrc;
2966e2f02bacSdrh   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
2967e2f02bacSdrh   if( ALWAYS(pSrc) ){
2968588a9a1aSdrh     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
2969588a9a1aSdrh       substSelect(db, pItem->pSelect, iTable, pEList);
2970588a9a1aSdrh     }
2971588a9a1aSdrh   }
2972b3bce662Sdanielk1977 }
29733514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
2974832508b7Sdrh 
29753514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
2976832508b7Sdrh /*
2977630d296cSdrh ** This routine attempts to flatten subqueries as a performance optimization.
2978630d296cSdrh ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
29791350b030Sdrh **
29801350b030Sdrh ** To understand the concept of flattening, consider the following
29811350b030Sdrh ** query:
29821350b030Sdrh **
29831350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
29841350b030Sdrh **
29851350b030Sdrh ** The default way of implementing this query is to execute the
29861350b030Sdrh ** subquery first and store the results in a temporary table, then
29871350b030Sdrh ** run the outer query on that temporary table.  This requires two
29881350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
29891350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
2990832508b7Sdrh ** optimized.
29911350b030Sdrh **
2992832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
29931350b030Sdrh ** a single flat select, like this:
29941350b030Sdrh **
29951350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
29961350b030Sdrh **
29971350b030Sdrh ** The code generated for this simpification gives the same result
2998832508b7Sdrh ** but only has to scan the data once.  And because indices might
2999832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
3000832508b7Sdrh ** avoided.
30011350b030Sdrh **
3002832508b7Sdrh ** Flattening is only attempted if all of the following are true:
30031350b030Sdrh **
3004832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
30051350b030Sdrh **
3006832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
3007832508b7Sdrh **
30082b300d5dSdrh **   (3)  The subquery is not the right operand of a left outer join
300949ad330dSdan **        (Originally ticket #306.  Strengthened by ticket #3300)
3010832508b7Sdrh **
301149ad330dSdan **   (4)  The subquery is not DISTINCT.
3012832508b7Sdrh **
301349ad330dSdan **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
301449ad330dSdan **        sub-queries that were excluded from this optimization. Restriction
301549ad330dSdan **        (4) has since been expanded to exclude all DISTINCT subqueries.
3016832508b7Sdrh **
3017832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
3018832508b7Sdrh **        DISTINCT.
3019832508b7Sdrh **
3020630d296cSdrh **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
3021630d296cSdrh **        A FROM clause, consider adding a FROM close with the special
3022630d296cSdrh **        table sqlite_once that consists of a single row containing a
3023630d296cSdrh **        single NULL.
302408192d5fSdrh **
3025df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
3026df199a25Sdrh **
3027df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
3028df199a25Sdrh **        aggregates.
3029df199a25Sdrh **
3030df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
3031df199a25Sdrh **        use LIMIT.
3032df199a25Sdrh **
3033174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
3034174b6195Sdrh **
30357b688edeSdrh **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
30362b300d5dSdrh **        a separate restriction deriving from ticket #350.
30373fc673e6Sdrh **
303849ad330dSdan **  (13)  The subquery and outer query do not both use LIMIT.
3039ac83963aSdrh **
304049ad330dSdan **  (14)  The subquery does not use OFFSET.
3041ac83963aSdrh **
3042ad91c6cdSdrh **  (15)  The outer query is not part of a compound select or the
3043f3913278Sdrh **        subquery does not have a LIMIT clause.
3044f3913278Sdrh **        (See ticket #2339 and ticket [02a8e81d44]).
3045ad91c6cdSdrh **
3046c52e355dSdrh **  (16)  The outer query is not an aggregate or the subquery does
3047c52e355dSdrh **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
3048c52e355dSdrh **        until we introduced the group_concat() function.
3049c52e355dSdrh **
3050f23329a2Sdanielk1977 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
30514914cf92Sdanielk1977 **        compound clause made up entirely of non-aggregate queries, and
3052f23329a2Sdanielk1977 **        the parent query:
3053f23329a2Sdanielk1977 **
3054f23329a2Sdanielk1977 **          * is not itself part of a compound select,
3055f23329a2Sdanielk1977 **          * is not an aggregate or DISTINCT query, and
3056630d296cSdrh **          * is not a join
3057f23329a2Sdanielk1977 **
30584914cf92Sdanielk1977 **        The parent and sub-query may contain WHERE clauses. Subject to
30594914cf92Sdanielk1977 **        rules (11), (13) and (14), they may also contain ORDER BY,
3060630d296cSdrh **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
3061630d296cSdrh **        operator other than UNION ALL because all the other compound
3062630d296cSdrh **        operators have an implied DISTINCT which is disallowed by
3063630d296cSdrh **        restriction (4).
3064f23329a2Sdanielk1977 **
306567c70142Sdan **        Also, each component of the sub-query must return the same number
306667c70142Sdan **        of result columns. This is actually a requirement for any compound
306767c70142Sdan **        SELECT statement, but all the code here does is make sure that no
306867c70142Sdan **        such (illegal) sub-query is flattened. The caller will detect the
306967c70142Sdan **        syntax error and return a detailed message.
307067c70142Sdan **
307149fc1f60Sdanielk1977 **  (18)  If the sub-query is a compound select, then all terms of the
307249fc1f60Sdanielk1977 **        ORDER by clause of the parent must be simple references to
307349fc1f60Sdanielk1977 **        columns of the sub-query.
307449fc1f60Sdanielk1977 **
3075229cf702Sdrh **  (19)  The subquery does not use LIMIT or the outer query does not
3076229cf702Sdrh **        have a WHERE clause.
3077229cf702Sdrh **
3078e8902a70Sdrh **  (20)  If the sub-query is a compound select, then it must not use
3079e8902a70Sdrh **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
3080e8902a70Sdrh **        somewhat by saying that the terms of the ORDER BY clause must
3081630d296cSdrh **        appear as unmodified result columns in the outer query.  But we
3082e8902a70Sdrh **        have other optimizations in mind to deal with that case.
3083e8902a70Sdrh **
3084a91491e5Sshaneh **  (21)  The subquery does not use LIMIT or the outer query is not
3085a91491e5Sshaneh **        DISTINCT.  (See ticket [752e1646fc]).
3086a91491e5Sshaneh **
30878290c2adSdan **  (22)  The subquery is not a recursive CTE.
30888290c2adSdan **
30898290c2adSdan **  (23)  The parent is not a recursive CTE, or the sub-query is not a
30908290c2adSdan **        compound query. This restriction is because transforming the
30918290c2adSdan **        parent to a compound query confuses the code that handles
30928290c2adSdan **        recursive queries in multiSelect().
30938290c2adSdan **
30948290c2adSdan **
3095832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
3096832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
3097832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
3098832508b7Sdrh **
3099665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
3100832508b7Sdrh ** If flattening is attempted this routine returns 1.
3101832508b7Sdrh **
3102832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
3103832508b7Sdrh ** the subquery before this routine runs.
31041350b030Sdrh */
31058c74a8caSdrh static int flattenSubquery(
3106524cc21eSdanielk1977   Parse *pParse,       /* Parsing context */
31078c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
31088c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
31098c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
31108c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
31118c74a8caSdrh ){
3112524cc21eSdanielk1977   const char *zSavedAuthContext = pParse->zAuthContext;
3113f23329a2Sdanielk1977   Select *pParent;
31140bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
3115f23329a2Sdanielk1977   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
3116ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
3117ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
31180bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
31196a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
312091bb0eedSdrh   int i;              /* Loop counter */
312191bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
312291bb0eedSdrh   struct SrcList_item *pSubitem;   /* The subquery */
3123524cc21eSdanielk1977   sqlite3 *db = pParse->db;
31241350b030Sdrh 
3125832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
3126832508b7Sdrh   */
3127a78c22c4Sdrh   assert( p!=0 );
3128a78c22c4Sdrh   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
31297e5418e4Sdrh   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
3130832508b7Sdrh   pSrc = p->pSrc;
3131ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
313291bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
313349fc1f60Sdanielk1977   iParent = pSubitem->iCursor;
313491bb0eedSdrh   pSub = pSubitem->pSelect;
3135832508b7Sdrh   assert( pSub!=0 );
3136ac83963aSdrh   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
3137ac83963aSdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
3138832508b7Sdrh   pSubSrc = pSub->pSrc;
3139832508b7Sdrh   assert( pSubSrc );
3140ac83963aSdrh   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
3141ac83963aSdrh   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
3142ac83963aSdrh   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
3143ac83963aSdrh   ** became arbitrary expressions, we were forced to add restrictions (13)
3144ac83963aSdrh   ** and (14). */
3145ac83963aSdrh   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
3146ac83963aSdrh   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
3147f3913278Sdrh   if( p->pRightmost && pSub->pLimit ){
3148ad91c6cdSdrh     return 0;                                            /* Restriction (15) */
3149ad91c6cdSdrh   }
3150ac83963aSdrh   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
315149ad330dSdan   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
315249ad330dSdan   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
315349ad330dSdan      return 0;         /* Restrictions (8)(9) */
3154df199a25Sdrh   }
31557d10d5a6Sdrh   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
31567d10d5a6Sdrh      return 0;         /* Restriction (6)  */
31577d10d5a6Sdrh   }
31587d10d5a6Sdrh   if( p->pOrderBy && pSub->pOrderBy ){
3159ac83963aSdrh      return 0;                                           /* Restriction (11) */
3160ac83963aSdrh   }
3161c52e355dSdrh   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
3162229cf702Sdrh   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
3163a91491e5Sshaneh   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
3164a91491e5Sshaneh      return 0;         /* Restriction (21) */
3165a91491e5Sshaneh   }
3166eae73fbfSdan   if( pSub->selFlags & SF_Recursive ) return 0;          /* Restriction (22)  */
3167eae73fbfSdan   if( (p->selFlags & SF_Recursive) && pSub->pPrior ) return 0;       /* (23)  */
3168832508b7Sdrh 
31692b300d5dSdrh   /* OBSOLETE COMMENT 1:
31702b300d5dSdrh   ** Restriction 3:  If the subquery is a join, make sure the subquery is
31718af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
31728af4d3acSdrh   ** is not allowed:
31738af4d3acSdrh   **
31748af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
31758af4d3acSdrh   **
31768af4d3acSdrh   ** If we flatten the above, we would get
31778af4d3acSdrh   **
31788af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
31798af4d3acSdrh   **
31808af4d3acSdrh   ** which is not at all the same thing.
31812b300d5dSdrh   **
31822b300d5dSdrh   ** OBSOLETE COMMENT 2:
31832b300d5dSdrh   ** Restriction 12:  If the subquery is the right operand of a left outer
31843fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
31853fc673e6Sdrh   ** An examples of why this is not allowed:
31863fc673e6Sdrh   **
31873fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
31883fc673e6Sdrh   **
31893fc673e6Sdrh   ** If we flatten the above, we would get
31903fc673e6Sdrh   **
31913fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
31923fc673e6Sdrh   **
31933fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
31943fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
31952b300d5dSdrh   **
31962b300d5dSdrh   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
31972b300d5dSdrh   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
31982b300d5dSdrh   ** is fraught with danger.  Best to avoid the whole thing.  If the
31992b300d5dSdrh   ** subquery is the right term of a LEFT JOIN, then do not flatten.
32003fc673e6Sdrh   */
32012b300d5dSdrh   if( (pSubitem->jointype & JT_OUTER)!=0 ){
32023fc673e6Sdrh     return 0;
32033fc673e6Sdrh   }
32043fc673e6Sdrh 
3205f23329a2Sdanielk1977   /* Restriction 17: If the sub-query is a compound SELECT, then it must
3206f23329a2Sdanielk1977   ** use only the UNION ALL operator. And none of the simple select queries
3207f23329a2Sdanielk1977   ** that make up the compound SELECT are allowed to be aggregate or distinct
3208f23329a2Sdanielk1977   ** queries.
3209f23329a2Sdanielk1977   */
3210f23329a2Sdanielk1977   if( pSub->pPrior ){
3211e8902a70Sdrh     if( pSub->pOrderBy ){
3212e8902a70Sdrh       return 0;  /* Restriction 20 */
3213e8902a70Sdrh     }
3214e2f02bacSdrh     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
3215f23329a2Sdanielk1977       return 0;
3216f23329a2Sdanielk1977     }
3217f23329a2Sdanielk1977     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
3218ccfcbceaSdrh       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
3219ccfcbceaSdrh       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
32204b3ac73cSdrh       assert( pSub->pSrc!=0 );
32217d10d5a6Sdrh       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
322280b3c548Sdanielk1977        || (pSub1->pPrior && pSub1->op!=TK_ALL)
32234b3ac73cSdrh        || pSub1->pSrc->nSrc<1
322467c70142Sdan        || pSub->pEList->nExpr!=pSub1->pEList->nExpr
322580b3c548Sdanielk1977       ){
3226f23329a2Sdanielk1977         return 0;
3227f23329a2Sdanielk1977       }
32284b3ac73cSdrh       testcase( pSub1->pSrc->nSrc>1 );
3229f23329a2Sdanielk1977     }
323049fc1f60Sdanielk1977 
323149fc1f60Sdanielk1977     /* Restriction 18. */
323249fc1f60Sdanielk1977     if( p->pOrderBy ){
323349fc1f60Sdanielk1977       int ii;
323449fc1f60Sdanielk1977       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
3235c2acc4e4Sdrh         if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
323649fc1f60Sdanielk1977       }
323749fc1f60Sdanielk1977     }
3238f23329a2Sdanielk1977   }
3239f23329a2Sdanielk1977 
32407d10d5a6Sdrh   /***** If we reach this point, flattening is permitted. *****/
32417d10d5a6Sdrh 
32427d10d5a6Sdrh   /* Authorize the subquery */
3243524cc21eSdanielk1977   pParse->zAuthContext = pSubitem->zName;
3244a2acb0d7Sdrh   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
3245a2acb0d7Sdrh   testcase( i==SQLITE_DENY );
3246524cc21eSdanielk1977   pParse->zAuthContext = zSavedAuthContext;
3247524cc21eSdanielk1977 
32487d10d5a6Sdrh   /* If the sub-query is a compound SELECT statement, then (by restrictions
32497d10d5a6Sdrh   ** 17 and 18 above) it must be a UNION ALL and the parent query must
32507d10d5a6Sdrh   ** be of the form:
3251f23329a2Sdanielk1977   **
3252f23329a2Sdanielk1977   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
3253f23329a2Sdanielk1977   **
3254f23329a2Sdanielk1977   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
3255a78c22c4Sdrh   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
3256f23329a2Sdanielk1977   ** OFFSET clauses and joins them to the left-hand-side of the original
3257f23329a2Sdanielk1977   ** using UNION ALL operators. In this case N is the number of simple
3258f23329a2Sdanielk1977   ** select statements in the compound sub-query.
3259a78c22c4Sdrh   **
3260a78c22c4Sdrh   ** Example:
3261a78c22c4Sdrh   **
3262a78c22c4Sdrh   **     SELECT a+1 FROM (
3263a78c22c4Sdrh   **        SELECT x FROM tab
3264a78c22c4Sdrh   **        UNION ALL
3265a78c22c4Sdrh   **        SELECT y FROM tab
3266a78c22c4Sdrh   **        UNION ALL
3267a78c22c4Sdrh   **        SELECT abs(z*2) FROM tab2
3268a78c22c4Sdrh   **     ) WHERE a!=5 ORDER BY 1
3269a78c22c4Sdrh   **
3270a78c22c4Sdrh   ** Transformed into:
3271a78c22c4Sdrh   **
3272a78c22c4Sdrh   **     SELECT x+1 FROM tab WHERE x+1!=5
3273a78c22c4Sdrh   **     UNION ALL
3274a78c22c4Sdrh   **     SELECT y+1 FROM tab WHERE y+1!=5
3275a78c22c4Sdrh   **     UNION ALL
3276a78c22c4Sdrh   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
3277a78c22c4Sdrh   **     ORDER BY 1
3278a78c22c4Sdrh   **
3279a78c22c4Sdrh   ** We call this the "compound-subquery flattening".
3280f23329a2Sdanielk1977   */
3281f23329a2Sdanielk1977   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
3282f23329a2Sdanielk1977     Select *pNew;
3283f23329a2Sdanielk1977     ExprList *pOrderBy = p->pOrderBy;
32844b86ef1dSdanielk1977     Expr *pLimit = p->pLimit;
3285547180baSdrh     Expr *pOffset = p->pOffset;
3286f23329a2Sdanielk1977     Select *pPrior = p->pPrior;
3287f23329a2Sdanielk1977     p->pOrderBy = 0;
3288f23329a2Sdanielk1977     p->pSrc = 0;
3289f23329a2Sdanielk1977     p->pPrior = 0;
32904b86ef1dSdanielk1977     p->pLimit = 0;
3291547180baSdrh     p->pOffset = 0;
32926ab3a2ecSdanielk1977     pNew = sqlite3SelectDup(db, p, 0);
3293547180baSdrh     p->pOffset = pOffset;
32944b86ef1dSdanielk1977     p->pLimit = pLimit;
3295a78c22c4Sdrh     p->pOrderBy = pOrderBy;
3296a78c22c4Sdrh     p->pSrc = pSrc;
3297a78c22c4Sdrh     p->op = TK_ALL;
3298f23329a2Sdanielk1977     p->pRightmost = 0;
3299a78c22c4Sdrh     if( pNew==0 ){
3300a78c22c4Sdrh       pNew = pPrior;
3301a78c22c4Sdrh     }else{
3302a78c22c4Sdrh       pNew->pPrior = pPrior;
3303f23329a2Sdanielk1977       pNew->pRightmost = 0;
3304f23329a2Sdanielk1977     }
3305a78c22c4Sdrh     p->pPrior = pNew;
3306a78c22c4Sdrh     if( db->mallocFailed ) return 1;
3307a78c22c4Sdrh   }
3308f23329a2Sdanielk1977 
33097d10d5a6Sdrh   /* Begin flattening the iFrom-th entry of the FROM clause
33107d10d5a6Sdrh   ** in the outer query.
3311832508b7Sdrh   */
3312f23329a2Sdanielk1977   pSub = pSub1 = pSubitem->pSelect;
3313c31c2eb8Sdrh 
3314a78c22c4Sdrh   /* Delete the transient table structure associated with the
3315a78c22c4Sdrh   ** subquery
3316a78c22c4Sdrh   */
3317a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zDatabase);
3318a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zName);
3319a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zAlias);
3320a78c22c4Sdrh   pSubitem->zDatabase = 0;
3321a78c22c4Sdrh   pSubitem->zName = 0;
3322a78c22c4Sdrh   pSubitem->zAlias = 0;
3323a78c22c4Sdrh   pSubitem->pSelect = 0;
3324a78c22c4Sdrh 
3325a78c22c4Sdrh   /* Defer deleting the Table object associated with the
3326a78c22c4Sdrh   ** subquery until code generation is
3327a78c22c4Sdrh   ** complete, since there may still exist Expr.pTab entries that
3328a78c22c4Sdrh   ** refer to the subquery even after flattening.  Ticket #3346.
3329ccfcbceaSdrh   **
3330ccfcbceaSdrh   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
3331a78c22c4Sdrh   */
3332ccfcbceaSdrh   if( ALWAYS(pSubitem->pTab!=0) ){
3333a78c22c4Sdrh     Table *pTabToDel = pSubitem->pTab;
3334a78c22c4Sdrh     if( pTabToDel->nRef==1 ){
333565a7cd16Sdan       Parse *pToplevel = sqlite3ParseToplevel(pParse);
333665a7cd16Sdan       pTabToDel->pNextZombie = pToplevel->pZombieTab;
333765a7cd16Sdan       pToplevel->pZombieTab = pTabToDel;
3338a78c22c4Sdrh     }else{
3339a78c22c4Sdrh       pTabToDel->nRef--;
3340a78c22c4Sdrh     }
3341a78c22c4Sdrh     pSubitem->pTab = 0;
3342a78c22c4Sdrh   }
3343a78c22c4Sdrh 
3344a78c22c4Sdrh   /* The following loop runs once for each term in a compound-subquery
3345a78c22c4Sdrh   ** flattening (as described above).  If we are doing a different kind
3346a78c22c4Sdrh   ** of flattening - a flattening other than a compound-subquery flattening -
3347a78c22c4Sdrh   ** then this loop only runs once.
3348a78c22c4Sdrh   **
3349a78c22c4Sdrh   ** This loop moves all of the FROM elements of the subquery into the
3350c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
3351c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
3352c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
3353c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
3354c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
3355c31c2eb8Sdrh   ** elements we are now copying in.
3356c31c2eb8Sdrh   */
3357a78c22c4Sdrh   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
3358a78c22c4Sdrh     int nSubSrc;
3359ea678832Sdrh     u8 jointype = 0;
3360a78c22c4Sdrh     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
3361a78c22c4Sdrh     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
3362a78c22c4Sdrh     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
3363588a9a1aSdrh 
3364a78c22c4Sdrh     if( pSrc ){
3365a78c22c4Sdrh       assert( pParent==p );  /* First time through the loop */
3366a78c22c4Sdrh       jointype = pSubitem->jointype;
3367588a9a1aSdrh     }else{
3368a78c22c4Sdrh       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
3369a78c22c4Sdrh       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
3370cfa063b3Sdrh       if( pSrc==0 ){
3371a78c22c4Sdrh         assert( db->mallocFailed );
3372a78c22c4Sdrh         break;
3373cfa063b3Sdrh       }
3374c31c2eb8Sdrh     }
3375a78c22c4Sdrh 
3376a78c22c4Sdrh     /* The subquery uses a single slot of the FROM clause of the outer
3377a78c22c4Sdrh     ** query.  If the subquery has more than one element in its FROM clause,
3378a78c22c4Sdrh     ** then expand the outer query to make space for it to hold all elements
3379a78c22c4Sdrh     ** of the subquery.
3380a78c22c4Sdrh     **
3381a78c22c4Sdrh     ** Example:
3382a78c22c4Sdrh     **
3383a78c22c4Sdrh     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
3384a78c22c4Sdrh     **
3385a78c22c4Sdrh     ** The outer query has 3 slots in its FROM clause.  One slot of the
3386a78c22c4Sdrh     ** outer query (the middle slot) is used by the subquery.  The next
3387a78c22c4Sdrh     ** block of code will expand the out query to 4 slots.  The middle
3388a78c22c4Sdrh     ** slot is expanded to two slots in order to make space for the
3389a78c22c4Sdrh     ** two elements in the FROM clause of the subquery.
3390a78c22c4Sdrh     */
3391a78c22c4Sdrh     if( nSubSrc>1 ){
3392a78c22c4Sdrh       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
3393a78c22c4Sdrh       if( db->mallocFailed ){
3394a78c22c4Sdrh         break;
3395c31c2eb8Sdrh       }
3396c31c2eb8Sdrh     }
3397a78c22c4Sdrh 
3398a78c22c4Sdrh     /* Transfer the FROM clause terms from the subquery into the
3399a78c22c4Sdrh     ** outer query.
3400a78c22c4Sdrh     */
3401c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
3402c3a8402aSdrh       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
3403c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
3404c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
3405c31c2eb8Sdrh     }
340661dfc31dSdrh     pSrc->a[iFrom].jointype = jointype;
3407c31c2eb8Sdrh 
3408c31c2eb8Sdrh     /* Now begin substituting subquery result set expressions for
3409c31c2eb8Sdrh     ** references to the iParent in the outer query.
3410c31c2eb8Sdrh     **
3411c31c2eb8Sdrh     ** Example:
3412c31c2eb8Sdrh     **
3413c31c2eb8Sdrh     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
3414c31c2eb8Sdrh     **   \                     \_____________ subquery __________/          /
3415c31c2eb8Sdrh     **    \_____________________ outer query ______________________________/
3416c31c2eb8Sdrh     **
3417c31c2eb8Sdrh     ** We look at every expression in the outer query and every place we see
3418c31c2eb8Sdrh     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
3419c31c2eb8Sdrh     */
3420f23329a2Sdanielk1977     pList = pParent->pEList;
3421832508b7Sdrh     for(i=0; i<pList->nExpr; i++){
3422ccfcbceaSdrh       if( pList->a[i].zName==0 ){
342342fbf321Sdrh         char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
342442fbf321Sdrh         sqlite3Dequote(zName);
342542fbf321Sdrh         pList->a[i].zName = zName;
3426832508b7Sdrh       }
3427ccfcbceaSdrh     }
3428f23329a2Sdanielk1977     substExprList(db, pParent->pEList, iParent, pSub->pEList);
34291b2e0329Sdrh     if( isAgg ){
3430f23329a2Sdanielk1977       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
3431b7916a78Sdrh       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
34321b2e0329Sdrh     }
3433174b6195Sdrh     if( pSub->pOrderBy ){
3434f23329a2Sdanielk1977       assert( pParent->pOrderBy==0 );
3435f23329a2Sdanielk1977       pParent->pOrderBy = pSub->pOrderBy;
3436174b6195Sdrh       pSub->pOrderBy = 0;
3437f23329a2Sdanielk1977     }else if( pParent->pOrderBy ){
3438f23329a2Sdanielk1977       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
3439174b6195Sdrh     }
3440832508b7Sdrh     if( pSub->pWhere ){
34416ab3a2ecSdanielk1977       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
3442832508b7Sdrh     }else{
3443832508b7Sdrh       pWhere = 0;
3444832508b7Sdrh     }
3445832508b7Sdrh     if( subqueryIsAgg ){
3446f23329a2Sdanielk1977       assert( pParent->pHaving==0 );
3447f23329a2Sdanielk1977       pParent->pHaving = pParent->pWhere;
3448f23329a2Sdanielk1977       pParent->pWhere = pWhere;
3449b7916a78Sdrh       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
3450f23329a2Sdanielk1977       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
34516ab3a2ecSdanielk1977                                   sqlite3ExprDup(db, pSub->pHaving, 0));
3452f23329a2Sdanielk1977       assert( pParent->pGroupBy==0 );
34536ab3a2ecSdanielk1977       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
3454832508b7Sdrh     }else{
3455b7916a78Sdrh       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
3456f23329a2Sdanielk1977       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
3457832508b7Sdrh     }
3458c31c2eb8Sdrh 
3459c31c2eb8Sdrh     /* The flattened query is distinct if either the inner or the
3460c31c2eb8Sdrh     ** outer query is distinct.
3461c31c2eb8Sdrh     */
34627d10d5a6Sdrh     pParent->selFlags |= pSub->selFlags & SF_Distinct;
34638c74a8caSdrh 
3464a58fdfb1Sdanielk1977     /*
3465a58fdfb1Sdanielk1977     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
3466ac83963aSdrh     **
3467ac83963aSdrh     ** One is tempted to try to add a and b to combine the limits.  But this
3468ac83963aSdrh     ** does not work if either limit is negative.
3469a58fdfb1Sdanielk1977     */
3470a2dc3b1aSdanielk1977     if( pSub->pLimit ){
3471f23329a2Sdanielk1977       pParent->pLimit = pSub->pLimit;
3472a2dc3b1aSdanielk1977       pSub->pLimit = 0;
3473df199a25Sdrh     }
3474f23329a2Sdanielk1977   }
34758c74a8caSdrh 
3476c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
3477c31c2eb8Sdrh   ** success.
3478c31c2eb8Sdrh   */
3479633e6d57Sdrh   sqlite3SelectDelete(db, pSub1);
3480f23329a2Sdanielk1977 
3481832508b7Sdrh   return 1;
34821350b030Sdrh }
34833514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
34841350b030Sdrh 
34851350b030Sdrh /*
34864ac391fcSdan ** Based on the contents of the AggInfo structure indicated by the first
34874ac391fcSdan ** argument, this function checks if the following are true:
3488a9d1ccb9Sdanielk1977 **
34894ac391fcSdan **    * the query contains just a single aggregate function,
34904ac391fcSdan **    * the aggregate function is either min() or max(), and
34914ac391fcSdan **    * the argument to the aggregate function is a column value.
3492738bdcfbSdanielk1977 **
34934ac391fcSdan ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
34944ac391fcSdan ** is returned as appropriate. Also, *ppMinMax is set to point to the
34954ac391fcSdan ** list of arguments passed to the aggregate before returning.
34964ac391fcSdan **
34974ac391fcSdan ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
34984ac391fcSdan ** WHERE_ORDERBY_NORMAL is returned.
3499a9d1ccb9Sdanielk1977 */
35004ac391fcSdan static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
35014ac391fcSdan   int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
3502a9d1ccb9Sdanielk1977 
35034ac391fcSdan   *ppMinMax = 0;
35044ac391fcSdan   if( pAggInfo->nFunc==1 ){
35054ac391fcSdan     Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
35064ac391fcSdan     ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
35074ac391fcSdan 
35084ac391fcSdan     assert( pExpr->op==TK_AGG_FUNCTION );
35094ac391fcSdan     if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
35104ac391fcSdan       const char *zFunc = pExpr->u.zToken;
35114ac391fcSdan       if( sqlite3StrICmp(zFunc, "min")==0 ){
35124ac391fcSdan         eRet = WHERE_ORDERBY_MIN;
35134ac391fcSdan         *ppMinMax = pEList;
35144ac391fcSdan       }else if( sqlite3StrICmp(zFunc, "max")==0 ){
35154ac391fcSdan         eRet = WHERE_ORDERBY_MAX;
35164ac391fcSdan         *ppMinMax = pEList;
3517a9d1ccb9Sdanielk1977       }
35184ac391fcSdan     }
35194ac391fcSdan   }
35204ac391fcSdan 
35214ac391fcSdan   assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
35224ac391fcSdan   return eRet;
3523a9d1ccb9Sdanielk1977 }
3524a9d1ccb9Sdanielk1977 
3525a9d1ccb9Sdanielk1977 /*
3526a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query.
3527a5533162Sdanielk1977 ** The second argment is the associated aggregate-info object. This
3528a5533162Sdanielk1977 ** function tests if the SELECT is of the form:
3529a5533162Sdanielk1977 **
3530a5533162Sdanielk1977 **   SELECT count(*) FROM <tbl>
3531a5533162Sdanielk1977 **
3532a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query
3533a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing
3534a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned.
3535a5533162Sdanielk1977 */
3536a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
3537a5533162Sdanielk1977   Table *pTab;
3538a5533162Sdanielk1977   Expr *pExpr;
3539a5533162Sdanielk1977 
3540a5533162Sdanielk1977   assert( !p->pGroupBy );
3541a5533162Sdanielk1977 
35427a895a80Sdanielk1977   if( p->pWhere || p->pEList->nExpr!=1
3543a5533162Sdanielk1977    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
3544a5533162Sdanielk1977   ){
3545a5533162Sdanielk1977     return 0;
3546a5533162Sdanielk1977   }
3547a5533162Sdanielk1977   pTab = p->pSrc->a[0].pTab;
3548a5533162Sdanielk1977   pExpr = p->pEList->a[0].pExpr;
354902f33725Sdanielk1977   assert( pTab && !pTab->pSelect && pExpr );
355002f33725Sdanielk1977 
355102f33725Sdanielk1977   if( IsVirtual(pTab) ) return 0;
3552a5533162Sdanielk1977   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
3553fb0a6081Sdrh   if( NEVER(pAggInfo->nFunc==0) ) return 0;
3554d36e1041Sdrh   if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
3555a5533162Sdanielk1977   if( pExpr->flags&EP_Distinct ) return 0;
3556a5533162Sdanielk1977 
3557a5533162Sdanielk1977   return pTab;
3558a5533162Sdanielk1977 }
3559a5533162Sdanielk1977 
3560a5533162Sdanielk1977 /*
3561b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an
3562b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there
3563b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return
3564b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
3565b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK.
3566b1c685b0Sdanielk1977 */
3567b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
3568b1c685b0Sdanielk1977   if( pFrom->pTab && pFrom->zIndex ){
3569b1c685b0Sdanielk1977     Table *pTab = pFrom->pTab;
3570b1c685b0Sdanielk1977     char *zIndex = pFrom->zIndex;
3571b1c685b0Sdanielk1977     Index *pIdx;
3572b1c685b0Sdanielk1977     for(pIdx=pTab->pIndex;
3573b1c685b0Sdanielk1977         pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
3574b1c685b0Sdanielk1977         pIdx=pIdx->pNext
3575b1c685b0Sdanielk1977     );
3576b1c685b0Sdanielk1977     if( !pIdx ){
3577b1c685b0Sdanielk1977       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
35781db95106Sdan       pParse->checkSchema = 1;
3579b1c685b0Sdanielk1977       return SQLITE_ERROR;
3580b1c685b0Sdanielk1977     }
3581b1c685b0Sdanielk1977     pFrom->pIndex = pIdx;
3582b1c685b0Sdanielk1977   }
3583b1c685b0Sdanielk1977   return SQLITE_OK;
3584b1c685b0Sdanielk1977 }
3585c01b7306Sdrh /*
3586c01b7306Sdrh ** Detect compound SELECT statements that use an ORDER BY clause with
3587c01b7306Sdrh ** an alternative collating sequence.
3588c01b7306Sdrh **
3589c01b7306Sdrh **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
3590c01b7306Sdrh **
3591c01b7306Sdrh ** These are rewritten as a subquery:
3592c01b7306Sdrh **
3593c01b7306Sdrh **    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
3594c01b7306Sdrh **     ORDER BY ... COLLATE ...
3595c01b7306Sdrh **
3596c01b7306Sdrh ** This transformation is necessary because the multiSelectOrderBy() routine
3597c01b7306Sdrh ** above that generates the code for a compound SELECT with an ORDER BY clause
3598c01b7306Sdrh ** uses a merge algorithm that requires the same collating sequence on the
3599c01b7306Sdrh ** result columns as on the ORDER BY clause.  See ticket
3600c01b7306Sdrh ** http://www.sqlite.org/src/info/6709574d2a
3601c01b7306Sdrh **
3602c01b7306Sdrh ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
3603c01b7306Sdrh ** The UNION ALL operator works fine with multiSelectOrderBy() even when
3604c01b7306Sdrh ** there are COLLATE terms in the ORDER BY.
3605c01b7306Sdrh */
3606c01b7306Sdrh static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
3607c01b7306Sdrh   int i;
3608c01b7306Sdrh   Select *pNew;
3609c01b7306Sdrh   Select *pX;
3610c01b7306Sdrh   sqlite3 *db;
3611c01b7306Sdrh   struct ExprList_item *a;
3612c01b7306Sdrh   SrcList *pNewSrc;
3613c01b7306Sdrh   Parse *pParse;
3614c01b7306Sdrh   Token dummy;
3615c01b7306Sdrh 
3616c01b7306Sdrh   if( p->pPrior==0 ) return WRC_Continue;
3617c01b7306Sdrh   if( p->pOrderBy==0 ) return WRC_Continue;
3618c01b7306Sdrh   for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
3619c01b7306Sdrh   if( pX==0 ) return WRC_Continue;
3620c01b7306Sdrh   a = p->pOrderBy->a;
3621c01b7306Sdrh   for(i=p->pOrderBy->nExpr-1; i>=0; i--){
3622c01b7306Sdrh     if( a[i].pExpr->flags & EP_Collate ) break;
3623c01b7306Sdrh   }
3624c01b7306Sdrh   if( i<0 ) return WRC_Continue;
3625c01b7306Sdrh 
3626c01b7306Sdrh   /* If we reach this point, that means the transformation is required. */
3627c01b7306Sdrh 
3628c01b7306Sdrh   pParse = pWalker->pParse;
3629c01b7306Sdrh   db = pParse->db;
3630c01b7306Sdrh   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
3631c01b7306Sdrh   if( pNew==0 ) return WRC_Abort;
3632c01b7306Sdrh   memset(&dummy, 0, sizeof(dummy));
3633c01b7306Sdrh   pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
3634c01b7306Sdrh   if( pNewSrc==0 ) return WRC_Abort;
3635c01b7306Sdrh   *pNew = *p;
3636c01b7306Sdrh   p->pSrc = pNewSrc;
3637c01b7306Sdrh   p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
3638c01b7306Sdrh   p->op = TK_SELECT;
3639c01b7306Sdrh   p->pWhere = 0;
3640c01b7306Sdrh   pNew->pGroupBy = 0;
3641c01b7306Sdrh   pNew->pHaving = 0;
3642c01b7306Sdrh   pNew->pOrderBy = 0;
3643c01b7306Sdrh   p->pPrior = 0;
3644c01b7306Sdrh   pNew->pLimit = 0;
3645c01b7306Sdrh   pNew->pOffset = 0;
3646c01b7306Sdrh   return WRC_Continue;
3647c01b7306Sdrh }
3648b1c685b0Sdanielk1977 
3649eede6a53Sdan #ifndef SQLITE_OMIT_CTE
3650eede6a53Sdan /*
3651eede6a53Sdan ** Argument pWith (which may be NULL) points to a linked list of nested
3652eede6a53Sdan ** WITH contexts, from inner to outermost. If the table identified by
3653eede6a53Sdan ** FROM clause element pItem is really a common-table-expression (CTE)
3654eede6a53Sdan ** then return a pointer to the CTE definition for that table. Otherwise
3655eede6a53Sdan ** return NULL.
365698f45e53Sdan **
365798f45e53Sdan ** If a non-NULL value is returned, set *ppContext to point to the With
365898f45e53Sdan ** object that the returned CTE belongs to.
365960c1a2f0Sdrh */
366098f45e53Sdan static struct Cte *searchWith(
366198f45e53Sdan   With *pWith,                    /* Current outermost WITH clause */
366298f45e53Sdan   struct SrcList_item *pItem,     /* FROM clause element to resolve */
366398f45e53Sdan   With **ppContext                /* OUT: WITH clause return value belongs to */
366498f45e53Sdan ){
36657b19f252Sdrh   const char *zName;
36667b19f252Sdrh   if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
3667eede6a53Sdan     With *p;
3668eede6a53Sdan     for(p=pWith; p; p=p->pOuter){
36694e9119d9Sdan       int i;
3670eede6a53Sdan       for(i=0; i<p->nCte; i++){
3671eede6a53Sdan         if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
367298f45e53Sdan           *ppContext = p;
3673eede6a53Sdan           return &p->a[i];
36744e9119d9Sdan         }
36754e9119d9Sdan       }
36764e9119d9Sdan     }
36774e9119d9Sdan   }
36784e9119d9Sdan   return 0;
36794e9119d9Sdan }
36804e9119d9Sdan 
3681c49832c2Sdrh /* The code generator maintains a stack of active WITH clauses
3682c49832c2Sdrh ** with the inner-most WITH clause being at the top of the stack.
3683c49832c2Sdrh **
3684b290f117Sdan ** This routine pushes the WITH clause passed as the second argument
3685b290f117Sdan ** onto the top of the stack. If argument bFree is true, then this
3686b290f117Sdan ** WITH clause will never be popped from the stack. In this case it
3687b290f117Sdan ** should be freed along with the Parse object. In other cases, when
3688b290f117Sdan ** bFree==0, the With object will be freed along with the SELECT
3689b290f117Sdan ** statement with which it is associated.
3690c49832c2Sdrh */
3691b290f117Sdan void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
3692b290f117Sdan   assert( bFree==0 || pParse->pWith==0 );
36934e9119d9Sdan   if( pWith ){
36944e9119d9Sdan     pWith->pOuter = pParse->pWith;
36954e9119d9Sdan     pParse->pWith = pWith;
3696b290f117Sdan     pParse->bFreeWith = bFree;
36974e9119d9Sdan   }
36984e9119d9Sdan }
36994e9119d9Sdan 
3700eede6a53Sdan /*
3701eede6a53Sdan ** This function checks if argument pFrom refers to a CTE declared by
3702eede6a53Sdan ** a WITH clause on the stack currently maintained by the parser. And,
3703eede6a53Sdan ** if currently processing a CTE expression, if it is a recursive
3704eede6a53Sdan ** reference to the current CTE.
3705eede6a53Sdan **
3706eede6a53Sdan ** If pFrom falls into either of the two categories above, pFrom->pTab
3707eede6a53Sdan ** and other fields are populated accordingly. The caller should check
3708eede6a53Sdan ** (pFrom->pTab!=0) to determine whether or not a successful match
3709eede6a53Sdan ** was found.
3710eede6a53Sdan **
3711eede6a53Sdan ** Whether or not a match is found, SQLITE_OK is returned if no error
3712eede6a53Sdan ** occurs. If an error does occur, an error message is stored in the
3713eede6a53Sdan ** parser and some error code other than SQLITE_OK returned.
3714eede6a53Sdan */
37158ce7184bSdan static int withExpand(
37168ce7184bSdan   Walker *pWalker,
3717eede6a53Sdan   struct SrcList_item *pFrom
37188ce7184bSdan ){
37198ce7184bSdan   Parse *pParse = pWalker->pParse;
37208ce7184bSdan   sqlite3 *db = pParse->db;
372198f45e53Sdan   struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
372298f45e53Sdan   With *pWith;                    /* WITH clause that pCte belongs to */
37238ce7184bSdan 
37248ce7184bSdan   assert( pFrom->pTab==0 );
37258ce7184bSdan 
372698f45e53Sdan   pCte = searchWith(pParse->pWith, pFrom, &pWith);
3727eae73fbfSdan   if( pCte ){
372898f45e53Sdan     Table *pTab;
37298ce7184bSdan     ExprList *pEList;
37308ce7184bSdan     Select *pSel;
373160e7068dSdan     Select *pLeft;                /* Left-most SELECT statement */
3732f2655fe8Sdan     int bMayRecursive;            /* True if compound joined by UNION [ALL] */
373398f45e53Sdan     With *pSavedWith;             /* Initial value of pParse->pWith */
3734f2655fe8Sdan 
3735f2655fe8Sdan     /* If pCte->zErr is non-NULL at this point, then this is an illegal
3736f2655fe8Sdan     ** recursive reference to CTE pCte. Leave an error in pParse and return
3737f2655fe8Sdan     ** early. If pCte->zErr is NULL, then this is not a recursive reference.
3738f2655fe8Sdan     ** In this case, proceed.  */
3739f2655fe8Sdan     if( pCte->zErr ){
3740f2655fe8Sdan       sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName);
374198f45e53Sdan       return SQLITE_ERROR;
3742f2655fe8Sdan     }
37438ce7184bSdan 
3744c25e2ebcSdrh     assert( pFrom->pTab==0 );
37458ce7184bSdan     pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
37468ce7184bSdan     if( pTab==0 ) return WRC_Abort;
37478ce7184bSdan     pTab->nRef = 1;
37482d4dc5fcSdan     pTab->zName = sqlite3DbStrDup(db, pCte->zName);
37498ce7184bSdan     pTab->iPKey = -1;
37508ce7184bSdan     pTab->nRowEst = 1048576;
37518ce7184bSdan     pTab->tabFlags |= TF_Ephemeral;
37528ce7184bSdan     pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
37538ce7184bSdan     if( db->mallocFailed ) return SQLITE_NOMEM;
37548ce7184bSdan     assert( pFrom->pSelect );
37558ce7184bSdan 
3756eae73fbfSdan     /* Check if this is a recursive CTE. */
37578ce7184bSdan     pSel = pFrom->pSelect;
3758f2655fe8Sdan     bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
3759f2655fe8Sdan     if( bMayRecursive ){
3760eae73fbfSdan       int i;
3761eae73fbfSdan       SrcList *pSrc = pFrom->pSelect->pSrc;
3762eae73fbfSdan       for(i=0; i<pSrc->nSrc; i++){
3763eae73fbfSdan         struct SrcList_item *pItem = &pSrc->a[i];
3764eae73fbfSdan         if( pItem->zDatabase==0
3765eae73fbfSdan          && pItem->zName!=0
3766eae73fbfSdan          && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
3767eae73fbfSdan           ){
3768eae73fbfSdan           pItem->pTab = pTab;
3769eae73fbfSdan           pItem->isRecursive = 1;
3770eae73fbfSdan           pTab->nRef++;
3771eae73fbfSdan           pSel->selFlags |= SF_Recursive;
37728ce7184bSdan         }
3773eae73fbfSdan       }
3774eae73fbfSdan     }
3775eae73fbfSdan 
3776eae73fbfSdan     /* Only one recursive reference is permitted. */
3777eae73fbfSdan     if( pTab->nRef>2 ){
3778eae73fbfSdan       sqlite3ErrorMsg(
3779727a99f1Sdrh           pParse, "multiple references to recursive table: %s", pCte->zName
3780eae73fbfSdan       );
378198f45e53Sdan       return SQLITE_ERROR;
3782eae73fbfSdan     }
3783eae73fbfSdan     assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
3784eae73fbfSdan 
3785727a99f1Sdrh     pCte->zErr = "circular reference: %s";
378698f45e53Sdan     pSavedWith = pParse->pWith;
378798f45e53Sdan     pParse->pWith = pWith;
3788f2655fe8Sdan     sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
37898ce7184bSdan 
37908ce7184bSdan     for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
37918ce7184bSdan     pEList = pLeft->pEList;
379260e7068dSdan     if( pCte->pCols ){
379360e7068dSdan       if( pEList->nExpr!=pCte->pCols->nExpr ){
3794727a99f1Sdrh         sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
379560e7068dSdan             pCte->zName, pEList->nExpr, pCte->pCols->nExpr
379660e7068dSdan         );
379798f45e53Sdan         pParse->pWith = pSavedWith;
379898f45e53Sdan         return SQLITE_ERROR;
37998ce7184bSdan       }
380060e7068dSdan       pEList = pCte->pCols;
380160e7068dSdan     }
38028ce7184bSdan 
380398f45e53Sdan     selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
3804f2655fe8Sdan     if( bMayRecursive ){
3805f2655fe8Sdan       if( pSel->selFlags & SF_Recursive ){
3806727a99f1Sdrh         pCte->zErr = "multiple recursive references: %s";
3807f2655fe8Sdan       }else{
3808727a99f1Sdrh         pCte->zErr = "recursive reference in a subquery: %s";
3809f2655fe8Sdan       }
3810f2655fe8Sdan       sqlite3WalkSelect(pWalker, pSel);
3811f2655fe8Sdan     }
3812f2655fe8Sdan     pCte->zErr = 0;
381398f45e53Sdan     pParse->pWith = pSavedWith;
38148ce7184bSdan   }
38158ce7184bSdan 
38168ce7184bSdan   return SQLITE_OK;
38178ce7184bSdan }
3818eede6a53Sdan #endif
38194e9119d9Sdan 
3820b290f117Sdan #ifndef SQLITE_OMIT_CTE
382171856944Sdan /*
382271856944Sdan ** If the SELECT passed as the second argument has an associated WITH
382371856944Sdan ** clause, pop it from the stack stored as part of the Parse object.
382471856944Sdan **
382571856944Sdan ** This function is used as the xSelectCallback2() callback by
382671856944Sdan ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
382771856944Sdan ** names and other FROM clause elements.
382871856944Sdan */
3829b290f117Sdan static void selectPopWith(Walker *pWalker, Select *p){
3830b290f117Sdan   Parse *pParse = pWalker->pParse;
3831b290f117Sdan   if( p->pWith ){
3832b290f117Sdan     assert( pParse->pWith==p->pWith );
3833b290f117Sdan     pParse->pWith = p->pWith->pOuter;
3834b290f117Sdan   }
3835b290f117Sdan }
3836b290f117Sdan #else
3837b290f117Sdan #define selectPopWith 0
3838b290f117Sdan #endif
3839b290f117Sdan 
3840b1c685b0Sdanielk1977 /*
38417d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement.
38427d10d5a6Sdrh ** "Expanding" means to do the following:
38437d10d5a6Sdrh **
38447d10d5a6Sdrh **    (1)  Make sure VDBE cursor numbers have been assigned to every
38457d10d5a6Sdrh **         element of the FROM clause.
38467d10d5a6Sdrh **
38477d10d5a6Sdrh **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
38487d10d5a6Sdrh **         defines FROM clause.  When views appear in the FROM clause,
38497d10d5a6Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
38507d10d5a6Sdrh **         that implements the view.  A copy is made of the view's SELECT
38517d10d5a6Sdrh **         statement so that we can freely modify or delete that statement
38527d10d5a6Sdrh **         without worrying about messing up the presistent representation
38537d10d5a6Sdrh **         of the view.
38547d10d5a6Sdrh **
38557d10d5a6Sdrh **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
38567d10d5a6Sdrh **         on joins and the ON and USING clause of joins.
38577d10d5a6Sdrh **
38587d10d5a6Sdrh **    (4)  Scan the list of columns in the result set (pEList) looking
38597d10d5a6Sdrh **         for instances of the "*" operator or the TABLE.* operator.
38607d10d5a6Sdrh **         If found, expand each "*" to be every column in every table
38617d10d5a6Sdrh **         and TABLE.* to be every column in TABLE.
38627d10d5a6Sdrh **
3863b3bce662Sdanielk1977 */
38647d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){
38657d10d5a6Sdrh   Parse *pParse = pWalker->pParse;
38667d10d5a6Sdrh   int i, j, k;
38677d10d5a6Sdrh   SrcList *pTabList;
38687d10d5a6Sdrh   ExprList *pEList;
38697d10d5a6Sdrh   struct SrcList_item *pFrom;
38707d10d5a6Sdrh   sqlite3 *db = pParse->db;
38713e3f1a5bSdrh   Expr *pE, *pRight, *pExpr;
3872785097daSdrh   u16 selFlags = p->selFlags;
38737d10d5a6Sdrh 
3874785097daSdrh   p->selFlags |= SF_Expanded;
38757d10d5a6Sdrh   if( db->mallocFailed  ){
38767d10d5a6Sdrh     return WRC_Abort;
38777d10d5a6Sdrh   }
3878785097daSdrh   if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
38797d10d5a6Sdrh     return WRC_Prune;
38807d10d5a6Sdrh   }
38817d10d5a6Sdrh   pTabList = p->pSrc;
38827d10d5a6Sdrh   pEList = p->pEList;
3883b290f117Sdan   sqlite3WithPush(pParse, p->pWith, 0);
38847d10d5a6Sdrh 
38857d10d5a6Sdrh   /* Make sure cursor numbers have been assigned to all entries in
38867d10d5a6Sdrh   ** the FROM clause of the SELECT statement.
38877d10d5a6Sdrh   */
38887d10d5a6Sdrh   sqlite3SrcListAssignCursors(pParse, pTabList);
38897d10d5a6Sdrh 
38907d10d5a6Sdrh   /* Look up every table named in the FROM clause of the select.  If
38917d10d5a6Sdrh   ** an entry of the FROM clause is a subquery instead of a table or view,
38927d10d5a6Sdrh   ** then create a transient table structure to describe the subquery.
38937d10d5a6Sdrh   */
38947d10d5a6Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
38957d10d5a6Sdrh     Table *pTab;
3896eae73fbfSdan     assert( pFrom->isRecursive==0 || pFrom->pTab );
3897eae73fbfSdan     if( pFrom->isRecursive ) continue;
38987d10d5a6Sdrh     if( pFrom->pTab!=0 ){
38997d10d5a6Sdrh       /* This statement has already been prepared.  There is no need
39007d10d5a6Sdrh       ** to go further. */
39017d10d5a6Sdrh       assert( i==0 );
3902b290f117Sdan #ifndef SQLITE_OMIT_CTE
3903b290f117Sdan       selectPopWith(pWalker, p);
3904b290f117Sdan #endif
39057d10d5a6Sdrh       return WRC_Prune;
39067d10d5a6Sdrh     }
39074e9119d9Sdan #ifndef SQLITE_OMIT_CTE
3908eede6a53Sdan     if( withExpand(pWalker, pFrom) ) return WRC_Abort;
3909eede6a53Sdan     if( pFrom->pTab ) {} else
39104e9119d9Sdan #endif
39117d10d5a6Sdrh     if( pFrom->zName==0 ){
39127d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
39137d10d5a6Sdrh       Select *pSel = pFrom->pSelect;
39147d10d5a6Sdrh       /* A sub-query in the FROM clause of a SELECT */
39157d10d5a6Sdrh       assert( pSel!=0 );
39167d10d5a6Sdrh       assert( pFrom->pTab==0 );
39177d10d5a6Sdrh       sqlite3WalkSelect(pWalker, pSel);
39187d10d5a6Sdrh       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
39197d10d5a6Sdrh       if( pTab==0 ) return WRC_Abort;
39207d10d5a6Sdrh       pTab->nRef = 1;
3921186ad8ccSdrh       pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
39227d10d5a6Sdrh       while( pSel->pPrior ){ pSel = pSel->pPrior; }
39237d10d5a6Sdrh       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
39247d10d5a6Sdrh       pTab->iPKey = -1;
3925186ad8ccSdrh       pTab->nRowEst = 1048576;
39267d10d5a6Sdrh       pTab->tabFlags |= TF_Ephemeral;
39277d10d5a6Sdrh #endif
39287d10d5a6Sdrh     }else{
39297d10d5a6Sdrh       /* An ordinary table or view name in the FROM clause */
39307d10d5a6Sdrh       assert( pFrom->pTab==0 );
393141fb5cd1Sdan       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
39327d10d5a6Sdrh       if( pTab==0 ) return WRC_Abort;
3933d2a56238Sdrh       if( pTab->nRef==0xffff ){
3934d2a56238Sdrh         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
3935d2a56238Sdrh            pTab->zName);
3936d2a56238Sdrh         pFrom->pTab = 0;
3937d2a56238Sdrh         return WRC_Abort;
3938d2a56238Sdrh       }
39397d10d5a6Sdrh       pTab->nRef++;
39407d10d5a6Sdrh #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
39417d10d5a6Sdrh       if( pTab->pSelect || IsVirtual(pTab) ){
39427d10d5a6Sdrh         /* We reach here if the named table is a really a view */
39437d10d5a6Sdrh         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
394443152cf8Sdrh         assert( pFrom->pSelect==0 );
39456ab3a2ecSdanielk1977         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
39467d10d5a6Sdrh         sqlite3WalkSelect(pWalker, pFrom->pSelect);
39477d10d5a6Sdrh       }
39487d10d5a6Sdrh #endif
39497d10d5a6Sdrh     }
395085574e31Sdanielk1977 
395185574e31Sdanielk1977     /* Locate the index named by the INDEXED BY clause, if any. */
3952b1c685b0Sdanielk1977     if( sqlite3IndexedByLookup(pParse, pFrom) ){
395385574e31Sdanielk1977       return WRC_Abort;
395485574e31Sdanielk1977     }
39557d10d5a6Sdrh   }
39567d10d5a6Sdrh 
39577d10d5a6Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
39587d10d5a6Sdrh   */
39597d10d5a6Sdrh   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
39607d10d5a6Sdrh     return WRC_Abort;
39617d10d5a6Sdrh   }
39627d10d5a6Sdrh 
39637d10d5a6Sdrh   /* For every "*" that occurs in the column list, insert the names of
39647d10d5a6Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
39657d10d5a6Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
39667d10d5a6Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
39677d10d5a6Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
39687d10d5a6Sdrh   ** each one to the list of all columns in all tables.
39697d10d5a6Sdrh   **
39707d10d5a6Sdrh   ** The first loop just checks to see if there are any "*" operators
39717d10d5a6Sdrh   ** that need expanding.
39727d10d5a6Sdrh   */
39737d10d5a6Sdrh   for(k=0; k<pEList->nExpr; k++){
39743e3f1a5bSdrh     pE = pEList->a[k].pExpr;
39757d10d5a6Sdrh     if( pE->op==TK_ALL ) break;
397643152cf8Sdrh     assert( pE->op!=TK_DOT || pE->pRight!=0 );
397743152cf8Sdrh     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
397843152cf8Sdrh     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
39797d10d5a6Sdrh   }
39807d10d5a6Sdrh   if( k<pEList->nExpr ){
39817d10d5a6Sdrh     /*
39827d10d5a6Sdrh     ** If we get here it means the result set contains one or more "*"
39837d10d5a6Sdrh     ** operators that need to be expanded.  Loop through each expression
39847d10d5a6Sdrh     ** in the result set and expand them one by one.
39857d10d5a6Sdrh     */
39867d10d5a6Sdrh     struct ExprList_item *a = pEList->a;
39877d10d5a6Sdrh     ExprList *pNew = 0;
39887d10d5a6Sdrh     int flags = pParse->db->flags;
39897d10d5a6Sdrh     int longNames = (flags & SQLITE_FullColNames)!=0
399038b384a0Sdrh                       && (flags & SQLITE_ShortColNames)==0;
399138b384a0Sdrh 
399238b384a0Sdrh     /* When processing FROM-clause subqueries, it is always the case
399338b384a0Sdrh     ** that full_column_names=OFF and short_column_names=ON.  The
399438b384a0Sdrh     ** sqlite3ResultSetOfSelect() routine makes it so. */
399538b384a0Sdrh     assert( (p->selFlags & SF_NestedFrom)==0
399638b384a0Sdrh           || ((flags & SQLITE_FullColNames)==0 &&
399738b384a0Sdrh               (flags & SQLITE_ShortColNames)!=0) );
39987d10d5a6Sdrh 
39997d10d5a6Sdrh     for(k=0; k<pEList->nExpr; k++){
40003e3f1a5bSdrh       pE = a[k].pExpr;
40013e3f1a5bSdrh       pRight = pE->pRight;
40023e3f1a5bSdrh       assert( pE->op!=TK_DOT || pRight!=0 );
40033e3f1a5bSdrh       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
40047d10d5a6Sdrh         /* This particular expression does not need to be expanded.
40057d10d5a6Sdrh         */
4006b7916a78Sdrh         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
40077d10d5a6Sdrh         if( pNew ){
40087d10d5a6Sdrh           pNew->a[pNew->nExpr-1].zName = a[k].zName;
4009b7916a78Sdrh           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
4010b7916a78Sdrh           a[k].zName = 0;
4011b7916a78Sdrh           a[k].zSpan = 0;
40127d10d5a6Sdrh         }
40137d10d5a6Sdrh         a[k].pExpr = 0;
40147d10d5a6Sdrh       }else{
40157d10d5a6Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
40167d10d5a6Sdrh         ** expanded. */
40177d10d5a6Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
40183e3f1a5bSdrh         char *zTName = 0;       /* text of name of TABLE */
401943152cf8Sdrh         if( pE->op==TK_DOT ){
402043152cf8Sdrh           assert( pE->pLeft!=0 );
402133e619fcSdrh           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
402233e619fcSdrh           zTName = pE->pLeft->u.zToken;
40237d10d5a6Sdrh         }
40247d10d5a6Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
40257d10d5a6Sdrh           Table *pTab = pFrom->pTab;
40263e3f1a5bSdrh           Select *pSub = pFrom->pSelect;
40277d10d5a6Sdrh           char *zTabName = pFrom->zAlias;
40283e3f1a5bSdrh           const char *zSchemaName = 0;
4029c75e09c7Sdrh           int iDb;
403043152cf8Sdrh           if( zTabName==0 ){
40317d10d5a6Sdrh             zTabName = pTab->zName;
40327d10d5a6Sdrh           }
40337d10d5a6Sdrh           if( db->mallocFailed ) break;
40343e3f1a5bSdrh           if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
40353e3f1a5bSdrh             pSub = 0;
40367d10d5a6Sdrh             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
40377d10d5a6Sdrh               continue;
40387d10d5a6Sdrh             }
40393e3f1a5bSdrh             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
4040c75e09c7Sdrh             zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
40413e3f1a5bSdrh           }
40427d10d5a6Sdrh           for(j=0; j<pTab->nCol; j++){
40437d10d5a6Sdrh             char *zName = pTab->aCol[j].zName;
4044b7916a78Sdrh             char *zColname;  /* The computed column name */
4045b7916a78Sdrh             char *zToFree;   /* Malloced string that needs to be freed */
4046b7916a78Sdrh             Token sColname;  /* Computed column name as a token */
40477d10d5a6Sdrh 
4048c75e09c7Sdrh             assert( zName );
40493e3f1a5bSdrh             if( zTName && pSub
40503e3f1a5bSdrh              && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
40513e3f1a5bSdrh             ){
40523e3f1a5bSdrh               continue;
40533e3f1a5bSdrh             }
40543e3f1a5bSdrh 
40557d10d5a6Sdrh             /* If a column is marked as 'hidden' (currently only possible
40567d10d5a6Sdrh             ** for virtual tables), do not include it in the expanded
40577d10d5a6Sdrh             ** result-set list.
40587d10d5a6Sdrh             */
40597d10d5a6Sdrh             if( IsHiddenColumn(&pTab->aCol[j]) ){
40607d10d5a6Sdrh               assert(IsVirtual(pTab));
40617d10d5a6Sdrh               continue;
40627d10d5a6Sdrh             }
40633e3f1a5bSdrh             tableSeen = 1;
40647d10d5a6Sdrh 
4065da55c48aSdrh             if( i>0 && zTName==0 ){
40662179b434Sdrh               if( (pFrom->jointype & JT_NATURAL)!=0
40672179b434Sdrh                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
40682179b434Sdrh               ){
40697d10d5a6Sdrh                 /* In a NATURAL join, omit the join columns from the
40702179b434Sdrh                 ** table to the right of the join */
40717d10d5a6Sdrh                 continue;
40727d10d5a6Sdrh               }
40732179b434Sdrh               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
40747d10d5a6Sdrh                 /* In a join with a USING clause, omit columns in the
40757d10d5a6Sdrh                 ** using clause from the table on the right. */
40767d10d5a6Sdrh                 continue;
40777d10d5a6Sdrh               }
40787d10d5a6Sdrh             }
4079b7916a78Sdrh             pRight = sqlite3Expr(db, TK_ID, zName);
4080b7916a78Sdrh             zColname = zName;
4081b7916a78Sdrh             zToFree = 0;
40827d10d5a6Sdrh             if( longNames || pTabList->nSrc>1 ){
4083b7916a78Sdrh               Expr *pLeft;
4084b7916a78Sdrh               pLeft = sqlite3Expr(db, TK_ID, zTabName);
40857d10d5a6Sdrh               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
408638b384a0Sdrh               if( zSchemaName ){
4087c75e09c7Sdrh                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
4088c75e09c7Sdrh                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
4089c75e09c7Sdrh               }
4090b7916a78Sdrh               if( longNames ){
4091b7916a78Sdrh                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
4092b7916a78Sdrh                 zToFree = zColname;
4093b7916a78Sdrh               }
40947d10d5a6Sdrh             }else{
40957d10d5a6Sdrh               pExpr = pRight;
40967d10d5a6Sdrh             }
4097b7916a78Sdrh             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
4098b7916a78Sdrh             sColname.z = zColname;
4099b7916a78Sdrh             sColname.n = sqlite3Strlen30(zColname);
4100b7916a78Sdrh             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
41018f25d18bSdrh             if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
41023e3f1a5bSdrh               struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
41033e3f1a5bSdrh               if( pSub ){
41043e3f1a5bSdrh                 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
4105c75e09c7Sdrh                 testcase( pX->zSpan==0 );
41063e3f1a5bSdrh               }else{
41073e3f1a5bSdrh                 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
41083e3f1a5bSdrh                                            zSchemaName, zTabName, zColname);
4109c75e09c7Sdrh                 testcase( pX->zSpan==0 );
41103e3f1a5bSdrh               }
41113e3f1a5bSdrh               pX->bSpanIsTab = 1;
41128f25d18bSdrh             }
4113b7916a78Sdrh             sqlite3DbFree(db, zToFree);
41147d10d5a6Sdrh           }
41157d10d5a6Sdrh         }
41167d10d5a6Sdrh         if( !tableSeen ){
41177d10d5a6Sdrh           if( zTName ){
41187d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
41197d10d5a6Sdrh           }else{
41207d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no tables specified");
41217d10d5a6Sdrh           }
41227d10d5a6Sdrh         }
41237d10d5a6Sdrh       }
41247d10d5a6Sdrh     }
41257d10d5a6Sdrh     sqlite3ExprListDelete(db, pEList);
41267d10d5a6Sdrh     p->pEList = pNew;
41277d10d5a6Sdrh   }
41287d10d5a6Sdrh #if SQLITE_MAX_COLUMN
41297d10d5a6Sdrh   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
41307d10d5a6Sdrh     sqlite3ErrorMsg(pParse, "too many columns in result set");
41317d10d5a6Sdrh   }
41327d10d5a6Sdrh #endif
41337d10d5a6Sdrh   return WRC_Continue;
41347d10d5a6Sdrh }
41357d10d5a6Sdrh 
41367d10d5a6Sdrh /*
41377d10d5a6Sdrh ** No-op routine for the parse-tree walker.
41387d10d5a6Sdrh **
41397d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees
41407d10d5a6Sdrh ** are walked without any actions being taken at each node.  Presumably,
41417d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then
41427d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every
41437d10d5a6Sdrh ** subquery in the parser tree.
41447d10d5a6Sdrh */
414562c14b34Sdanielk1977 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
414662c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
41477d10d5a6Sdrh   return WRC_Continue;
41487d10d5a6Sdrh }
41497d10d5a6Sdrh 
41507d10d5a6Sdrh /*
41517d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries.
41527d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT
41537d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above.
41547d10d5a6Sdrh **
41557d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a
41567d10d5a6Sdrh ** SELECT statement.  The SELECT statement must be expanded before
41577d10d5a6Sdrh ** name resolution is performed.
41587d10d5a6Sdrh **
41597d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse.
41607d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr
41617d10d5a6Sdrh ** and/or pParse->db->mallocFailed.
41627d10d5a6Sdrh */
41637d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
41647d10d5a6Sdrh   Walker w;
4165aa87f9a6Sdrh   memset(&w, 0, sizeof(w));
41667d10d5a6Sdrh   w.xExprCallback = exprWalkNoop;
41677d10d5a6Sdrh   w.pParse = pParse;
4168d58d3278Sdrh   if( pParse->hasCompound ){
4169d58d3278Sdrh     w.xSelectCallback = convertCompoundSelectToSubquery;
41707d10d5a6Sdrh     sqlite3WalkSelect(&w, pSelect);
4171d58d3278Sdrh   }
4172c01b7306Sdrh   w.xSelectCallback = selectExpander;
4173b290f117Sdan   w.xSelectCallback2 = selectPopWith;
4174c01b7306Sdrh   sqlite3WalkSelect(&w, pSelect);
41757d10d5a6Sdrh }
41767d10d5a6Sdrh 
41777d10d5a6Sdrh 
41787d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
41797d10d5a6Sdrh /*
41807d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
41817d10d5a6Sdrh ** interface.
41827d10d5a6Sdrh **
41837d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl
41847d10d5a6Sdrh ** information to the Table structure that represents the result set
41857d10d5a6Sdrh ** of that subquery.
41867d10d5a6Sdrh **
41877d10d5a6Sdrh ** The Table structure that represents the result set was constructed
41887d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted
41897d10d5a6Sdrh ** at that point because identifiers had not yet been resolved.  This
41907d10d5a6Sdrh ** routine is called after identifier resolution.
41917d10d5a6Sdrh */
4192b290f117Sdan static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
41937d10d5a6Sdrh   Parse *pParse;
41947d10d5a6Sdrh   int i;
41957d10d5a6Sdrh   SrcList *pTabList;
41967d10d5a6Sdrh   struct SrcList_item *pFrom;
41977d10d5a6Sdrh 
41989d8b3072Sdrh   assert( p->selFlags & SF_Resolved );
41995a29d9cbSdrh   if( (p->selFlags & SF_HasTypeInfo)==0 ){
42007d10d5a6Sdrh     p->selFlags |= SF_HasTypeInfo;
42017d10d5a6Sdrh     pParse = pWalker->pParse;
42027d10d5a6Sdrh     pTabList = p->pSrc;
42037d10d5a6Sdrh     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
42047d10d5a6Sdrh       Table *pTab = pFrom->pTab;
420543152cf8Sdrh       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
42067d10d5a6Sdrh         /* A sub-query in the FROM clause of a SELECT */
42077d10d5a6Sdrh         Select *pSel = pFrom->pSelect;
42088ce7184bSdan         if( pSel ){
42097d10d5a6Sdrh           while( pSel->pPrior ) pSel = pSel->pPrior;
4210186ad8ccSdrh           selectAddColumnTypeAndCollation(pParse, pTab, pSel);
42117d10d5a6Sdrh         }
42127d10d5a6Sdrh       }
42135a29d9cbSdrh     }
42148ce7184bSdan   }
42157d10d5a6Sdrh }
42167d10d5a6Sdrh #endif
42177d10d5a6Sdrh 
42187d10d5a6Sdrh 
42197d10d5a6Sdrh /*
42207d10d5a6Sdrh ** This routine adds datatype and collating sequence information to
42217d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a
42227d10d5a6Sdrh ** SELECT statement.
42237d10d5a6Sdrh **
42247d10d5a6Sdrh ** Use this routine after name resolution.
42257d10d5a6Sdrh */
42267d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
42277d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
42287d10d5a6Sdrh   Walker w;
4229aa87f9a6Sdrh   memset(&w, 0, sizeof(w));
4230b290f117Sdan   w.xSelectCallback2 = selectAddSubqueryTypeInfo;
42317d10d5a6Sdrh   w.xExprCallback = exprWalkNoop;
42327d10d5a6Sdrh   w.pParse = pParse;
42337d10d5a6Sdrh   sqlite3WalkSelect(&w, pSelect);
42347d10d5a6Sdrh #endif
42357d10d5a6Sdrh }
42367d10d5a6Sdrh 
42377d10d5a6Sdrh 
42387d10d5a6Sdrh /*
4239030796dfSdrh ** This routine sets up a SELECT statement for processing.  The
42407d10d5a6Sdrh ** following is accomplished:
42417d10d5a6Sdrh **
42427d10d5a6Sdrh **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
42437d10d5a6Sdrh **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
42447d10d5a6Sdrh **     *  ON and USING clauses are shifted into WHERE statements
42457d10d5a6Sdrh **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
42467d10d5a6Sdrh **     *  Identifiers in expression are matched to tables.
42477d10d5a6Sdrh **
42487d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT.
42497d10d5a6Sdrh */
42507d10d5a6Sdrh void sqlite3SelectPrep(
4251b3bce662Sdanielk1977   Parse *pParse,         /* The parser context */
4252b3bce662Sdanielk1977   Select *p,             /* The SELECT statement being coded. */
42537d10d5a6Sdrh   NameContext *pOuterNC  /* Name context for container */
4254b3bce662Sdanielk1977 ){
42557d10d5a6Sdrh   sqlite3 *db;
425643152cf8Sdrh   if( NEVER(p==0) ) return;
42577d10d5a6Sdrh   db = pParse->db;
4258785097daSdrh   if( db->mallocFailed ) return;
42597d10d5a6Sdrh   if( p->selFlags & SF_HasTypeInfo ) return;
42607d10d5a6Sdrh   sqlite3SelectExpand(pParse, p);
42617d10d5a6Sdrh   if( pParse->nErr || db->mallocFailed ) return;
42627d10d5a6Sdrh   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
42637d10d5a6Sdrh   if( pParse->nErr || db->mallocFailed ) return;
42647d10d5a6Sdrh   sqlite3SelectAddTypeInfo(pParse, p);
4265f6bbe022Sdrh }
4266b3bce662Sdanielk1977 
4267b3bce662Sdanielk1977 /*
426813449892Sdrh ** Reset the aggregate accumulator.
426913449892Sdrh **
427013449892Sdrh ** The aggregate accumulator is a set of memory cells that hold
427113449892Sdrh ** intermediate results while calculating an aggregate.  This
4272030796dfSdrh ** routine generates code that stores NULLs in all of those memory
4273030796dfSdrh ** cells.
4274b3bce662Sdanielk1977 */
427513449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
427613449892Sdrh   Vdbe *v = pParse->pVdbe;
427713449892Sdrh   int i;
4278c99130fdSdrh   struct AggInfo_func *pFunc;
42797e61d18eSdrh   int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
42807e61d18eSdrh   if( nReg==0 ) return;
42817e61d18eSdrh #ifdef SQLITE_DEBUG
42827e61d18eSdrh   /* Verify that all AggInfo registers are within the range specified by
42837e61d18eSdrh   ** AggInfo.mnReg..AggInfo.mxReg */
42847e61d18eSdrh   assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
428513449892Sdrh   for(i=0; i<pAggInfo->nColumn; i++){
42867e61d18eSdrh     assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
42877e61d18eSdrh          && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
428813449892Sdrh   }
42897e61d18eSdrh   for(i=0; i<pAggInfo->nFunc; i++){
42907e61d18eSdrh     assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
42917e61d18eSdrh          && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
42927e61d18eSdrh   }
42937e61d18eSdrh #endif
42947e61d18eSdrh   sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
4295c99130fdSdrh   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
4296c99130fdSdrh     if( pFunc->iDistinct>=0 ){
4297c99130fdSdrh       Expr *pE = pFunc->pExpr;
42986ab3a2ecSdanielk1977       assert( !ExprHasProperty(pE, EP_xIsSelect) );
42996ab3a2ecSdanielk1977       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
43000daa002cSdrh         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
43010daa002cSdrh            "argument");
4302c99130fdSdrh         pFunc->iDistinct = -1;
4303c99130fdSdrh       }else{
4304fe1c6bb9Sdrh         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0);
430566a5167bSdrh         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
43062ec2fb22Sdrh                           (char*)pKeyInfo, P4_KEYINFO);
4307c99130fdSdrh       }
4308c99130fdSdrh     }
430913449892Sdrh   }
4310b3bce662Sdanielk1977 }
4311b3bce662Sdanielk1977 
4312b3bce662Sdanielk1977 /*
431313449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function
431413449892Sdrh ** in the AggInfo structure.
4315b3bce662Sdanielk1977 */
431613449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
431713449892Sdrh   Vdbe *v = pParse->pVdbe;
431813449892Sdrh   int i;
431913449892Sdrh   struct AggInfo_func *pF;
432013449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
43216ab3a2ecSdanielk1977     ExprList *pList = pF->pExpr->x.pList;
43226ab3a2ecSdanielk1977     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
432366a5167bSdrh     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
432466a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
4325b3bce662Sdanielk1977   }
432613449892Sdrh }
432713449892Sdrh 
432813449892Sdrh /*
432913449892Sdrh ** Update the accumulator memory cells for an aggregate based on
433013449892Sdrh ** the current cursor position.
433113449892Sdrh */
433213449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
433313449892Sdrh   Vdbe *v = pParse->pVdbe;
433413449892Sdrh   int i;
43357a95789cSdrh   int regHit = 0;
43367a95789cSdrh   int addrHitTest = 0;
433713449892Sdrh   struct AggInfo_func *pF;
433813449892Sdrh   struct AggInfo_col *pC;
433913449892Sdrh 
434013449892Sdrh   pAggInfo->directMode = 1;
434113449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
434213449892Sdrh     int nArg;
4343c99130fdSdrh     int addrNext = 0;
434498757157Sdrh     int regAgg;
43456ab3a2ecSdanielk1977     ExprList *pList = pF->pExpr->x.pList;
43466ab3a2ecSdanielk1977     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
434713449892Sdrh     if( pList ){
434813449892Sdrh       nArg = pList->nExpr;
4349892d3179Sdrh       regAgg = sqlite3GetTempRange(pParse, nArg);
4350d1a01edaSdrh       sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP);
435113449892Sdrh     }else{
435213449892Sdrh       nArg = 0;
435398757157Sdrh       regAgg = 0;
435413449892Sdrh     }
4355c99130fdSdrh     if( pF->iDistinct>=0 ){
4356c99130fdSdrh       addrNext = sqlite3VdbeMakeLabel(v);
4357c99130fdSdrh       assert( nArg==1 );
43582dcef11bSdrh       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
4359c99130fdSdrh     }
4360d36e1041Sdrh     if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
436113449892Sdrh       CollSeq *pColl = 0;
436213449892Sdrh       struct ExprList_item *pItem;
436313449892Sdrh       int j;
4364e82f5d04Sdrh       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
436543617e9aSdrh       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
436613449892Sdrh         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
436713449892Sdrh       }
436813449892Sdrh       if( !pColl ){
436913449892Sdrh         pColl = pParse->db->pDfltColl;
437013449892Sdrh       }
43717a95789cSdrh       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
43727a95789cSdrh       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
437313449892Sdrh     }
437498757157Sdrh     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
437566a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
4376ea678832Sdrh     sqlite3VdbeChangeP5(v, (u8)nArg);
4377da250ea5Sdrh     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
4378f49f3523Sdrh     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
4379c99130fdSdrh     if( addrNext ){
4380c99130fdSdrh       sqlite3VdbeResolveLabel(v, addrNext);
4381ceea3321Sdrh       sqlite3ExprCacheClear(pParse);
4382c99130fdSdrh     }
438313449892Sdrh   }
438467a6a40cSdan 
438567a6a40cSdan   /* Before populating the accumulator registers, clear the column cache.
438667a6a40cSdan   ** Otherwise, if any of the required column values are already present
438767a6a40cSdan   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
438867a6a40cSdan   ** to pC->iMem. But by the time the value is used, the original register
438967a6a40cSdan   ** may have been used, invalidating the underlying buffer holding the
439067a6a40cSdan   ** text or blob value. See ticket [883034dcb5].
439167a6a40cSdan   **
439267a6a40cSdan   ** Another solution would be to change the OP_SCopy used to copy cached
439367a6a40cSdan   ** values to an OP_Copy.
439467a6a40cSdan   */
43957a95789cSdrh   if( regHit ){
43967a95789cSdrh     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
43977a95789cSdrh   }
439867a6a40cSdan   sqlite3ExprCacheClear(pParse);
439913449892Sdrh   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
4400389a1adbSdrh     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
440113449892Sdrh   }
440213449892Sdrh   pAggInfo->directMode = 0;
4403ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
44047a95789cSdrh   if( addrHitTest ){
44057a95789cSdrh     sqlite3VdbeJumpHere(v, addrHitTest);
44067a95789cSdrh   }
440713449892Sdrh }
440813449892Sdrh 
4409b3bce662Sdanielk1977 /*
4410ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple
4411ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab").
4412ef7075deSdan */
4413ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN
4414ef7075deSdan static void explainSimpleCount(
4415ef7075deSdan   Parse *pParse,                  /* Parse context */
4416ef7075deSdan   Table *pTab,                    /* Table being queried */
4417ef7075deSdan   Index *pIdx                     /* Index used to optimize scan, or NULL */
4418ef7075deSdan ){
4419ef7075deSdan   if( pParse->explain==2 ){
44208a4380d7Sdrh     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
4421ef7075deSdan         pTab->zName,
4422ef7075deSdan         pIdx ? " USING COVERING INDEX " : "",
44238a4380d7Sdrh         pIdx ? pIdx->zName : ""
4424ef7075deSdan     );
4425ef7075deSdan     sqlite3VdbeAddOp4(
4426ef7075deSdan         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
4427ef7075deSdan     );
4428ef7075deSdan   }
4429ef7075deSdan }
4430ef7075deSdan #else
4431ef7075deSdan # define explainSimpleCount(a,b,c)
4432ef7075deSdan #endif
4433ef7075deSdan 
4434ef7075deSdan /*
44357d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument.
44369bb61fe7Sdrh **
4437340309fdSdrh ** The results are returned according to the SelectDest structure.
4438340309fdSdrh ** See comments in sqliteInt.h for further information.
4439e78e8284Sdrh **
44409bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
44419bb61fe7Sdrh ** encountered, then an appropriate error message is left in
44429bb61fe7Sdrh ** pParse->zErrMsg.
44439bb61fe7Sdrh **
44449bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
44459bb61fe7Sdrh ** calling function needs to do that.
44469bb61fe7Sdrh */
44474adee20fSdanielk1977 int sqlite3Select(
4448cce7d176Sdrh   Parse *pParse,         /* The parser context */
44499bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
44507d10d5a6Sdrh   SelectDest *pDest      /* What to do with the query results */
4451cce7d176Sdrh ){
445213449892Sdrh   int i, j;              /* Loop counters */
445313449892Sdrh   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
445413449892Sdrh   Vdbe *v;               /* The virtual machine under construction */
4455b3bce662Sdanielk1977   int isAgg;             /* True for select lists like "count(*)" */
4456a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
4457ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
44589bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
44599bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
44602282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
44612282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
44621d83f052Sdrh   int rc = 1;            /* Value to return from this function */
4463b9bb7c18Sdrh   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
4464e8e4af76Sdrh   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
446513449892Sdrh   AggInfo sAggInfo;      /* Information used by aggregate queries */
4466ec7429aeSdrh   int iEnd;              /* Address of the end of the query */
446717435752Sdrh   sqlite3 *db;           /* The database connection */
44689bb61fe7Sdrh 
44692ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN
44702ce22453Sdan   int iRestoreSelectId = pParse->iSelectId;
44712ce22453Sdan   pParse->iSelectId = pParse->iNextSelectId++;
44722ce22453Sdan #endif
44732ce22453Sdan 
447417435752Sdrh   db = pParse->db;
447517435752Sdrh   if( p==0 || db->mallocFailed || pParse->nErr ){
44766f7adc8aSdrh     return 1;
44776f7adc8aSdrh   }
44784adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
447913449892Sdrh   memset(&sAggInfo, 0, sizeof(sAggInfo));
4480daffd0e5Sdrh 
44816c8c8ce0Sdanielk1977   if( IgnorableOrderby(pDest) ){
44829ed1dfa8Sdanielk1977     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
44839ed1dfa8Sdanielk1977            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
4484ccfcbceaSdrh     /* If ORDER BY makes no difference in the output then neither does
4485ccfcbceaSdrh     ** DISTINCT so it can be removed too. */
4486ccfcbceaSdrh     sqlite3ExprListDelete(db, p->pOrderBy);
4487ccfcbceaSdrh     p->pOrderBy = 0;
44887d10d5a6Sdrh     p->selFlags &= ~SF_Distinct;
44899a99334dSdrh   }
44907d10d5a6Sdrh   sqlite3SelectPrep(pParse, p, 0);
4491ccfcbceaSdrh   pOrderBy = p->pOrderBy;
4492b27b7f5dSdrh   pTabList = p->pSrc;
4493b27b7f5dSdrh   pEList = p->pEList;
4494956f4319Sdanielk1977   if( pParse->nErr || db->mallocFailed ){
44959a99334dSdrh     goto select_end;
44969a99334dSdrh   }
44977d10d5a6Sdrh   isAgg = (p->selFlags & SF_Aggregate)!=0;
449843152cf8Sdrh   assert( pEList!=0 );
4499cce7d176Sdrh 
4500d820cb1bSdrh   /* Begin generating code.
4501d820cb1bSdrh   */
45024adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
4503d820cb1bSdrh   if( v==0 ) goto select_end;
4504d820cb1bSdrh 
450574b617b2Sdan   /* If writing to memory or generating a set
450674b617b2Sdan   ** only a single column may be output.
450774b617b2Sdan   */
450874b617b2Sdan #ifndef SQLITE_OMIT_SUBQUERY
450974b617b2Sdan   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
451074b617b2Sdan     goto select_end;
451174b617b2Sdan   }
451274b617b2Sdan #endif
451374b617b2Sdan 
4514d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
4515d820cb1bSdrh   */
451651522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4517f23329a2Sdanielk1977   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
451813449892Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
45191013c932Sdrh     SelectDest dest;
4520daf79acbSdanielk1977     Select *pSub = pItem->pSelect;
4521f23329a2Sdanielk1977     int isAggSub;
4522c31c2eb8Sdrh 
45235b6a9ed4Sdrh     if( pSub==0 ) continue;
452421172c4cSdrh 
452521172c4cSdrh     /* Sometimes the code for a subquery will be generated more than
452621172c4cSdrh     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
452721172c4cSdrh     ** for example.  In that case, do not regenerate the code to manifest
452821172c4cSdrh     ** a view or the co-routine to implement a view.  The first instance
452921172c4cSdrh     ** is sufficient, though the subroutine to manifest the view does need
453021172c4cSdrh     ** to be invoked again. */
45315b6a9ed4Sdrh     if( pItem->addrFillSub ){
453221172c4cSdrh       if( pItem->viaCoroutine==0 ){
45335b6a9ed4Sdrh         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
453421172c4cSdrh       }
45355b6a9ed4Sdrh       continue;
45365b6a9ed4Sdrh     }
4537daf79acbSdanielk1977 
4538fc976065Sdanielk1977     /* Increment Parse.nHeight by the height of the largest expression
4539f7b5496eSdrh     ** tree referred to by this, the parent select. The child select
4540fc976065Sdanielk1977     ** may contain expression trees of at most
4541fc976065Sdanielk1977     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
4542fc976065Sdanielk1977     ** more conservative than necessary, but much easier than enforcing
4543fc976065Sdanielk1977     ** an exact limit.
4544fc976065Sdanielk1977     */
4545fc976065Sdanielk1977     pParse->nHeight += sqlite3SelectExprHeight(p);
4546daf79acbSdanielk1977 
45477d10d5a6Sdrh     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
4548524cc21eSdanielk1977     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
45495b6a9ed4Sdrh       /* This subquery can be absorbed into its parent. */
4550f23329a2Sdanielk1977       if( isAggSub ){
45517d10d5a6Sdrh         isAgg = 1;
45527d10d5a6Sdrh         p->selFlags |= SF_Aggregate;
4553daf79acbSdanielk1977       }
4554daf79acbSdanielk1977       i = -1;
4555*ee06c99bSdrh     }else if( pTabList->nSrc==1
4556a5759677Sdrh            && OptimizationEnabled(db, SQLITE_SubqCoroutine)
4557a5759677Sdrh     ){
455821172c4cSdrh       /* Implement a co-routine that will return a single row of the result
455921172c4cSdrh       ** set on each invocation.
456021172c4cSdrh       */
456121172c4cSdrh       int addrTop;
456221172c4cSdrh       int addrEof;
456321172c4cSdrh       pItem->regReturn = ++pParse->nMem;
456421172c4cSdrh       addrEof = ++pParse->nMem;
45654b2f3589Sdan       /* Before coding the OP_Goto to jump to the start of the main routine,
45664b2f3589Sdan       ** ensure that the jump to the verify-schema routine has already
45674b2f3589Sdan       ** been coded. Otherwise, the verify-schema would likely be coded as
45684b2f3589Sdan       ** part of the co-routine. If the main routine then accessed the
45694b2f3589Sdan       ** database before invoking the co-routine for the first time (for
45704b2f3589Sdan       ** example to initialize a LIMIT register from a sub-select), it would
45714b2f3589Sdan       ** be doing so without having verified the schema version and obtained
45724b2f3589Sdan       ** the required db locks. See ticket d6b36be38.  */
45734b2f3589Sdan       sqlite3CodeVerifySchema(pParse, -1);
457421172c4cSdrh       sqlite3VdbeAddOp0(v, OP_Goto);
457521172c4cSdrh       addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
457621172c4cSdrh       sqlite3VdbeChangeP5(v, 1);
457721172c4cSdrh       VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
457821172c4cSdrh       pItem->addrFillSub = addrTop;
457921172c4cSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
458021172c4cSdrh       sqlite3VdbeChangeP5(v, 1);
458121172c4cSdrh       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
458221172c4cSdrh       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
458321172c4cSdrh       sqlite3Select(pParse, pSub, &dest);
458421172c4cSdrh       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
458521172c4cSdrh       pItem->viaCoroutine = 1;
458621172c4cSdrh       sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
458721172c4cSdrh       sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
458821172c4cSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
458921172c4cSdrh       sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
459021172c4cSdrh       VdbeComment((v, "end %s", pItem->pTab->zName));
459121172c4cSdrh       sqlite3VdbeJumpHere(v, addrTop-1);
459221172c4cSdrh       sqlite3ClearTempRegCache(pParse);
4593daf79acbSdanielk1977     }else{
45945b6a9ed4Sdrh       /* Generate a subroutine that will fill an ephemeral table with
45955b6a9ed4Sdrh       ** the content of this subquery.  pItem->addrFillSub will point
45965b6a9ed4Sdrh       ** to the address of the generated subroutine.  pItem->regReturn
45975b6a9ed4Sdrh       ** is a register allocated to hold the subroutine return address
45985b6a9ed4Sdrh       */
45997157e8eaSdrh       int topAddr;
460048f2d3b1Sdrh       int onceAddr = 0;
46017157e8eaSdrh       int retAddr;
46025b6a9ed4Sdrh       assert( pItem->addrFillSub==0 );
46035b6a9ed4Sdrh       pItem->regReturn = ++pParse->nMem;
46047157e8eaSdrh       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
46057157e8eaSdrh       pItem->addrFillSub = topAddr+1;
46067157e8eaSdrh       VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
46071d8cb21fSdan       if( pItem->isCorrelated==0 ){
4608ed17167eSdrh         /* If the subquery is not correlated and if we are not inside of
46095b6a9ed4Sdrh         ** a trigger, then we only need to compute the value of the subquery
46105b6a9ed4Sdrh         ** once. */
46111d8cb21fSdan         onceAddr = sqlite3CodeOnce(pParse);
46125b6a9ed4Sdrh       }
46131013c932Sdrh       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
4614ce7e189dSdan       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
46157d10d5a6Sdrh       sqlite3Select(pParse, pSub, &dest);
461695aa47b1Sdrh       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
461748f2d3b1Sdrh       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
46187157e8eaSdrh       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
46197157e8eaSdrh       VdbeComment((v, "end %s", pItem->pTab->zName));
46207157e8eaSdrh       sqlite3VdbeChangeP1(v, topAddr, retAddr);
4621cdc69557Sdrh       sqlite3ClearTempRegCache(pParse);
4622daf79acbSdanielk1977     }
462343152cf8Sdrh     if( /*pParse->nErr ||*/ db->mallocFailed ){
4624cfa063b3Sdrh       goto select_end;
4625cfa063b3Sdrh     }
4626fc976065Sdanielk1977     pParse->nHeight -= sqlite3SelectExprHeight(p);
4627832508b7Sdrh     pTabList = p->pSrc;
46286c8c8ce0Sdanielk1977     if( !IgnorableOrderby(pDest) ){
4629832508b7Sdrh       pOrderBy = p->pOrderBy;
4630acd4c695Sdrh     }
4631daf79acbSdanielk1977   }
4632daf79acbSdanielk1977   pEList = p->pEList;
4633daf79acbSdanielk1977 #endif
4634daf79acbSdanielk1977   pWhere = p->pWhere;
4635832508b7Sdrh   pGroupBy = p->pGroupBy;
4636832508b7Sdrh   pHaving = p->pHaving;
4637e8e4af76Sdrh   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
4638832508b7Sdrh 
4639f23329a2Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
4640f23329a2Sdanielk1977   /* If there is are a sequence of queries, do the earlier ones first.
4641f23329a2Sdanielk1977   */
4642f23329a2Sdanielk1977   if( p->pPrior ){
4643f23329a2Sdanielk1977     if( p->pRightmost==0 ){
4644f23329a2Sdanielk1977       Select *pLoop, *pRight = 0;
4645f23329a2Sdanielk1977       int cnt = 0;
4646f23329a2Sdanielk1977       int mxSelect;
4647f23329a2Sdanielk1977       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
4648f23329a2Sdanielk1977         pLoop->pRightmost = p;
4649f23329a2Sdanielk1977         pLoop->pNext = pRight;
4650f23329a2Sdanielk1977         pRight = pLoop;
4651f23329a2Sdanielk1977       }
4652f23329a2Sdanielk1977       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
4653f23329a2Sdanielk1977       if( mxSelect && cnt>mxSelect ){
4654f23329a2Sdanielk1977         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
46552ce22453Sdan         goto select_end;
4656f23329a2Sdanielk1977       }
4657f23329a2Sdanielk1977     }
46587f61e92cSdan     rc = multiSelect(pParse, p, pDest);
465917c0bc0cSdan     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
46607f61e92cSdan     return rc;
4661f23329a2Sdanielk1977   }
4662f23329a2Sdanielk1977 #endif
4663f23329a2Sdanielk1977 
46648c6f666bSdrh   /* If there is both a GROUP BY and an ORDER BY clause and they are
46658c6f666bSdrh   ** identical, then disable the ORDER BY clause since the GROUP BY
46668c6f666bSdrh   ** will cause elements to come out in the correct order.  This is
46678c6f666bSdrh   ** an optimization - the correct answer should result regardless.
46688c6f666bSdrh   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
46698c6f666bSdrh   ** to disable this optimization for testing purposes.
46708c6f666bSdrh   */
4671619a1305Sdrh   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy, -1)==0
46727e5418e4Sdrh          && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
46738c6f666bSdrh     pOrderBy = 0;
46748c6f666bSdrh   }
46758c6f666bSdrh 
467650118cdfSdan   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
467750118cdfSdan   ** if the select-list is the same as the ORDER BY list, then this query
467850118cdfSdan   ** can be rewritten as a GROUP BY. In other words, this:
467950118cdfSdan   **
468050118cdfSdan   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
468150118cdfSdan   **
468250118cdfSdan   ** is transformed to:
468350118cdfSdan   **
468450118cdfSdan   **     SELECT xyz FROM ... GROUP BY xyz
468550118cdfSdan   **
468650118cdfSdan   ** The second form is preferred as a single index (or temp-table) may be
468750118cdfSdan   ** used for both the ORDER BY and DISTINCT processing. As originally
468850118cdfSdan   ** written the query must use a temp-table for at least one of the ORDER
468950118cdfSdan   ** BY and DISTINCT, and an index or separate temp-table for the other.
469050118cdfSdan   */
469150118cdfSdan   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
4692619a1305Sdrh    && sqlite3ExprListCompare(pOrderBy, p->pEList, -1)==0
469350118cdfSdan   ){
469450118cdfSdan     p->selFlags &= ~SF_Distinct;
469550118cdfSdan     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
469650118cdfSdan     pGroupBy = p->pGroupBy;
469750118cdfSdan     pOrderBy = 0;
4698e8e4af76Sdrh     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
4699e8e4af76Sdrh     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
4700e8e4af76Sdrh     ** original setting of the SF_Distinct flag, not the current setting */
4701e8e4af76Sdrh     assert( sDistinct.isTnct );
470250118cdfSdan   }
470350118cdfSdan 
47048b4c40d8Sdrh   /* If there is an ORDER BY clause, then this sorting
47058b4c40d8Sdrh   ** index might end up being unused if the data can be
47069d2985c7Sdrh   ** extracted in pre-sorted order.  If that is the case, then the
4707b9bb7c18Sdrh   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
47089d2985c7Sdrh   ** we figure out that the sorting index is not needed.  The addrSortIndex
47099d2985c7Sdrh   ** variable is used to facilitate that change.
47107cedc8d4Sdanielk1977   */
47117cedc8d4Sdanielk1977   if( pOrderBy ){
47120342b1f5Sdrh     KeyInfo *pKeyInfo;
4713fe1c6bb9Sdrh     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy, 0);
47149d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
4715b9bb7c18Sdrh     p->addrOpenEphm[2] = addrSortIndex =
471666a5167bSdrh       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
471766a5167bSdrh                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
47182ec2fb22Sdrh                            (char*)pKeyInfo, P4_KEYINFO);
47199d2985c7Sdrh   }else{
47209d2985c7Sdrh     addrSortIndex = -1;
47217cedc8d4Sdanielk1977   }
47227cedc8d4Sdanielk1977 
47232d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
47242d0794e3Sdrh   */
47256c8c8ce0Sdanielk1977   if( pDest->eDest==SRT_EphemTab ){
47262b596da8Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
47272d0794e3Sdrh   }
47282d0794e3Sdrh 
4729f42bacc2Sdrh   /* Set the limiter.
4730f42bacc2Sdrh   */
4731f42bacc2Sdrh   iEnd = sqlite3VdbeMakeLabel(v);
4732c63367efSdrh   p->nSelectRow = LARGEST_INT64;
4733f42bacc2Sdrh   computeLimitRegisters(pParse, p, iEnd);
4734c6aff30cSdrh   if( p->iLimit==0 && addrSortIndex>=0 ){
4735c6aff30cSdrh     sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
4736c6aff30cSdrh     p->selFlags |= SF_UseSorter;
4737c6aff30cSdrh   }
4738f42bacc2Sdrh 
4739dece1a84Sdrh   /* Open a virtual index to use for the distinct set.
4740cce7d176Sdrh   */
47412ce22453Sdan   if( p->selFlags & SF_Distinct ){
4742e8e4af76Sdrh     sDistinct.tabTnct = pParse->nTab++;
4743e8e4af76Sdrh     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
4744e8e4af76Sdrh                                 sDistinct.tabTnct, 0, 0,
4745fe1c6bb9Sdrh                                 (char*)keyInfoFromExprList(pParse, p->pEList, 0),
47462ec2fb22Sdrh                                 P4_KEYINFO);
4747d4187c71Sdrh     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
4748e8e4af76Sdrh     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
4749832508b7Sdrh   }else{
4750e8e4af76Sdrh     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
4751efb7251dSdrh   }
4752832508b7Sdrh 
475313449892Sdrh   if( !isAgg && pGroupBy==0 ){
4754e8e4af76Sdrh     /* No aggregate functions and no GROUP BY clause */
47556457a353Sdrh     u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
475638cc40c2Sdan 
475738cc40c2Sdan     /* Begin the database scan. */
47586457a353Sdrh     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, p->pEList,
47596457a353Sdrh                                wctrlFlags, 0);
47601d83f052Sdrh     if( pWInfo==0 ) goto select_end;
47616f32848dSdrh     if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
47626f32848dSdrh       p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
47636f32848dSdrh     }
47646457a353Sdrh     if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
47656f32848dSdrh       sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
47666f32848dSdrh     }
47676f32848dSdrh     if( pOrderBy && sqlite3WhereIsOrdered(pWInfo) ) pOrderBy = 0;
4768cce7d176Sdrh 
4769b9bb7c18Sdrh     /* If sorting index that was created by a prior OP_OpenEphemeral
4770b9bb7c18Sdrh     ** instruction ended up not being needed, then change the OP_OpenEphemeral
47719d2985c7Sdrh     ** into an OP_Noop.
47729d2985c7Sdrh     */
47739d2985c7Sdrh     if( addrSortIndex>=0 && pOrderBy==0 ){
477448f2d3b1Sdrh       sqlite3VdbeChangeToNoop(v, addrSortIndex);
4775b9bb7c18Sdrh       p->addrOpenEphm[2] = -1;
47769d2985c7Sdrh     }
47779d2985c7Sdrh 
477838cc40c2Sdan     /* Use the standard inner loop. */
4779340309fdSdrh     selectInnerLoop(pParse, p, pEList, -1, pOrderBy, &sDistinct, pDest,
47806f32848dSdrh                     sqlite3WhereContinueLabel(pWInfo),
47816f32848dSdrh                     sqlite3WhereBreakLabel(pWInfo));
47822282792aSdrh 
4783cce7d176Sdrh     /* End the database scan loop.
4784cce7d176Sdrh     */
47854adee20fSdanielk1977     sqlite3WhereEnd(pWInfo);
478613449892Sdrh   }else{
4787e8e4af76Sdrh     /* This case when there exist aggregate functions or a GROUP BY clause
4788e8e4af76Sdrh     ** or both */
478913449892Sdrh     NameContext sNC;    /* Name context for processing aggregate information */
479013449892Sdrh     int iAMem;          /* First Mem address for storing current GROUP BY */
479113449892Sdrh     int iBMem;          /* First Mem address for previous GROUP BY */
479213449892Sdrh     int iUseFlag;       /* Mem address holding flag indicating that at least
479313449892Sdrh                         ** one row of the input to the aggregator has been
479413449892Sdrh                         ** processed */
479513449892Sdrh     int iAbortFlag;     /* Mem address which causes query abort if positive */
479613449892Sdrh     int groupBySort;    /* Rows come from source in GROUP BY order */
4797d176611bSdrh     int addrEnd;        /* End of processing for this SELECT */
47981c9d835dSdrh     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
47991c9d835dSdrh     int sortOut = 0;    /* Output register from the sorter */
4800d176611bSdrh 
4801d176611bSdrh     /* Remove any and all aliases between the result set and the
4802d176611bSdrh     ** GROUP BY clause.
4803d176611bSdrh     */
4804d176611bSdrh     if( pGroupBy ){
4805dc5ea5c7Sdrh       int k;                        /* Loop counter */
4806d176611bSdrh       struct ExprList_item *pItem;  /* For looping over expression in a list */
4807d176611bSdrh 
4808dc5ea5c7Sdrh       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
4809c2acc4e4Sdrh         pItem->u.x.iAlias = 0;
4810d176611bSdrh       }
4811dc5ea5c7Sdrh       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
4812c2acc4e4Sdrh         pItem->u.x.iAlias = 0;
4813d176611bSdrh       }
4814c63367efSdrh       if( p->nSelectRow>100 ) p->nSelectRow = 100;
481595aa47b1Sdrh     }else{
4816c63367efSdrh       p->nSelectRow = 1;
4817d176611bSdrh     }
4818cce7d176Sdrh 
481913449892Sdrh 
4820d176611bSdrh     /* Create a label to jump to when we want to abort the query */
482113449892Sdrh     addrEnd = sqlite3VdbeMakeLabel(v);
482213449892Sdrh 
482313449892Sdrh     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
482413449892Sdrh     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
482513449892Sdrh     ** SELECT statement.
48262282792aSdrh     */
482713449892Sdrh     memset(&sNC, 0, sizeof(sNC));
482813449892Sdrh     sNC.pParse = pParse;
482913449892Sdrh     sNC.pSrcList = pTabList;
483013449892Sdrh     sNC.pAggInfo = &sAggInfo;
48317e61d18eSdrh     sAggInfo.mnReg = pParse->nMem+1;
483213449892Sdrh     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
48339d2985c7Sdrh     sAggInfo.pGroupBy = pGroupBy;
4834d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pEList);
4835d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
4836d2b3e23bSdrh     if( pHaving ){
4837d2b3e23bSdrh       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
483813449892Sdrh     }
483913449892Sdrh     sAggInfo.nAccumulator = sAggInfo.nColumn;
484013449892Sdrh     for(i=0; i<sAggInfo.nFunc; i++){
48416ab3a2ecSdanielk1977       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
48423a8c4be7Sdrh       sNC.ncFlags |= NC_InAggFunc;
48436ab3a2ecSdanielk1977       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
48443a8c4be7Sdrh       sNC.ncFlags &= ~NC_InAggFunc;
484513449892Sdrh     }
48467e61d18eSdrh     sAggInfo.mxReg = pParse->nMem;
484717435752Sdrh     if( db->mallocFailed ) goto select_end;
484813449892Sdrh 
484913449892Sdrh     /* Processing for aggregates with GROUP BY is very different and
48503c4809a2Sdanielk1977     ** much more complex than aggregates without a GROUP BY.
485113449892Sdrh     */
485213449892Sdrh     if( pGroupBy ){
485313449892Sdrh       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
4854d176611bSdrh       int j1;             /* A-vs-B comparision jump */
4855d176611bSdrh       int addrOutputRow;  /* Start of subroutine that outputs a result row */
4856d176611bSdrh       int regOutputRow;   /* Return address register for output subroutine */
4857d176611bSdrh       int addrSetAbort;   /* Set the abort flag and return */
4858d176611bSdrh       int addrTopOfLoop;  /* Top of the input loop */
4859d176611bSdrh       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
4860d176611bSdrh       int addrReset;      /* Subroutine for resetting the accumulator */
4861d176611bSdrh       int regReset;       /* Return address register for reset subroutine */
486213449892Sdrh 
486313449892Sdrh       /* If there is a GROUP BY clause we might need a sorting index to
486413449892Sdrh       ** implement it.  Allocate that sorting index now.  If it turns out
48651c9d835dSdrh       ** that we do not need it after all, the OP_SorterOpen instruction
486613449892Sdrh       ** will be converted into a Noop.
486713449892Sdrh       */
486813449892Sdrh       sAggInfo.sortingIdx = pParse->nTab++;
4869fe1c6bb9Sdrh       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0);
48701c9d835dSdrh       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
4871cd3e8f7cSdanielk1977           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
48722ec2fb22Sdrh           0, (char*)pKeyInfo, P4_KEYINFO);
487313449892Sdrh 
487413449892Sdrh       /* Initialize memory locations used by GROUP BY aggregate processing
487513449892Sdrh       */
48760a07c107Sdrh       iUseFlag = ++pParse->nMem;
48770a07c107Sdrh       iAbortFlag = ++pParse->nMem;
4878d176611bSdrh       regOutputRow = ++pParse->nMem;
4879d176611bSdrh       addrOutputRow = sqlite3VdbeMakeLabel(v);
4880d176611bSdrh       regReset = ++pParse->nMem;
4881d176611bSdrh       addrReset = sqlite3VdbeMakeLabel(v);
48820a07c107Sdrh       iAMem = pParse->nMem + 1;
488313449892Sdrh       pParse->nMem += pGroupBy->nExpr;
48840a07c107Sdrh       iBMem = pParse->nMem + 1;
488513449892Sdrh       pParse->nMem += pGroupBy->nExpr;
48864c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
4887d4e70ebdSdrh       VdbeComment((v, "clear abort flag"));
48884c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
4889d4e70ebdSdrh       VdbeComment((v, "indicate accumulator empty"));
4890b8475df8Sdrh       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
4891e313382eSdrh 
489213449892Sdrh       /* Begin a loop that will extract all source rows in GROUP BY order.
489313449892Sdrh       ** This might involve two separate loops with an OP_Sort in between, or
489413449892Sdrh       ** it might be a single loop that uses an index to extract information
489513449892Sdrh       ** in the right order to begin with.
489613449892Sdrh       */
48972eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
489893ec45d5Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
489993ec45d5Sdrh                                  WHERE_GROUPBY, 0);
49005360ad34Sdrh       if( pWInfo==0 ) goto select_end;
49016f32848dSdrh       if( sqlite3WhereIsOrdered(pWInfo) ){
490213449892Sdrh         /* The optimizer is able to deliver rows in group by order so
4903b9bb7c18Sdrh         ** we do not have to sort.  The OP_OpenEphemeral table will be
490413449892Sdrh         ** cancelled later because we still need to use the pKeyInfo
490513449892Sdrh         */
490613449892Sdrh         groupBySort = 0;
490713449892Sdrh       }else{
490813449892Sdrh         /* Rows are coming out in undetermined order.  We have to push
490913449892Sdrh         ** each row into a sorting index, terminate the first loop,
491013449892Sdrh         ** then loop over the sorting index in order to get the output
491113449892Sdrh         ** in sorted order
491213449892Sdrh         */
4913892d3179Sdrh         int regBase;
4914892d3179Sdrh         int regRecord;
4915892d3179Sdrh         int nCol;
4916892d3179Sdrh         int nGroupBy;
4917892d3179Sdrh 
49182ce22453Sdan         explainTempTable(pParse,
4919e8e4af76Sdrh             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
4920e8e4af76Sdrh                     "DISTINCT" : "GROUP BY");
49212ce22453Sdan 
492213449892Sdrh         groupBySort = 1;
4923892d3179Sdrh         nGroupBy = pGroupBy->nExpr;
4924892d3179Sdrh         nCol = nGroupBy + 1;
4925892d3179Sdrh         j = nGroupBy+1;
492613449892Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
4927892d3179Sdrh           if( sAggInfo.aCol[i].iSorterColumn>=j ){
4928892d3179Sdrh             nCol++;
492913449892Sdrh             j++;
493013449892Sdrh           }
4931892d3179Sdrh         }
4932892d3179Sdrh         regBase = sqlite3GetTempRange(pParse, nCol);
4933ceea3321Sdrh         sqlite3ExprCacheClear(pParse);
4934191b54cbSdrh         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
4935892d3179Sdrh         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
4936892d3179Sdrh         j = nGroupBy+1;
4937892d3179Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
4938892d3179Sdrh           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
4939892d3179Sdrh           if( pCol->iSorterColumn>=j ){
4940e55cbd72Sdrh             int r1 = j + regBase;
49416a012f04Sdrh             int r2;
4942701bb3b4Sdrh 
49436a012f04Sdrh             r2 = sqlite3ExprCodeGetColumn(pParse,
4944a748fdccSdrh                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
49456a012f04Sdrh             if( r1!=r2 ){
49466a012f04Sdrh               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
49476a012f04Sdrh             }
49486a012f04Sdrh             j++;
4949892d3179Sdrh           }
4950892d3179Sdrh         }
4951892d3179Sdrh         regRecord = sqlite3GetTempReg(pParse);
49521db639ceSdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
49531c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
4954892d3179Sdrh         sqlite3ReleaseTempReg(pParse, regRecord);
4955892d3179Sdrh         sqlite3ReleaseTempRange(pParse, regBase, nCol);
495613449892Sdrh         sqlite3WhereEnd(pWInfo);
49575134d135Sdan         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
49581c9d835dSdrh         sortOut = sqlite3GetTempReg(pParse);
49591c9d835dSdrh         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
49601c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
4961d4e70ebdSdrh         VdbeComment((v, "GROUP BY sort"));
496213449892Sdrh         sAggInfo.useSortingIdx = 1;
4963ceea3321Sdrh         sqlite3ExprCacheClear(pParse);
496413449892Sdrh       }
496513449892Sdrh 
496613449892Sdrh       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
496713449892Sdrh       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
496813449892Sdrh       ** Then compare the current GROUP BY terms against the GROUP BY terms
496913449892Sdrh       ** from the previous row currently stored in a0, a1, a2...
497013449892Sdrh       */
497113449892Sdrh       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
4972ceea3321Sdrh       sqlite3ExprCacheClear(pParse);
49731c9d835dSdrh       if( groupBySort ){
49741c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
49751c9d835dSdrh       }
497613449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
497713449892Sdrh         if( groupBySort ){
49781c9d835dSdrh           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
49791c9d835dSdrh           if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
498013449892Sdrh         }else{
498113449892Sdrh           sAggInfo.directMode = 1;
49822dcef11bSdrh           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
498313449892Sdrh         }
498413449892Sdrh       }
498516ee60ffSdrh       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
49862ec2fb22Sdrh                           (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
498716ee60ffSdrh       j1 = sqlite3VdbeCurrentAddr(v);
498816ee60ffSdrh       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
498913449892Sdrh 
499013449892Sdrh       /* Generate code that runs whenever the GROUP BY changes.
4991e00ee6ebSdrh       ** Changes in the GROUP BY are detected by the previous code
499213449892Sdrh       ** block.  If there were no changes, this block is skipped.
499313449892Sdrh       **
499413449892Sdrh       ** This code copies current group by terms in b0,b1,b2,...
499513449892Sdrh       ** over to a0,a1,a2.  It then calls the output subroutine
499613449892Sdrh       ** and resets the aggregate accumulator registers in preparation
499713449892Sdrh       ** for the next GROUP BY batch.
499813449892Sdrh       */
4999b21e7c70Sdrh       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
50002eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
5001d4e70ebdSdrh       VdbeComment((v, "output one row"));
50023c84ddffSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
5003d4e70ebdSdrh       VdbeComment((v, "check abort flag"));
50042eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
5005d4e70ebdSdrh       VdbeComment((v, "reset accumulator"));
500613449892Sdrh 
500713449892Sdrh       /* Update the aggregate accumulators based on the content of
500813449892Sdrh       ** the current row
500913449892Sdrh       */
501016ee60ffSdrh       sqlite3VdbeJumpHere(v, j1);
501113449892Sdrh       updateAccumulator(pParse, &sAggInfo);
50124c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
5013d4e70ebdSdrh       VdbeComment((v, "indicate data in accumulator"));
501413449892Sdrh 
501513449892Sdrh       /* End of the loop
501613449892Sdrh       */
501713449892Sdrh       if( groupBySort ){
50181c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
501913449892Sdrh       }else{
502013449892Sdrh         sqlite3WhereEnd(pWInfo);
502148f2d3b1Sdrh         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
502213449892Sdrh       }
502313449892Sdrh 
502413449892Sdrh       /* Output the final row of result
502513449892Sdrh       */
50262eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
5027d4e70ebdSdrh       VdbeComment((v, "output final row"));
502813449892Sdrh 
5029d176611bSdrh       /* Jump over the subroutines
5030d176611bSdrh       */
5031d176611bSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
5032d176611bSdrh 
5033d176611bSdrh       /* Generate a subroutine that outputs a single row of the result
5034d176611bSdrh       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
5035d176611bSdrh       ** is less than or equal to zero, the subroutine is a no-op.  If
5036d176611bSdrh       ** the processing calls for the query to abort, this subroutine
5037d176611bSdrh       ** increments the iAbortFlag memory location before returning in
5038d176611bSdrh       ** order to signal the caller to abort.
5039d176611bSdrh       */
5040d176611bSdrh       addrSetAbort = sqlite3VdbeCurrentAddr(v);
5041d176611bSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
5042d176611bSdrh       VdbeComment((v, "set abort flag"));
5043d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5044d176611bSdrh       sqlite3VdbeResolveLabel(v, addrOutputRow);
5045d176611bSdrh       addrOutputRow = sqlite3VdbeCurrentAddr(v);
5046d176611bSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
5047d176611bSdrh       VdbeComment((v, "Groupby result generator entry point"));
5048d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5049d176611bSdrh       finalizeAggFunctions(pParse, &sAggInfo);
5050d176611bSdrh       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
5051340309fdSdrh       selectInnerLoop(pParse, p, p->pEList, -1, pOrderBy,
5052e8e4af76Sdrh                       &sDistinct, pDest,
5053d176611bSdrh                       addrOutputRow+1, addrSetAbort);
5054d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5055d176611bSdrh       VdbeComment((v, "end groupby result generator"));
5056d176611bSdrh 
5057d176611bSdrh       /* Generate a subroutine that will reset the group-by accumulator
5058d176611bSdrh       */
5059d176611bSdrh       sqlite3VdbeResolveLabel(v, addrReset);
5060d176611bSdrh       resetAccumulator(pParse, &sAggInfo);
5061d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regReset);
5062d176611bSdrh 
506343152cf8Sdrh     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
506413449892Sdrh     else {
5065dba0137eSdanielk1977       ExprList *pDel = 0;
5066a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT
5067a5533162Sdanielk1977       Table *pTab;
5068a5533162Sdanielk1977       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
5069a5533162Sdanielk1977         /* If isSimpleCount() returns a pointer to a Table structure, then
5070a5533162Sdanielk1977         ** the SQL statement is of the form:
5071a5533162Sdanielk1977         **
5072a5533162Sdanielk1977         **   SELECT count(*) FROM <tbl>
5073a5533162Sdanielk1977         **
5074a5533162Sdanielk1977         ** where the Table structure returned represents table <tbl>.
5075a5533162Sdanielk1977         **
5076a5533162Sdanielk1977         ** This statement is so common that it is optimized specially. The
5077a5533162Sdanielk1977         ** OP_Count instruction is executed either on the intkey table that
5078a5533162Sdanielk1977         ** contains the data for table <tbl> or on one of its indexes. It
5079a5533162Sdanielk1977         ** is better to execute the op on an index, as indexes are almost
5080a5533162Sdanielk1977         ** always spread across less pages than their corresponding tables.
5081a5533162Sdanielk1977         */
5082a5533162Sdanielk1977         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
5083a5533162Sdanielk1977         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
5084a5533162Sdanielk1977         Index *pIdx;                         /* Iterator variable */
5085a5533162Sdanielk1977         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
5086a5533162Sdanielk1977         Index *pBest = 0;                    /* Best index found so far */
5087a5533162Sdanielk1977         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
5088a9d1ccb9Sdanielk1977 
5089a5533162Sdanielk1977         sqlite3CodeVerifySchema(pParse, iDb);
5090a5533162Sdanielk1977         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
5091a5533162Sdanielk1977 
5092d9e3cad2Sdrh         /* Search for the index that has the lowest scan cost.
5093a5533162Sdanielk1977         **
50943e9548b3Sdrh         ** (2011-04-15) Do not do a full scan of an unordered index.
50953e9548b3Sdrh         **
5096abcc1941Sdrh         ** (2013-10-03) Do not count the entries in a partial index.
50975f33f375Sdrh         **
5098a5533162Sdanielk1977         ** In practice the KeyInfo structure will not be used. It is only
5099a5533162Sdanielk1977         ** passed to keep OP_OpenRead happy.
5100a5533162Sdanielk1977         */
51015c7917e4Sdrh         if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
5102a5533162Sdanielk1977         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
5103d9e3cad2Sdrh           if( pIdx->bUnordered==0
5104e13e9f54Sdrh            && pIdx->szIdxRow<pTab->szTabRow
5105d3037a41Sdrh            && pIdx->pPartIdxWhere==0
5106e13e9f54Sdrh            && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
5107d9e3cad2Sdrh           ){
5108a5533162Sdanielk1977             pBest = pIdx;
5109a5533162Sdanielk1977           }
5110a5533162Sdanielk1977         }
5111d9e3cad2Sdrh         if( pBest ){
5112a5533162Sdanielk1977           iRoot = pBest->tnum;
51132ec2fb22Sdrh           pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
5114a5533162Sdanielk1977         }
5115a5533162Sdanielk1977 
5116a5533162Sdanielk1977         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
5117261c02d9Sdrh         sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
5118a5533162Sdanielk1977         if( pKeyInfo ){
51192ec2fb22Sdrh           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
5120a5533162Sdanielk1977         }
5121a5533162Sdanielk1977         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
5122a5533162Sdanielk1977         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
5123ef7075deSdan         explainSimpleCount(pParse, pTab, pBest);
5124a5533162Sdanielk1977       }else
5125a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */
5126a5533162Sdanielk1977       {
5127738bdcfbSdanielk1977         /* Check if the query is of one of the following forms:
5128738bdcfbSdanielk1977         **
5129738bdcfbSdanielk1977         **   SELECT min(x) FROM ...
5130738bdcfbSdanielk1977         **   SELECT max(x) FROM ...
5131738bdcfbSdanielk1977         **
5132738bdcfbSdanielk1977         ** If it is, then ask the code in where.c to attempt to sort results
5133738bdcfbSdanielk1977         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
5134738bdcfbSdanielk1977         ** If where.c is able to produce results sorted in this order, then
5135738bdcfbSdanielk1977         ** add vdbe code to break out of the processing loop after the
5136738bdcfbSdanielk1977         ** first iteration (since the first iteration of the loop is
5137738bdcfbSdanielk1977         ** guaranteed to operate on the row with the minimum or maximum
5138738bdcfbSdanielk1977         ** value of x, the only row required).
5139738bdcfbSdanielk1977         **
5140738bdcfbSdanielk1977         ** A special flag must be passed to sqlite3WhereBegin() to slightly
514148864df9Smistachkin         ** modify behavior as follows:
5142738bdcfbSdanielk1977         **
5143738bdcfbSdanielk1977         **   + If the query is a "SELECT min(x)", then the loop coded by
5144738bdcfbSdanielk1977         **     where.c should not iterate over any values with a NULL value
5145738bdcfbSdanielk1977         **     for x.
5146738bdcfbSdanielk1977         **
5147738bdcfbSdanielk1977         **   + The optimizer code in where.c (the thing that decides which
5148738bdcfbSdanielk1977         **     index or indices to use) should place a different priority on
5149738bdcfbSdanielk1977         **     satisfying the 'ORDER BY' clause than it does in other cases.
5150738bdcfbSdanielk1977         **     Refer to code and comments in where.c for details.
5151738bdcfbSdanielk1977         */
5152a5533162Sdanielk1977         ExprList *pMinMax = 0;
51534ac391fcSdan         u8 flag = WHERE_ORDERBY_NORMAL;
51544ac391fcSdan 
51554ac391fcSdan         assert( p->pGroupBy==0 );
51564ac391fcSdan         assert( flag==0 );
51574ac391fcSdan         if( p->pHaving==0 ){
51584ac391fcSdan           flag = minMaxQuery(&sAggInfo, &pMinMax);
51594ac391fcSdan         }
51604ac391fcSdan         assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
51614ac391fcSdan 
5162a9d1ccb9Sdanielk1977         if( flag ){
51634ac391fcSdan           pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
51646ab3a2ecSdanielk1977           pDel = pMinMax;
51650e359b30Sdrh           if( pMinMax && !db->mallocFailed ){
5166ea678832Sdrh             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
5167a9d1ccb9Sdanielk1977             pMinMax->a[0].pExpr->op = TK_COLUMN;
5168a9d1ccb9Sdanielk1977           }
51691013c932Sdrh         }
5170a9d1ccb9Sdanielk1977 
517113449892Sdrh         /* This case runs if the aggregate has no GROUP BY clause.  The
517213449892Sdrh         ** processing is much simpler since there is only a single row
517313449892Sdrh         ** of output.
517413449892Sdrh         */
517513449892Sdrh         resetAccumulator(pParse, &sAggInfo);
517646ec5b63Sdrh         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
5177dba0137eSdanielk1977         if( pWInfo==0 ){
5178633e6d57Sdrh           sqlite3ExprListDelete(db, pDel);
5179dba0137eSdanielk1977           goto select_end;
5180dba0137eSdanielk1977         }
518113449892Sdrh         updateAccumulator(pParse, &sAggInfo);
518246c35f9bSdrh         assert( pMinMax==0 || pMinMax->nExpr==1 );
51836f32848dSdrh         if( sqlite3WhereIsOrdered(pWInfo) ){
51846f32848dSdrh           sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
5185a5533162Sdanielk1977           VdbeComment((v, "%s() by index",
5186a5533162Sdanielk1977                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
5187a9d1ccb9Sdanielk1977         }
518813449892Sdrh         sqlite3WhereEnd(pWInfo);
518913449892Sdrh         finalizeAggFunctions(pParse, &sAggInfo);
51907a895a80Sdanielk1977       }
51917a895a80Sdanielk1977 
519213449892Sdrh       pOrderBy = 0;
519335573356Sdrh       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
5194340309fdSdrh       selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
5195a9671a22Sdrh                       pDest, addrEnd, addrEnd);
5196633e6d57Sdrh       sqlite3ExprListDelete(db, pDel);
519713449892Sdrh     }
519813449892Sdrh     sqlite3VdbeResolveLabel(v, addrEnd);
519913449892Sdrh 
520013449892Sdrh   } /* endif aggregate query */
52012282792aSdrh 
5202e8e4af76Sdrh   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
52032ce22453Sdan     explainTempTable(pParse, "DISTINCT");
52042ce22453Sdan   }
52052ce22453Sdan 
5206cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
5207cce7d176Sdrh   ** and send them to the callback one by one.
5208cce7d176Sdrh   */
5209cce7d176Sdrh   if( pOrderBy ){
52102ce22453Sdan     explainTempTable(pParse, "ORDER BY");
52116c8c8ce0Sdanielk1977     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
5212cce7d176Sdrh   }
52136a535340Sdrh 
5214ec7429aeSdrh   /* Jump here to skip this query
5215ec7429aeSdrh   */
5216ec7429aeSdrh   sqlite3VdbeResolveLabel(v, iEnd);
5217ec7429aeSdrh 
52181d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
52191d83f052Sdrh   ** to indicate no errors.
52201d83f052Sdrh   */
52211d83f052Sdrh   rc = 0;
52221d83f052Sdrh 
52231d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
52241d83f052Sdrh   ** successful coding of the SELECT.
52251d83f052Sdrh   */
52261d83f052Sdrh select_end:
522717c0bc0cSdan   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
5228955de52cSdanielk1977 
52297d10d5a6Sdrh   /* Identify column names if results of the SELECT are to be output.
5230955de52cSdanielk1977   */
52317d10d5a6Sdrh   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
5232955de52cSdanielk1977     generateColumnNames(pParse, pTabList, pEList);
5233955de52cSdanielk1977   }
5234955de52cSdanielk1977 
5235633e6d57Sdrh   sqlite3DbFree(db, sAggInfo.aCol);
5236633e6d57Sdrh   sqlite3DbFree(db, sAggInfo.aFunc);
52371d83f052Sdrh   return rc;
5238cce7d176Sdrh }
5239485f0039Sdrh 
5240678a9aa7Sdrh #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
5241485f0039Sdrh /*
52427e02e5e6Sdrh ** Generate a human-readable description of a the Select object.
5243485f0039Sdrh */
5244a84203a0Sdrh static void explainOneSelect(Vdbe *pVdbe, Select *p){
52457e02e5e6Sdrh   sqlite3ExplainPrintf(pVdbe, "SELECT ");
52464e2a9c32Sdrh   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
52474e2a9c32Sdrh     if( p->selFlags & SF_Distinct ){
52484e2a9c32Sdrh       sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
5249485f0039Sdrh     }
52504e2a9c32Sdrh     if( p->selFlags & SF_Aggregate ){
52514e2a9c32Sdrh       sqlite3ExplainPrintf(pVdbe, "agg_flag ");
5252485f0039Sdrh     }
52534e2a9c32Sdrh     sqlite3ExplainNL(pVdbe);
52544e2a9c32Sdrh     sqlite3ExplainPrintf(pVdbe, "   ");
5255485f0039Sdrh   }
52567e02e5e6Sdrh   sqlite3ExplainExprList(pVdbe, p->pEList);
52577e02e5e6Sdrh   sqlite3ExplainNL(pVdbe);
52587e02e5e6Sdrh   if( p->pSrc && p->pSrc->nSrc ){
5259485f0039Sdrh     int i;
52607e02e5e6Sdrh     sqlite3ExplainPrintf(pVdbe, "FROM ");
52617e02e5e6Sdrh     sqlite3ExplainPush(pVdbe);
5262485f0039Sdrh     for(i=0; i<p->pSrc->nSrc; i++){
5263485f0039Sdrh       struct SrcList_item *pItem = &p->pSrc->a[i];
526404b8342bSdrh       sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
5265485f0039Sdrh       if( pItem->pSelect ){
52667e02e5e6Sdrh         sqlite3ExplainSelect(pVdbe, pItem->pSelect);
5267485f0039Sdrh         if( pItem->pTab ){
526804b8342bSdrh           sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
526904b8342bSdrh         }
5270485f0039Sdrh       }else if( pItem->zName ){
52717e02e5e6Sdrh         sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
5272485f0039Sdrh       }
5273485f0039Sdrh       if( pItem->zAlias ){
527404b8342bSdrh         sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
5275485f0039Sdrh       }
5276a84203a0Sdrh       if( pItem->jointype & JT_LEFT ){
5277a84203a0Sdrh         sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
5278485f0039Sdrh       }
52797e02e5e6Sdrh       sqlite3ExplainNL(pVdbe);
5280485f0039Sdrh     }
52817e02e5e6Sdrh     sqlite3ExplainPop(pVdbe);
5282485f0039Sdrh   }
5283485f0039Sdrh   if( p->pWhere ){
52847e02e5e6Sdrh     sqlite3ExplainPrintf(pVdbe, "WHERE ");
52857e02e5e6Sdrh     sqlite3ExplainExpr(pVdbe, p->pWhere);
52867e02e5e6Sdrh     sqlite3ExplainNL(pVdbe);
5287485f0039Sdrh   }
5288485f0039Sdrh   if( p->pGroupBy ){
52897e02e5e6Sdrh     sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
52907e02e5e6Sdrh     sqlite3ExplainExprList(pVdbe, p->pGroupBy);
52917e02e5e6Sdrh     sqlite3ExplainNL(pVdbe);
5292485f0039Sdrh   }
5293485f0039Sdrh   if( p->pHaving ){
52947e02e5e6Sdrh     sqlite3ExplainPrintf(pVdbe, "HAVING ");
52957e02e5e6Sdrh     sqlite3ExplainExpr(pVdbe, p->pHaving);
52967e02e5e6Sdrh     sqlite3ExplainNL(pVdbe);
5297485f0039Sdrh   }
5298485f0039Sdrh   if( p->pOrderBy ){
52997e02e5e6Sdrh     sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
53007e02e5e6Sdrh     sqlite3ExplainExprList(pVdbe, p->pOrderBy);
53017e02e5e6Sdrh     sqlite3ExplainNL(pVdbe);
5302485f0039Sdrh   }
5303a84203a0Sdrh   if( p->pLimit ){
5304a84203a0Sdrh     sqlite3ExplainPrintf(pVdbe, "LIMIT ");
5305a84203a0Sdrh     sqlite3ExplainExpr(pVdbe, p->pLimit);
5306a84203a0Sdrh     sqlite3ExplainNL(pVdbe);
5307a84203a0Sdrh   }
5308a84203a0Sdrh   if( p->pOffset ){
5309a84203a0Sdrh     sqlite3ExplainPrintf(pVdbe, "OFFSET ");
5310a84203a0Sdrh     sqlite3ExplainExpr(pVdbe, p->pOffset);
5311a84203a0Sdrh     sqlite3ExplainNL(pVdbe);
5312485f0039Sdrh   }
5313485f0039Sdrh }
5314a84203a0Sdrh void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
5315a84203a0Sdrh   if( p==0 ){
5316a84203a0Sdrh     sqlite3ExplainPrintf(pVdbe, "(null-select)");
5317a84203a0Sdrh     return;
5318a84203a0Sdrh   }
531947f2239fSdrh   while( p->pPrior ){
532047f2239fSdrh     p->pPrior->pNext = p;
532147f2239fSdrh     p = p->pPrior;
532247f2239fSdrh   }
5323a84203a0Sdrh   sqlite3ExplainPush(pVdbe);
5324a84203a0Sdrh   while( p ){
5325a84203a0Sdrh     explainOneSelect(pVdbe, p);
5326a84203a0Sdrh     p = p->pNext;
5327a84203a0Sdrh     if( p==0 ) break;
5328a84203a0Sdrh     sqlite3ExplainNL(pVdbe);
5329a84203a0Sdrh     sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
5330a84203a0Sdrh   }
53317e02e5e6Sdrh   sqlite3ExplainPrintf(pVdbe, "END");
5332a84203a0Sdrh   sqlite3ExplainPop(pVdbe);
5333485f0039Sdrh }
53347e02e5e6Sdrh 
5335485f0039Sdrh /* End of the structure debug printing code
5336485f0039Sdrh *****************************************************************************/
533714a55b71Smistachkin #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
5338