xref: /sqlite-3.40.0/src/select.c (revision 9ca33fa4)
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 
17079a3072Sdrh /*
18abd4c723Sdrh ** Trace output macros
19abd4c723Sdrh */
20abd4c723Sdrh #if SELECTTRACE_ENABLED
21abd4c723Sdrh /***/ int sqlite3SelectTrace = 0;
22eb9b884cSdrh # define SELECTTRACE(K,P,S,X)  \
23eb9b884cSdrh   if(sqlite3SelectTrace&(K))   \
2438b4149cSdrh     sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
2538b4149cSdrh         (S)->zSelName,(S)),\
26eb9b884cSdrh     sqlite3DebugPrintf X
27abd4c723Sdrh #else
28eb9b884cSdrh # define SELECTTRACE(K,P,S,X)
29abd4c723Sdrh #endif
30abd4c723Sdrh 
31315555caSdrh 
32cce7d176Sdrh /*
33079a3072Sdrh ** An instance of the following object is used to record information about
34079a3072Sdrh ** how to process the DISTINCT keyword, to simplify passing that information
35079a3072Sdrh ** into the selectInnerLoop() routine.
36eda639e1Sdrh */
37079a3072Sdrh typedef struct DistinctCtx DistinctCtx;
38079a3072Sdrh struct DistinctCtx {
39079a3072Sdrh   u8 isTnct;      /* True if the DISTINCT keyword is present */
40079a3072Sdrh   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
41079a3072Sdrh   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
42079a3072Sdrh   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
43079a3072Sdrh };
44079a3072Sdrh 
45079a3072Sdrh /*
46079a3072Sdrh ** An instance of the following object is used to record information about
47079a3072Sdrh ** the ORDER BY (or GROUP BY) clause of query is being coded.
48079a3072Sdrh */
49079a3072Sdrh typedef struct SortCtx SortCtx;
50079a3072Sdrh struct SortCtx {
51079a3072Sdrh   ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
52079a3072Sdrh   int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
53079a3072Sdrh   int iECursor;         /* Cursor number for the sorter */
54079a3072Sdrh   int regReturn;        /* Register holding block-output return address */
55079a3072Sdrh   int labelBkOut;       /* Start label for the block-output subroutine */
56079a3072Sdrh   int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
57079a3072Sdrh   u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
58079a3072Sdrh };
59079a3072Sdrh #define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
60cce7d176Sdrh 
61cce7d176Sdrh /*
62b87fbed5Sdrh ** Delete all the content of a Select structure.  Deallocate the structure
63b87fbed5Sdrh ** itself only if bFree is true.
64eda639e1Sdrh */
65b87fbed5Sdrh static void clearSelect(sqlite3 *db, Select *p, int bFree){
66b87fbed5Sdrh   while( p ){
67b87fbed5Sdrh     Select *pPrior = p->pPrior;
68633e6d57Sdrh     sqlite3ExprListDelete(db, p->pEList);
69633e6d57Sdrh     sqlite3SrcListDelete(db, p->pSrc);
70633e6d57Sdrh     sqlite3ExprDelete(db, p->pWhere);
71633e6d57Sdrh     sqlite3ExprListDelete(db, p->pGroupBy);
72633e6d57Sdrh     sqlite3ExprDelete(db, p->pHaving);
73633e6d57Sdrh     sqlite3ExprListDelete(db, p->pOrderBy);
74633e6d57Sdrh     sqlite3ExprDelete(db, p->pLimit);
75633e6d57Sdrh     sqlite3ExprDelete(db, p->pOffset);
764e9119d9Sdan     sqlite3WithDelete(db, p->pWith);
77b87fbed5Sdrh     if( bFree ) sqlite3DbFree(db, p);
78b87fbed5Sdrh     p = pPrior;
79b87fbed5Sdrh     bFree = 1;
80b87fbed5Sdrh   }
81eda639e1Sdrh }
82eda639e1Sdrh 
831013c932Sdrh /*
841013c932Sdrh ** Initialize a SelectDest structure.
851013c932Sdrh */
861013c932Sdrh void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
87ea678832Sdrh   pDest->eDest = (u8)eDest;
882b596da8Sdrh   pDest->iSDParm = iParm;
892b596da8Sdrh   pDest->affSdst = 0;
902b596da8Sdrh   pDest->iSdst = 0;
912b596da8Sdrh   pDest->nSdst = 0;
921013c932Sdrh }
931013c932Sdrh 
94eda639e1Sdrh 
95eda639e1Sdrh /*
969bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that
979bb61fe7Sdrh ** structure.
98cce7d176Sdrh */
994adee20fSdanielk1977 Select *sqlite3SelectNew(
10017435752Sdrh   Parse *pParse,        /* Parsing context */
101daffd0e5Sdrh   ExprList *pEList,     /* which columns to include in the result */
102ad3cab52Sdrh   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
103daffd0e5Sdrh   Expr *pWhere,         /* the WHERE clause */
104daffd0e5Sdrh   ExprList *pGroupBy,   /* the GROUP BY clause */
105daffd0e5Sdrh   Expr *pHaving,        /* the HAVING clause */
106daffd0e5Sdrh   ExprList *pOrderBy,   /* the ORDER BY clause */
107832ee3d4Sdrh   u16 selFlags,         /* Flag parameters, such as SF_Distinct */
108a2dc3b1aSdanielk1977   Expr *pLimit,         /* LIMIT value.  NULL means not used */
109a2dc3b1aSdanielk1977   Expr *pOffset         /* OFFSET value.  NULL means no offset */
1109bb61fe7Sdrh ){
1119bb61fe7Sdrh   Select *pNew;
112eda639e1Sdrh   Select standin;
11317435752Sdrh   sqlite3 *db = pParse->db;
114ca3862dcSdrh   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
115daffd0e5Sdrh   if( pNew==0 ){
116338ec3e1Sdrh     assert( db->mallocFailed );
117eda639e1Sdrh     pNew = &standin;
118eda639e1Sdrh   }
119b733d037Sdrh   if( pEList==0 ){
1201a1d3cd2Sdrh     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ASTERISK,0));
121b733d037Sdrh   }
1229bb61fe7Sdrh   pNew->pEList = pEList;
123ca3862dcSdrh   pNew->op = TK_SELECT;
124ca3862dcSdrh   pNew->selFlags = selFlags;
125ca3862dcSdrh   pNew->iLimit = 0;
126ca3862dcSdrh   pNew->iOffset = 0;
127*9ca33fa4Sdrh #if SELECTTRACE_ENABLED
128*9ca33fa4Sdrh   pNew->zSelName[0] = 0;
129*9ca33fa4Sdrh #endif
130ca3862dcSdrh   pNew->addrOpenEphm[0] = -1;
131ca3862dcSdrh   pNew->addrOpenEphm[1] = -1;
132ca3862dcSdrh   pNew->nSelectRow = 0;
1337b113babSdrh   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
1349bb61fe7Sdrh   pNew->pSrc = pSrc;
1359bb61fe7Sdrh   pNew->pWhere = pWhere;
1369bb61fe7Sdrh   pNew->pGroupBy = pGroupBy;
1379bb61fe7Sdrh   pNew->pHaving = pHaving;
1389bb61fe7Sdrh   pNew->pOrderBy = pOrderBy;
139ca3862dcSdrh   pNew->pPrior = 0;
140ca3862dcSdrh   pNew->pNext = 0;
141a2dc3b1aSdanielk1977   pNew->pLimit = pLimit;
142a2dc3b1aSdanielk1977   pNew->pOffset = pOffset;
143ca3862dcSdrh   pNew->pWith = 0;
144b8289a8bSdrh   assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
1450a846f96Sdrh   if( db->mallocFailed ) {
146b87fbed5Sdrh     clearSelect(db, pNew, pNew!=&standin);
147eda639e1Sdrh     pNew = 0;
148a464c234Sdrh   }else{
149a464c234Sdrh     assert( pNew->pSrc!=0 || pParse->nErr>0 );
150daffd0e5Sdrh   }
151338ec3e1Sdrh   assert( pNew!=&standin );
1529bb61fe7Sdrh   return pNew;
1539bb61fe7Sdrh }
1549bb61fe7Sdrh 
155eb9b884cSdrh #if SELECTTRACE_ENABLED
156eb9b884cSdrh /*
157eb9b884cSdrh ** Set the name of a Select object
158eb9b884cSdrh */
159eb9b884cSdrh void sqlite3SelectSetName(Select *p, const char *zName){
160eb9b884cSdrh   if( p && zName ){
161eb9b884cSdrh     sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
162eb9b884cSdrh   }
163eb9b884cSdrh }
164eb9b884cSdrh #endif
165eb9b884cSdrh 
166eb9b884cSdrh 
1679bb61fe7Sdrh /*
168eda639e1Sdrh ** Delete the given Select structure and all of its substructures.
169eda639e1Sdrh */
170633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){
171b87fbed5Sdrh   clearSelect(db, p, 1);
172eda639e1Sdrh }
173eda639e1Sdrh 
174eda639e1Sdrh /*
175d227a291Sdrh ** Return a pointer to the right-most SELECT statement in a compound.
176d227a291Sdrh */
177d227a291Sdrh static Select *findRightmost(Select *p){
178d227a291Sdrh   while( p->pNext ) p = p->pNext;
179d227a291Sdrh   return p;
1809bb61fe7Sdrh }
1819bb61fe7Sdrh 
1829bb61fe7Sdrh /*
183f7b5496eSdrh ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
18401f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
18501f3f253Sdrh ** in terms of the following bit values:
18601f3f253Sdrh **
18701f3f253Sdrh **     JT_INNER
1883dec223cSdrh **     JT_CROSS
18901f3f253Sdrh **     JT_OUTER
19001f3f253Sdrh **     JT_NATURAL
19101f3f253Sdrh **     JT_LEFT
19201f3f253Sdrh **     JT_RIGHT
19301f3f253Sdrh **
19401f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
19501f3f253Sdrh **
19601f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
19701f3f253Sdrh ** a join type, but put an error in the pParse structure.
19801f3f253Sdrh */
1994adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
20001f3f253Sdrh   int jointype = 0;
20101f3f253Sdrh   Token *apAll[3];
20201f3f253Sdrh   Token *p;
203373cc2ddSdrh                              /*   0123456789 123456789 123456789 123 */
204373cc2ddSdrh   static const char zKeyText[] = "naturaleftouterightfullinnercross";
2055719628aSdrh   static const struct {
206373cc2ddSdrh     u8 i;        /* Beginning of keyword text in zKeyText[] */
207373cc2ddSdrh     u8 nChar;    /* Length of the keyword in characters */
208373cc2ddSdrh     u8 code;     /* Join type mask */
209373cc2ddSdrh   } aKeyword[] = {
210373cc2ddSdrh     /* natural */ { 0,  7, JT_NATURAL                },
211373cc2ddSdrh     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
212373cc2ddSdrh     /* outer   */ { 10, 5, JT_OUTER                  },
213373cc2ddSdrh     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
214373cc2ddSdrh     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
215373cc2ddSdrh     /* inner   */ { 23, 5, JT_INNER                  },
216373cc2ddSdrh     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
21701f3f253Sdrh   };
21801f3f253Sdrh   int i, j;
21901f3f253Sdrh   apAll[0] = pA;
22001f3f253Sdrh   apAll[1] = pB;
22101f3f253Sdrh   apAll[2] = pC;
222195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
22301f3f253Sdrh     p = apAll[i];
224373cc2ddSdrh     for(j=0; j<ArraySize(aKeyword); j++){
225373cc2ddSdrh       if( p->n==aKeyword[j].nChar
226373cc2ddSdrh           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
227373cc2ddSdrh         jointype |= aKeyword[j].code;
22801f3f253Sdrh         break;
22901f3f253Sdrh       }
23001f3f253Sdrh     }
231373cc2ddSdrh     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
232373cc2ddSdrh     if( j>=ArraySize(aKeyword) ){
23301f3f253Sdrh       jointype |= JT_ERROR;
23401f3f253Sdrh       break;
23501f3f253Sdrh     }
23601f3f253Sdrh   }
237ad2d8307Sdrh   if(
238ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
239195e6967Sdrh      (jointype & JT_ERROR)!=0
240ad2d8307Sdrh   ){
241a9671a22Sdrh     const char *zSp = " ";
242a9671a22Sdrh     assert( pB!=0 );
243a9671a22Sdrh     if( pC==0 ){ zSp++; }
244ae29ffbeSdrh     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
245a9671a22Sdrh        "%T %T%s%T", pA, pB, zSp, pC);
24601f3f253Sdrh     jointype = JT_INNER;
247373cc2ddSdrh   }else if( (jointype & JT_OUTER)!=0
248373cc2ddSdrh          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
2494adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
250da93d238Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported");
251195e6967Sdrh     jointype = JT_INNER;
25201f3f253Sdrh   }
25301f3f253Sdrh   return jointype;
25401f3f253Sdrh }
25501f3f253Sdrh 
25601f3f253Sdrh /*
257ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
258ad2d8307Sdrh ** is not contained in the table.
259ad2d8307Sdrh */
260ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
261ad2d8307Sdrh   int i;
262ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
2634adee20fSdanielk1977     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
264ad2d8307Sdrh   }
265ad2d8307Sdrh   return -1;
266ad2d8307Sdrh }
267ad2d8307Sdrh 
268ad2d8307Sdrh /*
2692179b434Sdrh ** Search the first N tables in pSrc, from left to right, looking for a
2702179b434Sdrh ** table that has a column named zCol.
2712179b434Sdrh **
2722179b434Sdrh ** When found, set *piTab and *piCol to the table index and column index
2732179b434Sdrh ** of the matching column and return TRUE.
2742179b434Sdrh **
2752179b434Sdrh ** If not found, return FALSE.
2762179b434Sdrh */
2772179b434Sdrh static int tableAndColumnIndex(
2782179b434Sdrh   SrcList *pSrc,       /* Array of tables to search */
2792179b434Sdrh   int N,               /* Number of tables in pSrc->a[] to search */
2802179b434Sdrh   const char *zCol,    /* Name of the column we are looking for */
2812179b434Sdrh   int *piTab,          /* Write index of pSrc->a[] here */
2822179b434Sdrh   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
2832179b434Sdrh ){
2842179b434Sdrh   int i;               /* For looping over tables in pSrc */
2852179b434Sdrh   int iCol;            /* Index of column matching zCol */
2862179b434Sdrh 
2872179b434Sdrh   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
2882179b434Sdrh   for(i=0; i<N; i++){
2892179b434Sdrh     iCol = columnIndex(pSrc->a[i].pTab, zCol);
2902179b434Sdrh     if( iCol>=0 ){
2912179b434Sdrh       if( piTab ){
2922179b434Sdrh         *piTab = i;
2932179b434Sdrh         *piCol = iCol;
2942179b434Sdrh       }
2952179b434Sdrh       return 1;
2962179b434Sdrh     }
2972179b434Sdrh   }
2982179b434Sdrh   return 0;
2992179b434Sdrh }
3002179b434Sdrh 
3012179b434Sdrh /*
302f7b0b0adSdan ** This function is used to add terms implied by JOIN syntax to the
303f7b0b0adSdan ** WHERE clause expression of a SELECT statement. The new term, which
304f7b0b0adSdan ** is ANDed with the existing WHERE clause, is of the form:
305f7b0b0adSdan **
306f7b0b0adSdan **    (tab1.col1 = tab2.col2)
307f7b0b0adSdan **
308f7b0b0adSdan ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
309f7b0b0adSdan ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
310f7b0b0adSdan ** column iColRight of tab2.
311ad2d8307Sdrh */
312ad2d8307Sdrh static void addWhereTerm(
31317435752Sdrh   Parse *pParse,                  /* Parsing context */
314f7b0b0adSdan   SrcList *pSrc,                  /* List of tables in FROM clause */
3152179b434Sdrh   int iLeft,                      /* Index of first table to join in pSrc */
316f7b0b0adSdan   int iColLeft,                   /* Index of column in first table */
3172179b434Sdrh   int iRight,                     /* Index of second table in pSrc */
318f7b0b0adSdan   int iColRight,                  /* Index of column in second table */
319f7b0b0adSdan   int isOuterJoin,                /* True if this is an OUTER join */
320f7b0b0adSdan   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
321ad2d8307Sdrh ){
322f7b0b0adSdan   sqlite3 *db = pParse->db;
323f7b0b0adSdan   Expr *pE1;
324f7b0b0adSdan   Expr *pE2;
325f7b0b0adSdan   Expr *pEq;
326ad2d8307Sdrh 
3272179b434Sdrh   assert( iLeft<iRight );
3282179b434Sdrh   assert( pSrc->nSrc>iRight );
3292179b434Sdrh   assert( pSrc->a[iLeft].pTab );
3302179b434Sdrh   assert( pSrc->a[iRight].pTab );
331f7b0b0adSdan 
3322179b434Sdrh   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
3332179b434Sdrh   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
334f7b0b0adSdan 
335f7b0b0adSdan   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
336f7b0b0adSdan   if( pEq && isOuterJoin ){
337f7b0b0adSdan     ExprSetProperty(pEq, EP_FromJoin);
338c5cd1249Sdrh     assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
339ebb6a65dSdrh     ExprSetVVAProperty(pEq, EP_NoReduce);
340f7b0b0adSdan     pEq->iRightJoinTable = (i16)pE2->iTable;
341030530deSdrh   }
342f7b0b0adSdan   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
343ad2d8307Sdrh }
344ad2d8307Sdrh 
345ad2d8307Sdrh /*
3461f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
34722d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the
34822d6a53aSdrh ** expression.
3491cc093c2Sdrh **
350e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
3511cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
3521f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
3531f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
3541f16230bSdrh ** WHERE clause during join processing but we need to remember that they
3551f16230bSdrh ** originated in the ON or USING clause.
35622d6a53aSdrh **
35722d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the
35822d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not
35922d6a53aSdrh ** explicitly mentioned in the expression.  That information is needed
36022d6a53aSdrh ** for cases like this:
36122d6a53aSdrh **
36222d6a53aSdrh **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
36322d6a53aSdrh **
36422d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5
36522d6a53aSdrh ** term until after the t2 loop of the join.  In that way, a
36622d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
36722d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately
36822d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in
36922d6a53aSdrh ** the output, which is incorrect.
3701cc093c2Sdrh */
37122d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){
3721cc093c2Sdrh   while( p ){
3731f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
374c5cd1249Sdrh     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
375ebb6a65dSdrh     ExprSetVVAProperty(p, EP_NoReduce);
376cf697396Sshane     p->iRightJoinTable = (i16)iTable;
377606f2344Sdrh     if( p->op==TK_FUNCTION && p->x.pList ){
378606f2344Sdrh       int i;
379606f2344Sdrh       for(i=0; i<p->x.pList->nExpr; i++){
380606f2344Sdrh         setJoinExpr(p->x.pList->a[i].pExpr, iTable);
381606f2344Sdrh       }
382606f2344Sdrh     }
38322d6a53aSdrh     setJoinExpr(p->pLeft, iTable);
3841cc093c2Sdrh     p = p->pRight;
3851cc093c2Sdrh   }
3861cc093c2Sdrh }
3871cc093c2Sdrh 
3881cc093c2Sdrh /*
389ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
390ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
391ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
392ad2d8307Sdrh **
39391bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure.
39491bb0eedSdrh ** The left most table is the first entry in Select.pSrc.  The right-most
39591bb0eedSdrh ** table is the last entry.  The join operator is held in the entry to
39691bb0eedSdrh ** the left.  Thus entry 0 contains the join operator for the join between
39791bb0eedSdrh ** entries 0 and 1.  Any ON or USING clauses associated with the join are
39891bb0eedSdrh ** also attached to the left entry.
39991bb0eedSdrh **
400ad2d8307Sdrh ** This routine returns the number of errors encountered.
401ad2d8307Sdrh */
402ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
40391bb0eedSdrh   SrcList *pSrc;                  /* All tables in the FROM clause */
40491bb0eedSdrh   int i, j;                       /* Loop counters */
40591bb0eedSdrh   struct SrcList_item *pLeft;     /* Left table being joined */
40691bb0eedSdrh   struct SrcList_item *pRight;    /* Right table being joined */
407ad2d8307Sdrh 
40891bb0eedSdrh   pSrc = p->pSrc;
40991bb0eedSdrh   pLeft = &pSrc->a[0];
41091bb0eedSdrh   pRight = &pLeft[1];
41191bb0eedSdrh   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
41291bb0eedSdrh     Table *pLeftTab = pLeft->pTab;
41391bb0eedSdrh     Table *pRightTab = pRight->pTab;
414ad27e761Sdrh     int isOuter;
41591bb0eedSdrh 
4161c767f0dSdrh     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
4178a48b9c0Sdrh     isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
418ad2d8307Sdrh 
419ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
420ad2d8307Sdrh     ** every column that the two tables have in common.
421ad2d8307Sdrh     */
4228a48b9c0Sdrh     if( pRight->fg.jointype & JT_NATURAL ){
42361dfc31dSdrh       if( pRight->pOn || pRight->pUsing ){
4244adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
425ad2d8307Sdrh            "an ON or USING clause", 0);
426ad2d8307Sdrh         return 1;
427ad2d8307Sdrh       }
4282179b434Sdrh       for(j=0; j<pRightTab->nCol; j++){
4292179b434Sdrh         char *zName;   /* Name of column in the right table */
4302179b434Sdrh         int iLeft;     /* Matching left table */
4312179b434Sdrh         int iLeftCol;  /* Matching column in the left table */
4322179b434Sdrh 
4332179b434Sdrh         zName = pRightTab->aCol[j].zName;
4342179b434Sdrh         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
4352179b434Sdrh           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
4362179b434Sdrh                        isOuter, &p->pWhere);
437ad2d8307Sdrh         }
438ad2d8307Sdrh       }
439ad2d8307Sdrh     }
440ad2d8307Sdrh 
441ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
442ad2d8307Sdrh     */
44361dfc31dSdrh     if( pRight->pOn && pRight->pUsing ){
4444adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
445da93d238Sdrh         "clauses in the same join");
446ad2d8307Sdrh       return 1;
447ad2d8307Sdrh     }
448ad2d8307Sdrh 
449ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
45091bb0eedSdrh     ** an AND operator.
451ad2d8307Sdrh     */
45261dfc31dSdrh     if( pRight->pOn ){
453ad27e761Sdrh       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
45417435752Sdrh       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
45561dfc31dSdrh       pRight->pOn = 0;
456ad2d8307Sdrh     }
457ad2d8307Sdrh 
458ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
459ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
460ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
461ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
462ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
463ad2d8307Sdrh     ** not contained in both tables to be joined.
464ad2d8307Sdrh     */
46561dfc31dSdrh     if( pRight->pUsing ){
46661dfc31dSdrh       IdList *pList = pRight->pUsing;
467ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
4682179b434Sdrh         char *zName;     /* Name of the term in the USING clause */
4692179b434Sdrh         int iLeft;       /* Table on the left with matching column name */
4702179b434Sdrh         int iLeftCol;    /* Column number of matching column on the left */
4712179b434Sdrh         int iRightCol;   /* Column number of matching column on the right */
4722179b434Sdrh 
4732179b434Sdrh         zName = pList->a[j].zName;
4742179b434Sdrh         iRightCol = columnIndex(pRightTab, zName);
4752179b434Sdrh         if( iRightCol<0
4762179b434Sdrh          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
4772179b434Sdrh         ){
4784adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
47991bb0eedSdrh             "not present in both tables", zName);
480ad2d8307Sdrh           return 1;
481ad2d8307Sdrh         }
4822179b434Sdrh         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
4832179b434Sdrh                      isOuter, &p->pWhere);
484ad2d8307Sdrh       }
485ad2d8307Sdrh     }
486ad2d8307Sdrh   }
487ad2d8307Sdrh   return 0;
488ad2d8307Sdrh }
489ad2d8307Sdrh 
490079a3072Sdrh /* Forward reference */
491079a3072Sdrh static KeyInfo *keyInfoFromExprList(
492079a3072Sdrh   Parse *pParse,       /* Parsing context */
493079a3072Sdrh   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
494079a3072Sdrh   int iStart,          /* Begin with this column of pList */
495079a3072Sdrh   int nExtra           /* Add this many extra columns to the end */
496079a3072Sdrh );
497079a3072Sdrh 
498ad2d8307Sdrh /*
499f45f2326Sdrh ** Generate code that will push the record in registers regData
500f45f2326Sdrh ** through regData+nData-1 onto the sorter.
501c926afbcSdrh */
502d59ba6ceSdrh static void pushOntoSorter(
503d59ba6ceSdrh   Parse *pParse,         /* Parser context */
504079a3072Sdrh   SortCtx *pSort,        /* Information about the ORDER BY clause */
505b7654111Sdrh   Select *pSelect,       /* The whole SELECT statement */
506f45f2326Sdrh   int regData,           /* First register holding data to be sorted */
5075579d59fSdrh   int regOrigData,       /* First register holding data before packing */
508fd0a2f97Sdrh   int nData,             /* Number of elements in the data array */
509fd0a2f97Sdrh   int nPrefixReg         /* No. of reg prior to regData available for use */
510d59ba6ceSdrh ){
511f45f2326Sdrh   Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
51278d58432Sdan   int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
513f45f2326Sdrh   int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
51478d58432Sdan   int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
515fd0a2f97Sdrh   int regBase;                                     /* Regs for sorter record */
516fb0d6e56Sdrh   int regRecord = ++pParse->nMem;                  /* Assembled sorter record */
51778d58432Sdan   int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
518f45f2326Sdrh   int op;                            /* Opcode to add sorter record to sorter */
519f45f2326Sdrh 
52078d58432Sdan   assert( bSeq==0 || bSeq==1 );
5215579d59fSdrh   assert( nData==1 || regData==regOrigData );
522fd0a2f97Sdrh   if( nPrefixReg ){
52378d58432Sdan     assert( nPrefixReg==nExpr+bSeq );
52478d58432Sdan     regBase = regData - nExpr - bSeq;
525fd0a2f97Sdrh   }else{
526fb0d6e56Sdrh     regBase = pParse->nMem + 1;
527fb0d6e56Sdrh     pParse->nMem += nBase;
528fd0a2f97Sdrh   }
5295579d59fSdrh   sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
5305579d59fSdrh                           SQLITE_ECEL_DUP|SQLITE_ECEL_REF);
53178d58432Sdan   if( bSeq ){
532079a3072Sdrh     sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
533fd0a2f97Sdrh   }
53478d58432Sdan   if( nPrefixReg==0 ){
535236241aeSdrh     sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
53678d58432Sdan   }
53778d58432Sdan 
538f45f2326Sdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
539079a3072Sdrh   if( nOBSat>0 ){
540079a3072Sdrh     int regPrevKey;   /* The first nOBSat columns of the previous row */
541079a3072Sdrh     int addrFirst;    /* Address of the OP_IfNot opcode */
542079a3072Sdrh     int addrJmp;      /* Address of the OP_Jump opcode */
543079a3072Sdrh     VdbeOp *pOp;      /* Opcode that opens the sorter */
544079a3072Sdrh     int nKey;         /* Number of sorting key columns, including OP_Sequence */
545dbfca2b7Sdrh     KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
546079a3072Sdrh 
54726d7e7c6Sdrh     regPrevKey = pParse->nMem+1;
54826d7e7c6Sdrh     pParse->nMem += pSort->nOBSat;
54978d58432Sdan     nKey = nExpr - pSort->nOBSat + bSeq;
55078d58432Sdan     if( bSeq ){
55178d58432Sdan       addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
55278d58432Sdan     }else{
55378d58432Sdan       addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
55478d58432Sdan     }
55578d58432Sdan     VdbeCoverage(v);
55626d7e7c6Sdrh     sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
557079a3072Sdrh     pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
55859b8f2e1Sdrh     if( pParse->db->mallocFailed ) return;
559fb0d6e56Sdrh     pOp->p2 = nKey + nData;
560dbfca2b7Sdrh     pKI = pOp->p4.pKeyInfo;
561dbfca2b7Sdrh     memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
562dbfca2b7Sdrh     sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
563fe201effSdrh     testcase( pKI->nXField>2 );
564fe201effSdrh     pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
565fe201effSdrh                                            pKI->nXField-1);
566079a3072Sdrh     addrJmp = sqlite3VdbeCurrentAddr(v);
567079a3072Sdrh     sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
568079a3072Sdrh     pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
569079a3072Sdrh     pSort->regReturn = ++pParse->nMem;
570079a3072Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
57165ea12cbSdrh     sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
572079a3072Sdrh     sqlite3VdbeJumpHere(v, addrFirst);
573236241aeSdrh     sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
574079a3072Sdrh     sqlite3VdbeJumpHere(v, addrJmp);
575079a3072Sdrh   }
576079a3072Sdrh   if( pSort->sortFlags & SORTFLAG_UseSorter ){
577c6aff30cSdrh     op = OP_SorterInsert;
578c6aff30cSdrh   }else{
579c6aff30cSdrh     op = OP_IdxInsert;
580c6aff30cSdrh   }
581079a3072Sdrh   sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
58292b01d53Sdrh   if( pSelect->iLimit ){
58316897072Sdrh     int addr;
584b7654111Sdrh     int iLimit;
5850acb7e48Sdrh     if( pSelect->iOffset ){
586b7654111Sdrh       iLimit = pSelect->iOffset+1;
587b7654111Sdrh     }else{
588b7654111Sdrh       iLimit = pSelect->iLimit;
589b7654111Sdrh     }
5908b0cf38aSdrh     addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v);
591079a3072Sdrh     sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
592079a3072Sdrh     sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
59316897072Sdrh     sqlite3VdbeJumpHere(v, addr);
594d59ba6ceSdrh   }
595c926afbcSdrh }
596c926afbcSdrh 
597c926afbcSdrh /*
598ec7429aeSdrh ** Add code to implement the OFFSET
599ea48eb2eSdrh */
600ec7429aeSdrh static void codeOffset(
601bab39e13Sdrh   Vdbe *v,          /* Generate code into this VM */
602aa9ce707Sdrh   int iOffset,      /* Register holding the offset counter */
603b7654111Sdrh   int iContinue     /* Jump here to skip the current record */
604ea48eb2eSdrh ){
605a22a75e5Sdrh   if( iOffset>0 ){
6068b0cf38aSdrh     sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
6078b0cf38aSdrh     VdbeComment((v, "OFFSET"));
608ea48eb2eSdrh   }
609ea48eb2eSdrh }
610ea48eb2eSdrh 
611ea48eb2eSdrh /*
61298757157Sdrh ** Add code that will check to make sure the N registers starting at iMem
61398757157Sdrh ** form a distinct entry.  iTab is a sorting index that holds previously
614a2a49dc9Sdrh ** seen combinations of the N values.  A new entry is made in iTab
615a2a49dc9Sdrh ** if the current N values are new.
616a2a49dc9Sdrh **
617a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the
618a2a49dc9Sdrh ** stack if the top N elements are not distinct.
619a2a49dc9Sdrh */
620a2a49dc9Sdrh static void codeDistinct(
6212dcef11bSdrh   Parse *pParse,     /* Parsing and code generating context */
622a2a49dc9Sdrh   int iTab,          /* A sorting index used to test for distinctness */
623a2a49dc9Sdrh   int addrRepeat,    /* Jump to here if not distinct */
624477df4b3Sdrh   int N,             /* Number of elements */
625a2a49dc9Sdrh   int iMem           /* First element */
626a2a49dc9Sdrh ){
6272dcef11bSdrh   Vdbe *v;
6282dcef11bSdrh   int r1;
6292dcef11bSdrh 
6302dcef11bSdrh   v = pParse->pVdbe;
6312dcef11bSdrh   r1 = sqlite3GetTempReg(pParse);
632688852abSdrh   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
6331db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
6342dcef11bSdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
6352dcef11bSdrh   sqlite3ReleaseTempReg(pParse, r1);
636a2a49dc9Sdrh }
637a2a49dc9Sdrh 
638bb7dd683Sdrh #ifndef SQLITE_OMIT_SUBQUERY
639a2a49dc9Sdrh /*
640e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression
641e305f43fSdrh ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
642bb7dd683Sdrh ** column.  We do this in a subroutine because the error used to occur
643bb7dd683Sdrh ** in multiple places.  (The error only occurs in one place now, but we
644bb7dd683Sdrh ** retain the subroutine to minimize code disruption.)
645e305f43fSdrh */
6466c8c8ce0Sdanielk1977 static int checkForMultiColumnSelectError(
6476c8c8ce0Sdanielk1977   Parse *pParse,       /* Parse context. */
6486c8c8ce0Sdanielk1977   SelectDest *pDest,   /* Destination of SELECT results */
6496c8c8ce0Sdanielk1977   int nExpr            /* Number of result columns returned by SELECT */
6506c8c8ce0Sdanielk1977 ){
6516c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
652e305f43fSdrh   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
653e305f43fSdrh     sqlite3ErrorMsg(pParse, "only a single result allowed for "
654e305f43fSdrh        "a SELECT that is part of an expression");
655e305f43fSdrh     return 1;
656e305f43fSdrh   }else{
657e305f43fSdrh     return 0;
658e305f43fSdrh   }
659e305f43fSdrh }
660bb7dd683Sdrh #endif
661c99130fdSdrh 
662c99130fdSdrh /*
6632282792aSdrh ** This routine generates the code for the inside of the inner loop
6642282792aSdrh ** of a SELECT.
66582c3d636Sdrh **
666340309fdSdrh ** If srcTab is negative, then the pEList expressions
667340309fdSdrh ** are evaluated in order to get the data for this row.  If srcTab is
668340309fdSdrh ** zero or more, then data is pulled from srcTab and pEList is used only
669340309fdSdrh ** to get number columns and the datatype for each column.
6702282792aSdrh */
671d2b3e23bSdrh static void selectInnerLoop(
6722282792aSdrh   Parse *pParse,          /* The parser context */
673df199a25Sdrh   Select *p,              /* The complete select statement being coded */
6742282792aSdrh   ExprList *pEList,       /* List of values being extracted */
67582c3d636Sdrh   int srcTab,             /* Pull data from this table */
676079a3072Sdrh   SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
677e8e4af76Sdrh   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
6786c8c8ce0Sdanielk1977   SelectDest *pDest,      /* How to dispose of the results */
6792282792aSdrh   int iContinue,          /* Jump here to continue with next row */
680a9671a22Sdrh   int iBreak              /* Jump here to break out of the inner loop */
6812282792aSdrh ){
6822282792aSdrh   Vdbe *v = pParse->pVdbe;
683d847eaadSdrh   int i;
684ea48eb2eSdrh   int hasDistinct;        /* True if the DISTINCT keyword is present */
685d847eaadSdrh   int regResult;              /* Start of memory holding result set */
686d847eaadSdrh   int eDest = pDest->eDest;   /* How to dispose of results */
6872b596da8Sdrh   int iParm = pDest->iSDParm; /* First argument to disposal method */
688d847eaadSdrh   int nResultCol;             /* Number of result columns */
689fd0a2f97Sdrh   int nPrefixReg = 0;         /* Number of extra registers before regResult */
69038640e15Sdrh 
6911c767f0dSdrh   assert( v );
69238640e15Sdrh   assert( pEList!=0 );
693e8e4af76Sdrh   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
694079a3072Sdrh   if( pSort && pSort->pOrderBy==0 ) pSort = 0;
695079a3072Sdrh   if( pSort==0 && !hasDistinct ){
696a22a75e5Sdrh     assert( iContinue!=0 );
697aa9ce707Sdrh     codeOffset(v, p->iOffset, iContinue);
698df199a25Sdrh   }
699df199a25Sdrh 
700967e8b73Sdrh   /* Pull the requested columns.
7012282792aSdrh   */
702d847eaadSdrh   nResultCol = pEList->nExpr;
70305a86c5cSdrh 
7042b596da8Sdrh   if( pDest->iSdst==0 ){
705fd0a2f97Sdrh     if( pSort ){
70678d58432Sdan       nPrefixReg = pSort->pOrderBy->nExpr;
70778d58432Sdan       if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
708fd0a2f97Sdrh       pParse->nMem += nPrefixReg;
7091013c932Sdrh     }
710a2a49dc9Sdrh     pDest->iSdst = pParse->nMem+1;
711477df4b3Sdrh     pParse->nMem += nResultCol;
71205a86c5cSdrh   }else if( pDest->iSdst+nResultCol > pParse->nMem ){
71305a86c5cSdrh     /* This is an error condition that can result, for example, when a SELECT
71405a86c5cSdrh     ** on the right-hand side of an INSERT contains more result columns than
71505a86c5cSdrh     ** there are columns in the table on the left.  The error will be caught
71605a86c5cSdrh     ** and reported later.  But we need to make sure enough memory is allocated
71705a86c5cSdrh     ** to avoid other spurious errors in the meantime. */
71805a86c5cSdrh     pParse->nMem += nResultCol;
7194c583128Sdrh   }
72005a86c5cSdrh   pDest->nSdst = nResultCol;
7212b596da8Sdrh   regResult = pDest->iSdst;
722340309fdSdrh   if( srcTab>=0 ){
723340309fdSdrh     for(i=0; i<nResultCol; i++){
724d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
725340309fdSdrh       VdbeComment((v, "%s", pEList->a[i].zName));
72682c3d636Sdrh     }
7279ed1dfa8Sdanielk1977   }else if( eDest!=SRT_Exists ){
7289ed1dfa8Sdanielk1977     /* If the destination is an EXISTS(...) expression, the actual
7299ed1dfa8Sdanielk1977     ** values returned by the SELECT are not required.
7309ed1dfa8Sdanielk1977     */
731df553659Sdrh     u8 ecelFlags;
732df553659Sdrh     if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
733df553659Sdrh       ecelFlags = SQLITE_ECEL_DUP;
734df553659Sdrh     }else{
735df553659Sdrh       ecelFlags = 0;
736a2a49dc9Sdrh     }
7375579d59fSdrh     sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags);
738a2a49dc9Sdrh   }
7392282792aSdrh 
740daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
741daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
742daffd0e5Sdrh   ** part of the result.
7432282792aSdrh   */
744ea48eb2eSdrh   if( hasDistinct ){
745e8e4af76Sdrh     switch( pDistinct->eTnctType ){
746e8e4af76Sdrh       case WHERE_DISTINCT_ORDERED: {
747e8e4af76Sdrh         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
748e8e4af76Sdrh         int iJump;              /* Jump destination */
749e8e4af76Sdrh         int regPrev;            /* Previous row content */
750e8e4af76Sdrh 
751e8e4af76Sdrh         /* Allocate space for the previous row */
752e8e4af76Sdrh         regPrev = pParse->nMem+1;
753340309fdSdrh         pParse->nMem += nResultCol;
754e8e4af76Sdrh 
755e8e4af76Sdrh         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
756e8e4af76Sdrh         ** sets the MEM_Cleared bit on the first register of the
757e8e4af76Sdrh         ** previous value.  This will cause the OP_Ne below to always
758e8e4af76Sdrh         ** fail on the first iteration of the loop even if the first
759e8e4af76Sdrh         ** row is all NULLs.
760e8e4af76Sdrh         */
761e8e4af76Sdrh         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
762e8e4af76Sdrh         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
763e8e4af76Sdrh         pOp->opcode = OP_Null;
764e8e4af76Sdrh         pOp->p1 = 1;
765e8e4af76Sdrh         pOp->p2 = regPrev;
766e8e4af76Sdrh 
767340309fdSdrh         iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
768340309fdSdrh         for(i=0; i<nResultCol; i++){
769e8e4af76Sdrh           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
770340309fdSdrh           if( i<nResultCol-1 ){
771e8e4af76Sdrh             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
772688852abSdrh             VdbeCoverage(v);
773e8e4af76Sdrh           }else{
774e8e4af76Sdrh             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
775688852abSdrh             VdbeCoverage(v);
776e8e4af76Sdrh            }
777e8e4af76Sdrh           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
778e8e4af76Sdrh           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
779e8e4af76Sdrh         }
780fcf2a775Sdrh         assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
781340309fdSdrh         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
782e8e4af76Sdrh         break;
783e8e4af76Sdrh       }
784e8e4af76Sdrh 
785e8e4af76Sdrh       case WHERE_DISTINCT_UNIQUE: {
786e8e4af76Sdrh         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
787e8e4af76Sdrh         break;
788e8e4af76Sdrh       }
789e8e4af76Sdrh 
790e8e4af76Sdrh       default: {
791e8e4af76Sdrh         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
79238b4149cSdrh         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
79338b4149cSdrh                      regResult);
794e8e4af76Sdrh         break;
795e8e4af76Sdrh       }
796e8e4af76Sdrh     }
797079a3072Sdrh     if( pSort==0 ){
798aa9ce707Sdrh       codeOffset(v, p->iOffset, iContinue);
799ea48eb2eSdrh     }
8002282792aSdrh   }
80182c3d636Sdrh 
802c926afbcSdrh   switch( eDest ){
80382c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
80482c3d636Sdrh     ** table iParm.
8052282792aSdrh     */
80613449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
807c926afbcSdrh     case SRT_Union: {
8089cbf3425Sdrh       int r1;
8099cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
810340309fdSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
8119cbf3425Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
8129cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
813c926afbcSdrh       break;
814c926afbcSdrh     }
81582c3d636Sdrh 
81682c3d636Sdrh     /* Construct a record from the query result, but instead of
81782c3d636Sdrh     ** saving that record, use it as a key to delete elements from
81882c3d636Sdrh     ** the temporary table iParm.
81982c3d636Sdrh     */
820c926afbcSdrh     case SRT_Except: {
821340309fdSdrh       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
822c926afbcSdrh       break;
823c926afbcSdrh     }
824781def29Sdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
8255338a5f7Sdanielk1977 
8265338a5f7Sdanielk1977     /* Store the result as data using a unique key.
8275338a5f7Sdanielk1977     */
8288e1ee88cSdrh     case SRT_Fifo:
8298e1ee88cSdrh     case SRT_DistFifo:
8305338a5f7Sdanielk1977     case SRT_Table:
831b9bb7c18Sdrh     case SRT_EphemTab: {
832fd0a2f97Sdrh       int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
833373cc2ddSdrh       testcase( eDest==SRT_Table );
834373cc2ddSdrh       testcase( eDest==SRT_EphemTab );
835e2248cfdSdrh       testcase( eDest==SRT_Fifo );
836e2248cfdSdrh       testcase( eDest==SRT_DistFifo );
837fd0a2f97Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
8388ce7184bSdan #ifndef SQLITE_OMIT_CTE
8398e1ee88cSdrh       if( eDest==SRT_DistFifo ){
8408e1ee88cSdrh         /* If the destination is DistFifo, then cursor (iParm+1) is open
8418ce7184bSdan         ** on an ephemeral index. If the current row is already present
8428ce7184bSdan         ** in the index, do not write it to the output. If not, add the
8438ce7184bSdan         ** current row to the index and proceed with writing it to the
8448ce7184bSdan         ** output table as well.  */
8458ce7184bSdan         int addr = sqlite3VdbeCurrentAddr(v) + 4;
84638b4149cSdrh         sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
84738b4149cSdrh         VdbeCoverage(v);
8488ce7184bSdan         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
849079a3072Sdrh         assert( pSort==0 );
8508ce7184bSdan       }
8518ce7184bSdan #endif
852079a3072Sdrh       if( pSort ){
8535579d59fSdrh         pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
8545338a5f7Sdanielk1977       }else{
855b7654111Sdrh         int r2 = sqlite3GetTempReg(pParse);
856b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
857b7654111Sdrh         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
858b7654111Sdrh         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
859b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r2);
8605338a5f7Sdanielk1977       }
861fd0a2f97Sdrh       sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
8625338a5f7Sdanielk1977       break;
8635338a5f7Sdanielk1977     }
8642282792aSdrh 
86593758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
8662282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
8672282792aSdrh     ** then there should be a single item on the stack.  Write this
8682282792aSdrh     ** item into the set table with bogus data.
8692282792aSdrh     */
870c926afbcSdrh     case SRT_Set: {
871340309fdSdrh       assert( nResultCol==1 );
872634d81deSdrh       pDest->affSdst =
873634d81deSdrh                   sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
874079a3072Sdrh       if( pSort ){
875de941c60Sdrh         /* At first glance you would think we could optimize out the
876de941c60Sdrh         ** ORDER BY in this case since the order of entries in the set
877de941c60Sdrh         ** does not matter.  But there might be a LIMIT clause, in which
878de941c60Sdrh         ** case the order does matter */
8795579d59fSdrh         pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
880c926afbcSdrh       }else{
881b7654111Sdrh         int r1 = sqlite3GetTempReg(pParse);
882634d81deSdrh         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
883da250ea5Sdrh         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
884b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
885b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r1);
886c926afbcSdrh       }
887c926afbcSdrh       break;
888c926afbcSdrh     }
88982c3d636Sdrh 
890504b6989Sdrh     /* If any row exist in the result set, record that fact and abort.
891ec7429aeSdrh     */
892ec7429aeSdrh     case SRT_Exists: {
8934c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
894ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
895ec7429aeSdrh       break;
896ec7429aeSdrh     }
897ec7429aeSdrh 
8982282792aSdrh     /* If this is a scalar select that is part of an expression, then
8992282792aSdrh     ** store the results in the appropriate memory cell and break out
9002282792aSdrh     ** of the scan loop.
9012282792aSdrh     */
902c926afbcSdrh     case SRT_Mem: {
903340309fdSdrh       assert( nResultCol==1 );
904079a3072Sdrh       if( pSort ){
9055579d59fSdrh         pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
906c926afbcSdrh       }else{
90753932ce8Sdrh         assert( regResult==iParm );
908ec7429aeSdrh         /* The LIMIT clause will jump out of the loop for us */
909c926afbcSdrh       }
910c926afbcSdrh       break;
911c926afbcSdrh     }
91293758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
9132282792aSdrh 
91481cf13ecSdrh     case SRT_Coroutine:       /* Send data to a co-routine */
91581cf13ecSdrh     case SRT_Output: {        /* Return the results */
916373cc2ddSdrh       testcase( eDest==SRT_Coroutine );
917373cc2ddSdrh       testcase( eDest==SRT_Output );
918079a3072Sdrh       if( pSort ){
9195579d59fSdrh         pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol,
9205579d59fSdrh                        nPrefixReg);
921e00ee6ebSdrh       }else if( eDest==SRT_Coroutine ){
9222b596da8Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
923c182d163Sdrh       }else{
924340309fdSdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
925340309fdSdrh         sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
926ac82fcf5Sdrh       }
927142e30dfSdrh       break;
928142e30dfSdrh     }
929142e30dfSdrh 
930fe1c6bb9Sdrh #ifndef SQLITE_OMIT_CTE
931fe1c6bb9Sdrh     /* Write the results into a priority queue that is order according to
932fe1c6bb9Sdrh     ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
933fe1c6bb9Sdrh     ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
934fe1c6bb9Sdrh     ** pSO->nExpr columns, then make sure all keys are unique by adding a
935fe1c6bb9Sdrh     ** final OP_Sequence column.  The last column is the record as a blob.
936fe1c6bb9Sdrh     */
937fe1c6bb9Sdrh     case SRT_DistQueue:
938fe1c6bb9Sdrh     case SRT_Queue: {
939fe1c6bb9Sdrh       int nKey;
940fe1c6bb9Sdrh       int r1, r2, r3;
941fe1c6bb9Sdrh       int addrTest = 0;
942fe1c6bb9Sdrh       ExprList *pSO;
943fe1c6bb9Sdrh       pSO = pDest->pOrderBy;
944fe1c6bb9Sdrh       assert( pSO );
945fe1c6bb9Sdrh       nKey = pSO->nExpr;
946fe1c6bb9Sdrh       r1 = sqlite3GetTempReg(pParse);
947fe1c6bb9Sdrh       r2 = sqlite3GetTempRange(pParse, nKey+2);
948fe1c6bb9Sdrh       r3 = r2+nKey+1;
949fe1c6bb9Sdrh       if( eDest==SRT_DistQueue ){
950fe1c6bb9Sdrh         /* If the destination is DistQueue, then cursor (iParm+1) is open
951fe1c6bb9Sdrh         ** on a second ephemeral index that holds all values every previously
9527e4efaecSdrh         ** added to the queue. */
9537e4efaecSdrh         addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
9547e4efaecSdrh                                         regResult, nResultCol);
955688852abSdrh         VdbeCoverage(v);
9567e4efaecSdrh       }
9577e4efaecSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
9587e4efaecSdrh       if( eDest==SRT_DistQueue ){
959fe1c6bb9Sdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
960cfe24586Sdan         sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
961fe1c6bb9Sdrh       }
962fe1c6bb9Sdrh       for(i=0; i<nKey; i++){
963fe1c6bb9Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy,
964fe1c6bb9Sdrh                           regResult + pSO->a[i].u.x.iOrderByCol - 1,
965fe1c6bb9Sdrh                           r2+i);
966fe1c6bb9Sdrh       }
967fe1c6bb9Sdrh       sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
968fe1c6bb9Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
969fe1c6bb9Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
970fe1c6bb9Sdrh       if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
971fe1c6bb9Sdrh       sqlite3ReleaseTempReg(pParse, r1);
972fe1c6bb9Sdrh       sqlite3ReleaseTempRange(pParse, r2, nKey+2);
973fe1c6bb9Sdrh       break;
974fe1c6bb9Sdrh     }
975fe1c6bb9Sdrh #endif /* SQLITE_OMIT_CTE */
976fe1c6bb9Sdrh 
977fe1c6bb9Sdrh 
978fe1c6bb9Sdrh 
9796a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER)
980d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
981d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
982d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
983d7489c39Sdrh     ** about the actual results of the select.
984d7489c39Sdrh     */
985c926afbcSdrh     default: {
986f46f905aSdrh       assert( eDest==SRT_Discard );
987c926afbcSdrh       break;
988c926afbcSdrh     }
98993758c8dSdanielk1977 #endif
990c926afbcSdrh   }
991ec7429aeSdrh 
9925e87be87Sdrh   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
9935e87be87Sdrh   ** there is a sorter, in which case the sorter has already limited
9945e87be87Sdrh   ** the output for us.
995ec7429aeSdrh   */
996079a3072Sdrh   if( pSort==0 && p->iLimit ){
99716897072Sdrh     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
998ec7429aeSdrh   }
99982c3d636Sdrh }
100082c3d636Sdrh 
100182c3d636Sdrh /*
1002ad124329Sdrh ** Allocate a KeyInfo object sufficient for an index of N key columns and
1003ad124329Sdrh ** X extra columns.
1004323df790Sdrh */
1005ad124329Sdrh KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
10062ec2fb22Sdrh   KeyInfo *p = sqlite3DbMallocZero(0,
1007ad124329Sdrh                    sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
1008323df790Sdrh   if( p ){
1009ad124329Sdrh     p->aSortOrder = (u8*)&p->aColl[N+X];
1010323df790Sdrh     p->nField = (u16)N;
1011ad124329Sdrh     p->nXField = (u16)X;
1012323df790Sdrh     p->enc = ENC(db);
1013323df790Sdrh     p->db = db;
10142ec2fb22Sdrh     p->nRef = 1;
10152ec2fb22Sdrh   }else{
10162ec2fb22Sdrh     db->mallocFailed = 1;
1017323df790Sdrh   }
1018323df790Sdrh   return p;
1019323df790Sdrh }
1020323df790Sdrh 
1021323df790Sdrh /*
10222ec2fb22Sdrh ** Deallocate a KeyInfo object
10232ec2fb22Sdrh */
10242ec2fb22Sdrh void sqlite3KeyInfoUnref(KeyInfo *p){
10252ec2fb22Sdrh   if( p ){
10262ec2fb22Sdrh     assert( p->nRef>0 );
10272ec2fb22Sdrh     p->nRef--;
1028c6efe12dSmistachkin     if( p->nRef==0 ) sqlite3DbFree(0, p);
10292ec2fb22Sdrh   }
10302ec2fb22Sdrh }
10312ec2fb22Sdrh 
10322ec2fb22Sdrh /*
10332ec2fb22Sdrh ** Make a new pointer to a KeyInfo object
10342ec2fb22Sdrh */
10352ec2fb22Sdrh KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
10362ec2fb22Sdrh   if( p ){
10372ec2fb22Sdrh     assert( p->nRef>0 );
10382ec2fb22Sdrh     p->nRef++;
10392ec2fb22Sdrh   }
10402ec2fb22Sdrh   return p;
10412ec2fb22Sdrh }
10422ec2fb22Sdrh 
10432ec2fb22Sdrh #ifdef SQLITE_DEBUG
10442ec2fb22Sdrh /*
10452ec2fb22Sdrh ** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
10462ec2fb22Sdrh ** can only be changed if this is just a single reference to the object.
10472ec2fb22Sdrh **
10482ec2fb22Sdrh ** This routine is used only inside of assert() statements.
10492ec2fb22Sdrh */
10502ec2fb22Sdrh int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
10512ec2fb22Sdrh #endif /* SQLITE_DEBUG */
10522ec2fb22Sdrh 
10532ec2fb22Sdrh /*
1054dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records
1055dece1a84Sdrh ** the collating sequence for each expression in that expression list.
1056dece1a84Sdrh **
10570342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
10580342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to
10590342b1f5Sdrh ** implement that clause.  If the ExprList is the result set of a SELECT
10600342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual
10610342b1f5Sdrh ** index to implement a DISTINCT test.
10620342b1f5Sdrh **
106360ec914cSpeter.d.reid ** Space to hold the KeyInfo structure is obtained from malloc.  The calling
1064dece1a84Sdrh ** function is responsible for seeing that this structure is eventually
10652ec2fb22Sdrh ** freed.
1066dece1a84Sdrh */
1067079a3072Sdrh static KeyInfo *keyInfoFromExprList(
1068079a3072Sdrh   Parse *pParse,       /* Parsing context */
1069079a3072Sdrh   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
1070079a3072Sdrh   int iStart,          /* Begin with this column of pList */
1071079a3072Sdrh   int nExtra           /* Add this many extra columns to the end */
1072079a3072Sdrh ){
1073dece1a84Sdrh   int nExpr;
1074dece1a84Sdrh   KeyInfo *pInfo;
1075dece1a84Sdrh   struct ExprList_item *pItem;
1076323df790Sdrh   sqlite3 *db = pParse->db;
1077dece1a84Sdrh   int i;
1078dece1a84Sdrh 
1079dece1a84Sdrh   nExpr = pList->nExpr;
10803f39bcf5Sdrh   pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
1081dece1a84Sdrh   if( pInfo ){
10822ec2fb22Sdrh     assert( sqlite3KeyInfoIsWriteable(pInfo) );
10836284db90Sdrh     for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
1084dece1a84Sdrh       CollSeq *pColl;
1085dece1a84Sdrh       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
1086323df790Sdrh       if( !pColl ) pColl = db->pDfltColl;
10876284db90Sdrh       pInfo->aColl[i-iStart] = pColl;
10886284db90Sdrh       pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
1089dece1a84Sdrh     }
1090dece1a84Sdrh   }
1091dece1a84Sdrh   return pInfo;
1092dece1a84Sdrh }
1093dece1a84Sdrh 
10947f61e92cSdan /*
10957f61e92cSdan ** Name of the connection operator, used for error messages.
10967f61e92cSdan */
10977f61e92cSdan static const char *selectOpName(int id){
10987f61e92cSdan   char *z;
10997f61e92cSdan   switch( id ){
11007f61e92cSdan     case TK_ALL:       z = "UNION ALL";   break;
11017f61e92cSdan     case TK_INTERSECT: z = "INTERSECT";   break;
11027f61e92cSdan     case TK_EXCEPT:    z = "EXCEPT";      break;
11037f61e92cSdan     default:           z = "UNION";       break;
11047f61e92cSdan   }
11057f61e92cSdan   return z;
11067f61e92cSdan }
11077f61e92cSdan 
11082ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN
110917c0bc0cSdan /*
111017c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
111117c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
111217c0bc0cSdan ** where the caption is of the form:
111317c0bc0cSdan **
111417c0bc0cSdan **   "USE TEMP B-TREE FOR xxx"
111517c0bc0cSdan **
111617c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
111717c0bc0cSdan ** is determined by the zUsage argument.
111817c0bc0cSdan */
11192ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){
11202ce22453Sdan   if( pParse->explain==2 ){
11212ce22453Sdan     Vdbe *v = pParse->pVdbe;
11222ce22453Sdan     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
11232ce22453Sdan     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
11242ce22453Sdan   }
11252ce22453Sdan }
112617c0bc0cSdan 
112717c0bc0cSdan /*
1128bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro
1129bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
1130bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that
1131bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
1132bb2b4418Sdan ** code with #ifndef directives.
1133bb2b4418Sdan */
1134bb2b4418Sdan # define explainSetInteger(a, b) a = b
1135bb2b4418Sdan 
1136bb2b4418Sdan #else
1137bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */
1138bb2b4418Sdan # define explainTempTable(y,z)
1139bb2b4418Sdan # define explainSetInteger(y,z)
1140bb2b4418Sdan #endif
1141bb2b4418Sdan 
1142bb2b4418Sdan #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
1143bb2b4418Sdan /*
11447f61e92cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
11457f61e92cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
11467f61e92cSdan ** where the caption is of one of the two forms:
11477f61e92cSdan **
11487f61e92cSdan **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
11497f61e92cSdan **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
11507f61e92cSdan **
11517f61e92cSdan ** where iSub1 and iSub2 are the integers passed as the corresponding
11527f61e92cSdan ** function parameters, and op is the text representation of the parameter
11537f61e92cSdan ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
11547f61e92cSdan ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
11557f61e92cSdan ** false, or the second form if it is true.
11567f61e92cSdan */
11577f61e92cSdan static void explainComposite(
11587f61e92cSdan   Parse *pParse,                  /* Parse context */
11597f61e92cSdan   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
11607f61e92cSdan   int iSub1,                      /* Subquery id 1 */
11617f61e92cSdan   int iSub2,                      /* Subquery id 2 */
11627f61e92cSdan   int bUseTmp                     /* True if a temp table was used */
11637f61e92cSdan ){
11647f61e92cSdan   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
11657f61e92cSdan   if( pParse->explain==2 ){
11667f61e92cSdan     Vdbe *v = pParse->pVdbe;
11677f61e92cSdan     char *zMsg = sqlite3MPrintf(
116830969d3fSdan         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
11697f61e92cSdan         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
11707f61e92cSdan     );
11717f61e92cSdan     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
11727f61e92cSdan   }
11737f61e92cSdan }
11742ce22453Sdan #else
117517c0bc0cSdan /* No-op versions of the explainXXX() functions and macros. */
11767f61e92cSdan # define explainComposite(v,w,x,y,z)
11772ce22453Sdan #endif
1178dece1a84Sdrh 
1179dece1a84Sdrh /*
1180d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
1181d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
1182d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
1183d8bc7086Sdrh ** routine generates the code needed to do that.
1184d8bc7086Sdrh */
1185c926afbcSdrh static void generateSortTail(
1186cdd536f0Sdrh   Parse *pParse,    /* Parsing context */
1187c926afbcSdrh   Select *p,        /* The SELECT statement */
1188079a3072Sdrh   SortCtx *pSort,   /* Information on the ORDER BY clause */
1189c926afbcSdrh   int nColumn,      /* Number of columns of data */
11906c8c8ce0Sdanielk1977   SelectDest *pDest /* Write the sorted results here */
1191c926afbcSdrh ){
1192ddba0c22Sdrh   Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
1193dc5ea5c7Sdrh   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
1194dc5ea5c7Sdrh   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
1195d8bc7086Sdrh   int addr;
1196079a3072Sdrh   int addrOnce = 0;
11970342b1f5Sdrh   int iTab;
1198079a3072Sdrh   ExprList *pOrderBy = pSort->pOrderBy;
11996c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
12002b596da8Sdrh   int iParm = pDest->iSDParm;
12012d401ab8Sdrh   int regRow;
12022d401ab8Sdrh   int regRowid;
1203079a3072Sdrh   int nKey;
1204f45f2326Sdrh   int iSortTab;                   /* Sorter cursor to read from */
1205f45f2326Sdrh   int nSortData;                  /* Trailing values to read from sorter */
1206f45f2326Sdrh   int i;
120778d58432Sdan   int bSeq;                       /* True if sorter record includes seq. no. */
120870f624c3Sdrh #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
120970f624c3Sdrh   struct ExprList_item *aOutEx = p->pEList->a;
121070f624c3Sdrh #endif
12112d401ab8Sdrh 
1212079a3072Sdrh   if( pSort->labelBkOut ){
1213079a3072Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
1214076e85f5Sdrh     sqlite3VdbeGoto(v, addrBreak);
1215079a3072Sdrh     sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
1216079a3072Sdrh   }
1217079a3072Sdrh   iTab = pSort->iECursor;
12187d10d5a6Sdrh   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
12193e9ca094Sdrh     regRowid = 0;
1220f45f2326Sdrh     regRow = pDest->iSdst;
1221f45f2326Sdrh     nSortData = nColumn;
12223e9ca094Sdrh   }else{
12233e9ca094Sdrh     regRowid = sqlite3GetTempReg(pParse);
1224f45f2326Sdrh     regRow = sqlite3GetTempReg(pParse);
1225f45f2326Sdrh     nSortData = 1;
1226cdd536f0Sdrh   }
1227079a3072Sdrh   nKey = pOrderBy->nExpr - pSort->nOBSat;
1228079a3072Sdrh   if( pSort->sortFlags & SORTFLAG_UseSorter ){
1229c2bb3282Sdrh     int regSortOut = ++pParse->nMem;
1230f45f2326Sdrh     iSortTab = pParse->nTab++;
123183553eefSdrh     if( pSort->labelBkOut ){
123283553eefSdrh       addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
123383553eefSdrh     }
1234f45f2326Sdrh     sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
1235079a3072Sdrh     if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
1236c6aff30cSdrh     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
1237688852abSdrh     VdbeCoverage(v);
1238aa9ce707Sdrh     codeOffset(v, p->iOffset, addrContinue);
12396cf4a7dfSdrh     sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
124078d58432Sdan     bSeq = 0;
1241c6aff30cSdrh   }else{
1242688852abSdrh     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
1243aa9ce707Sdrh     codeOffset(v, p->iOffset, addrContinue);
1244f45f2326Sdrh     iSortTab = iTab;
124578d58432Sdan     bSeq = 1;
1246f45f2326Sdrh   }
1247f45f2326Sdrh   for(i=0; i<nSortData; i++){
124878d58432Sdan     sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
124970f624c3Sdrh     VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
1250c6aff30cSdrh   }
1251c926afbcSdrh   switch( eDest ){
1252b9bb7c18Sdrh     case SRT_EphemTab: {
12532d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
12542d401ab8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
12552d401ab8Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1256c926afbcSdrh       break;
1257c926afbcSdrh     }
125893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
1259c926afbcSdrh     case SRT_Set: {
1260c926afbcSdrh       assert( nColumn==1 );
1261634d81deSdrh       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
1262634d81deSdrh                         &pDest->affSdst, 1);
1263da250ea5Sdrh       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
1264a7a8e14bSdanielk1977       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
1265c926afbcSdrh       break;
1266c926afbcSdrh     }
1267c926afbcSdrh     case SRT_Mem: {
1268c926afbcSdrh       assert( nColumn==1 );
1269b21e7c70Sdrh       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
1270ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
1271c926afbcSdrh       break;
1272c926afbcSdrh     }
127393758c8dSdanielk1977 #endif
1274373cc2ddSdrh     default: {
1275373cc2ddSdrh       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
12761c767f0dSdrh       testcase( eDest==SRT_Output );
12771c767f0dSdrh       testcase( eDest==SRT_Coroutine );
12787d10d5a6Sdrh       if( eDest==SRT_Output ){
12792b596da8Sdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
12802b596da8Sdrh         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
1281a9671a22Sdrh       }else{
12822b596da8Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1283ce665cf6Sdrh       }
1284ac82fcf5Sdrh       break;
1285ac82fcf5Sdrh     }
1286c926afbcSdrh   }
1287f45f2326Sdrh   if( regRowid ){
12882d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regRow);
12892d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regRowid);
1290f45f2326Sdrh   }
1291ec7429aeSdrh   /* The bottom of the loop
1292ec7429aeSdrh   */
1293dc5ea5c7Sdrh   sqlite3VdbeResolveLabel(v, addrContinue);
1294079a3072Sdrh   if( pSort->sortFlags & SORTFLAG_UseSorter ){
1295688852abSdrh     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
1296c6aff30cSdrh   }else{
1297688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
1298c6aff30cSdrh   }
1299079a3072Sdrh   if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
1300dc5ea5c7Sdrh   sqlite3VdbeResolveLabel(v, addrBreak);
1301d8bc7086Sdrh }
1302d8bc7086Sdrh 
1303d8bc7086Sdrh /*
1304517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
1305517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
1306e78e8284Sdrh **
13075f3e5e74Sdrh ** Also try to estimate the size of the returned value and return that
13085f3e5e74Sdrh ** result in *pEstWidth.
13095f3e5e74Sdrh **
1310955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the
1311955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The
1312955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
1313955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The
1314955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is
1315955de52cSdanielk1977 ** considered a column by this function.
1316e78e8284Sdrh **
1317955de52cSdanielk1977 **   SELECT col FROM tbl;
1318955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl;
1319955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl);
1320955de52cSdanielk1977 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
1321955de52cSdanielk1977 **
1322955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL.
13235f3e5e74Sdrh **
13245f3e5e74Sdrh ** This routine has either 3 or 6 parameters depending on whether or not
13255f3e5e74Sdrh ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
1326fcb78a49Sdrh */
13275f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
13285f3e5e74Sdrh # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
1329b121dd14Sdrh #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
1330b121dd14Sdrh # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
1331b121dd14Sdrh #endif
13325f3e5e74Sdrh static const char *columnTypeImpl(
1333955de52cSdanielk1977   NameContext *pNC,
1334955de52cSdanielk1977   Expr *pExpr,
1335b121dd14Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
13365f3e5e74Sdrh   const char **pzOrigDb,
13375f3e5e74Sdrh   const char **pzOrigTab,
13385f3e5e74Sdrh   const char **pzOrigCol,
1339b121dd14Sdrh #endif
13405f3e5e74Sdrh   u8 *pEstWidth
1341955de52cSdanielk1977 ){
1342955de52cSdanielk1977   char const *zType = 0;
1343517eb646Sdanielk1977   int j;
13445f3e5e74Sdrh   u8 estWidth = 1;
1345b121dd14Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1346b121dd14Sdrh   char const *zOrigDb = 0;
1347b121dd14Sdrh   char const *zOrigTab = 0;
1348b121dd14Sdrh   char const *zOrigCol = 0;
1349b121dd14Sdrh #endif
13505338a5f7Sdanielk1977 
1351f7ce4291Sdrh   assert( pExpr!=0 );
1352f7ce4291Sdrh   assert( pNC->pSrcList!=0 );
135300e279d9Sdanielk1977   switch( pExpr->op ){
135430bcf5dbSdrh     case TK_AGG_COLUMN:
135500e279d9Sdanielk1977     case TK_COLUMN: {
1356955de52cSdanielk1977       /* The expression is a column. Locate the table the column is being
1357955de52cSdanielk1977       ** extracted from in NameContext.pSrcList. This table may be real
1358955de52cSdanielk1977       ** database table or a subquery.
1359955de52cSdanielk1977       */
1360955de52cSdanielk1977       Table *pTab = 0;            /* Table structure column is extracted from */
1361955de52cSdanielk1977       Select *pS = 0;             /* Select the column is extracted from */
1362955de52cSdanielk1977       int iCol = pExpr->iColumn;  /* Index of column in pTab */
1363373cc2ddSdrh       testcase( pExpr->op==TK_AGG_COLUMN );
1364373cc2ddSdrh       testcase( pExpr->op==TK_COLUMN );
136543bc88bbSdan       while( pNC && !pTab ){
1366b3bce662Sdanielk1977         SrcList *pTabList = pNC->pSrcList;
1367b3bce662Sdanielk1977         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
1368b3bce662Sdanielk1977         if( j<pTabList->nSrc ){
13696a3ea0e6Sdrh           pTab = pTabList->a[j].pTab;
1370955de52cSdanielk1977           pS = pTabList->a[j].pSelect;
1371b3bce662Sdanielk1977         }else{
1372b3bce662Sdanielk1977           pNC = pNC->pNext;
1373b3bce662Sdanielk1977         }
1374b3bce662Sdanielk1977       }
1375955de52cSdanielk1977 
137643bc88bbSdan       if( pTab==0 ){
1377417168adSdrh         /* At one time, code such as "SELECT new.x" within a trigger would
1378417168adSdrh         ** cause this condition to run.  Since then, we have restructured how
1379417168adSdrh         ** trigger code is generated and so this condition is no longer
138043bc88bbSdan         ** possible. However, it can still be true for statements like
138143bc88bbSdan         ** the following:
138243bc88bbSdan         **
138343bc88bbSdan         **   CREATE TABLE t1(col INTEGER);
138443bc88bbSdan         **   SELECT (SELECT t1.col) FROM FROM t1;
138543bc88bbSdan         **
138643bc88bbSdan         ** when columnType() is called on the expression "t1.col" in the
138743bc88bbSdan         ** sub-select. In this case, set the column type to NULL, even
138843bc88bbSdan         ** though it should really be "INTEGER".
138943bc88bbSdan         **
139043bc88bbSdan         ** This is not a problem, as the column type of "t1.col" is never
139143bc88bbSdan         ** used. When columnType() is called on the expression
139243bc88bbSdan         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
139343bc88bbSdan         ** branch below.  */
13947e62779aSdrh         break;
13957e62779aSdrh       }
1396955de52cSdanielk1977 
139743bc88bbSdan       assert( pTab && pExpr->pTab==pTab );
1398955de52cSdanielk1977       if( pS ){
1399955de52cSdanielk1977         /* The "table" is actually a sub-select or a view in the FROM clause
1400955de52cSdanielk1977         ** of the SELECT statement. Return the declaration type and origin
1401955de52cSdanielk1977         ** data for the result-set column of the sub-select.
1402955de52cSdanielk1977         */
14037b688edeSdrh         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
1404955de52cSdanielk1977           /* If iCol is less than zero, then the expression requests the
1405955de52cSdanielk1977           ** rowid of the sub-select or view. This expression is legal (see
1406955de52cSdanielk1977           ** test case misc2.2.2) - it always evaluates to NULL.
14072ec18a3cSdrh           **
14082ec18a3cSdrh           ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
14092ec18a3cSdrh           ** caught already by name resolution.
1410955de52cSdanielk1977           */
1411955de52cSdanielk1977           NameContext sNC;
1412955de52cSdanielk1977           Expr *p = pS->pEList->a[iCol].pExpr;
1413955de52cSdanielk1977           sNC.pSrcList = pS->pSrc;
141443bc88bbSdan           sNC.pNext = pNC;
1415955de52cSdanielk1977           sNC.pParse = pNC->pParse;
14165f3e5e74Sdrh           zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
1417955de52cSdanielk1977         }
141893c36bb3Sdrh       }else if( pTab->pSchema ){
1419955de52cSdanielk1977         /* A real table */
1420955de52cSdanielk1977         assert( !pS );
1421fcb78a49Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
1422fcb78a49Sdrh         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
14235f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1424fcb78a49Sdrh         if( iCol<0 ){
1425fcb78a49Sdrh           zType = "INTEGER";
14265f3e5e74Sdrh           zOrigCol = "rowid";
1427fcb78a49Sdrh         }else{
1428fcb78a49Sdrh           zType = pTab->aCol[iCol].zType;
14295f3e5e74Sdrh           zOrigCol = pTab->aCol[iCol].zName;
14305f3e5e74Sdrh           estWidth = pTab->aCol[iCol].szEst;
1431955de52cSdanielk1977         }
14325f3e5e74Sdrh         zOrigTab = pTab->zName;
1433955de52cSdanielk1977         if( pNC->pParse ){
1434955de52cSdanielk1977           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
14355f3e5e74Sdrh           zOrigDb = pNC->pParse->db->aDb[iDb].zName;
1436955de52cSdanielk1977         }
14375f3e5e74Sdrh #else
14385f3e5e74Sdrh         if( iCol<0 ){
14395f3e5e74Sdrh           zType = "INTEGER";
14405f3e5e74Sdrh         }else{
14415f3e5e74Sdrh           zType = pTab->aCol[iCol].zType;
14425f3e5e74Sdrh           estWidth = pTab->aCol[iCol].szEst;
14435f3e5e74Sdrh         }
14445f3e5e74Sdrh #endif
1445fcb78a49Sdrh       }
144600e279d9Sdanielk1977       break;
1447736c22b8Sdrh     }
144893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
144900e279d9Sdanielk1977     case TK_SELECT: {
1450955de52cSdanielk1977       /* The expression is a sub-select. Return the declaration type and
1451955de52cSdanielk1977       ** origin info for the single column in the result set of the SELECT
1452955de52cSdanielk1977       ** statement.
1453955de52cSdanielk1977       */
1454b3bce662Sdanielk1977       NameContext sNC;
14556ab3a2ecSdanielk1977       Select *pS = pExpr->x.pSelect;
1456955de52cSdanielk1977       Expr *p = pS->pEList->a[0].pExpr;
14576ab3a2ecSdanielk1977       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
1458955de52cSdanielk1977       sNC.pSrcList = pS->pSrc;
1459b3bce662Sdanielk1977       sNC.pNext = pNC;
1460955de52cSdanielk1977       sNC.pParse = pNC->pParse;
14615f3e5e74Sdrh       zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
146200e279d9Sdanielk1977       break;
1463fcb78a49Sdrh     }
146493758c8dSdanielk1977 #endif
146500e279d9Sdanielk1977   }
146600e279d9Sdanielk1977 
14675f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
14685f3e5e74Sdrh   if( pzOrigDb ){
14695f3e5e74Sdrh     assert( pzOrigTab && pzOrigCol );
14705f3e5e74Sdrh     *pzOrigDb = zOrigDb;
14715f3e5e74Sdrh     *pzOrigTab = zOrigTab;
14725f3e5e74Sdrh     *pzOrigCol = zOrigCol;
1473955de52cSdanielk1977   }
14745f3e5e74Sdrh #endif
14755f3e5e74Sdrh   if( pEstWidth ) *pEstWidth = estWidth;
1476517eb646Sdanielk1977   return zType;
1477517eb646Sdanielk1977 }
1478517eb646Sdanielk1977 
1479517eb646Sdanielk1977 /*
1480517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
1481517eb646Sdanielk1977 ** in the result set.
1482517eb646Sdanielk1977 */
1483517eb646Sdanielk1977 static void generateColumnTypes(
1484517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
1485517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
1486517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
1487517eb646Sdanielk1977 ){
14883f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE
1489517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
1490517eb646Sdanielk1977   int i;
1491b3bce662Sdanielk1977   NameContext sNC;
1492b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
1493955de52cSdanielk1977   sNC.pParse = pParse;
1494517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
1495517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
14963f913576Sdrh     const char *zType;
14973f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1498955de52cSdanielk1977     const char *zOrigDb = 0;
1499955de52cSdanielk1977     const char *zOrigTab = 0;
1500955de52cSdanielk1977     const char *zOrigCol = 0;
15015f3e5e74Sdrh     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
1502955de52cSdanielk1977 
150385b623f2Sdrh     /* The vdbe must make its own copy of the column-type and other
15044b1ae99dSdanielk1977     ** column specific strings, in case the schema is reset before this
15054b1ae99dSdanielk1977     ** virtual machine is deleted.
1506fbcd585fSdanielk1977     */
150710fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
150810fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
150910fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
15103f913576Sdrh #else
15115f3e5e74Sdrh     zType = columnType(&sNC, p, 0, 0, 0, 0);
15123f913576Sdrh #endif
151310fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
1514fcb78a49Sdrh   }
15155f3e5e74Sdrh #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
1516fcb78a49Sdrh }
1517fcb78a49Sdrh 
1518fcb78a49Sdrh /*
1519fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
1520fcb78a49Sdrh ** in the result set.  This information is used to provide the
1521fcabd464Sdrh ** azCol[] values in the callback.
152282c3d636Sdrh */
1523832508b7Sdrh static void generateColumnNames(
1524832508b7Sdrh   Parse *pParse,      /* Parser context */
1525ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
1526832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
1527832508b7Sdrh ){
1528d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
15296a3ea0e6Sdrh   int i, j;
15309bb575fdSdrh   sqlite3 *db = pParse->db;
1531fcabd464Sdrh   int fullNames, shortNames;
1532fcabd464Sdrh 
1533fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN
15343cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
15353cf86063Sdanielk1977   if( pParse->explain ){
153661de0d1bSdanielk1977     return;
15373cf86063Sdanielk1977   }
15385338a5f7Sdanielk1977 #endif
15393cf86063Sdanielk1977 
15409802947fSdrh   if( pParse->colNamesSet || db->mallocFailed ) return;
15419802947fSdrh   assert( v!=0 );
1542f7ce4291Sdrh   assert( pTabList!=0 );
1543d8bc7086Sdrh   pParse->colNamesSet = 1;
1544fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
1545fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
154622322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
154782c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
154882c3d636Sdrh     Expr *p;
15495a38705eSdrh     p = pEList->a[i].pExpr;
1550373cc2ddSdrh     if( NEVER(p==0) ) continue;
155182c3d636Sdrh     if( pEList->a[i].zName ){
155282c3d636Sdrh       char *zName = pEList->a[i].zName;
155310fb749bSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
1554f7ce4291Sdrh     }else if( p->op==TK_COLUMN || p->op==TK_AGG_COLUMN ){
15556a3ea0e6Sdrh       Table *pTab;
155697665873Sdrh       char *zCol;
15578aff1015Sdrh       int iCol = p->iColumn;
1558e2f02bacSdrh       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
1559e2f02bacSdrh         if( pTabList->a[j].iCursor==p->iTable ) break;
1560e2f02bacSdrh       }
15616a3ea0e6Sdrh       assert( j<pTabList->nSrc );
15626a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
15638aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
156497665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1565b1363206Sdrh       if( iCol<0 ){
156647a6db2bSdrh         zCol = "rowid";
1567b1363206Sdrh       }else{
1568b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
1569b1363206Sdrh       }
1570e49b146fSdrh       if( !shortNames && !fullNames ){
157110fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
1572b7916a78Sdrh             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
15731c767f0dSdrh       }else if( fullNames ){
157482c3d636Sdrh         char *zName = 0;
15751c767f0dSdrh         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
157610fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
157782c3d636Sdrh       }else{
157810fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
157982c3d636Sdrh       }
15801bee3d7bSdrh     }else{
1581859bc542Sdrh       const char *z = pEList->a[i].zSpan;
1582859bc542Sdrh       z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
1583859bc542Sdrh       sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
158482c3d636Sdrh     }
158582c3d636Sdrh   }
158676d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
15875080aaa7Sdrh }
158882c3d636Sdrh 
1589d8bc7086Sdrh /*
159060ec914cSpeter.d.reid ** Given an expression list (which is really the list of expressions
15917d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate
15927d10d5a6Sdrh ** column names for a table that would hold the expression list.
15937d10d5a6Sdrh **
15947d10d5a6Sdrh ** All column names will be unique.
15957d10d5a6Sdrh **
15967d10d5a6Sdrh ** Only the column names are computed.  Column.zType, Column.zColl,
15977d10d5a6Sdrh ** and other fields of Column are zeroed.
15987d10d5a6Sdrh **
15997d10d5a6Sdrh ** Return SQLITE_OK on success.  If a memory allocation error occurs,
16007d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
1601315555caSdrh */
16028981b904Sdrh int sqlite3ColumnsFromExprList(
16037d10d5a6Sdrh   Parse *pParse,          /* Parsing context */
16047d10d5a6Sdrh   ExprList *pEList,       /* Expr list from which to derive column names */
1605d815f17dSdrh   i16 *pnCol,             /* Write the number of columns here */
16067d10d5a6Sdrh   Column **paCol          /* Write the new column list here */
16077d10d5a6Sdrh ){
1608dc5ea5c7Sdrh   sqlite3 *db = pParse->db;   /* Database connection */
1609dc5ea5c7Sdrh   int i, j;                   /* Loop counters */
1610ebed3fa3Sdrh   u32 cnt;                    /* Index added to make the name unique */
1611dc5ea5c7Sdrh   Column *aCol, *pCol;        /* For looping over result columns */
1612dc5ea5c7Sdrh   int nCol;                   /* Number of columns in the result set */
1613dc5ea5c7Sdrh   Expr *p;                    /* Expression for a single result column */
1614dc5ea5c7Sdrh   char *zName;                /* Column name */
1615dc5ea5c7Sdrh   int nName;                  /* Size of name in zName[] */
16160315e3ccSdrh   Hash ht;                    /* Hash table of column names */
161779d5f63fSdrh 
16180315e3ccSdrh   sqlite3HashInit(&ht);
16198c2e0f02Sdan   if( pEList ){
16208c2e0f02Sdan     nCol = pEList->nExpr;
16218c2e0f02Sdan     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
16228c2e0f02Sdan     testcase( aCol==0 );
16238c2e0f02Sdan   }else{
16248c2e0f02Sdan     nCol = 0;
16258c2e0f02Sdan     aCol = 0;
16268c2e0f02Sdan   }
16278836cbbcSdan   assert( nCol==(i16)nCol );
16288c2e0f02Sdan   *pnCol = nCol;
16298c2e0f02Sdan   *paCol = aCol;
16308c2e0f02Sdan 
16310315e3ccSdrh   for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
163279d5f63fSdrh     /* Get an appropriate name for the column
163379d5f63fSdrh     */
1634580c8c18Sdrh     p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
163591bb0eedSdrh     if( (zName = pEList->a[i].zName)!=0 ){
163679d5f63fSdrh       /* If the column contains an "AS <name>" phrase, use <name> as the name */
16377d10d5a6Sdrh     }else{
1638dc5ea5c7Sdrh       Expr *pColExpr = p;  /* The expression that is the result column name */
1639dc5ea5c7Sdrh       Table *pTab;         /* Table associated with this expression */
1640b07028f7Sdrh       while( pColExpr->op==TK_DOT ){
1641b07028f7Sdrh         pColExpr = pColExpr->pRight;
1642b07028f7Sdrh         assert( pColExpr!=0 );
1643b07028f7Sdrh       }
1644373cc2ddSdrh       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
164593a960a0Sdrh         /* For columns use the column name name */
1646dc5ea5c7Sdrh         int iCol = pColExpr->iColumn;
1647373cc2ddSdrh         pTab = pColExpr->pTab;
1648f0209f74Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
164996ceaf86Sdrh         zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
1650b7916a78Sdrh       }else if( pColExpr->op==TK_ID ){
165133e619fcSdrh         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
165296ceaf86Sdrh         zName = pColExpr->u.zToken;
165393a960a0Sdrh       }else{
165479d5f63fSdrh         /* Use the original text of the column expression as its name */
165596ceaf86Sdrh         zName = pEList->a[i].zSpan;
16567d10d5a6Sdrh       }
165722f70c32Sdrh     }
165896ceaf86Sdrh     zName = sqlite3MPrintf(db, "%s", zName);
165979d5f63fSdrh 
166079d5f63fSdrh     /* Make sure the column name is unique.  If the name is not unique,
166160ec914cSpeter.d.reid     ** append an integer to the name so that it becomes unique.
166279d5f63fSdrh     */
16630315e3ccSdrh     cnt = 0;
16640315e3ccSdrh     while( zName && sqlite3HashFind(&ht, zName)!=0 ){
16650315e3ccSdrh       nName = sqlite3Strlen30(zName);
1666f7ee8965Sdrh       if( nName>0 ){
16670315e3ccSdrh         for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
16680315e3ccSdrh         if( zName[j]==':' ) nName = j;
1669f7ee8965Sdrh       }
167096ceaf86Sdrh       zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
1671ebed3fa3Sdrh       if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
167279d5f63fSdrh     }
167391bb0eedSdrh     pCol->zName = zName;
1674ba68f8f3Sdan     sqlite3ColumnPropertiesFromName(0, pCol);
167503d69a68Sdrh     if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
16760315e3ccSdrh       db->mallocFailed = 1;
16777d10d5a6Sdrh     }
16780315e3ccSdrh   }
16790315e3ccSdrh   sqlite3HashClear(&ht);
16807d10d5a6Sdrh   if( db->mallocFailed ){
16817d10d5a6Sdrh     for(j=0; j<i; j++){
16827d10d5a6Sdrh       sqlite3DbFree(db, aCol[j].zName);
16837d10d5a6Sdrh     }
16847d10d5a6Sdrh     sqlite3DbFree(db, aCol);
16857d10d5a6Sdrh     *paCol = 0;
16867d10d5a6Sdrh     *pnCol = 0;
16877d10d5a6Sdrh     return SQLITE_NOMEM;
16887d10d5a6Sdrh   }
16897d10d5a6Sdrh   return SQLITE_OK;
16907d10d5a6Sdrh }
1691e014a838Sdanielk1977 
16927d10d5a6Sdrh /*
16937d10d5a6Sdrh ** Add type and collation information to a column list based on
16947d10d5a6Sdrh ** a SELECT statement.
16957d10d5a6Sdrh **
16967d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList().
16977d10d5a6Sdrh ** The column list has only names, not types or collations.  This
16987d10d5a6Sdrh ** routine goes through and adds the types and collations.
16997d10d5a6Sdrh **
1700b08a67a7Sshane ** This routine requires that all identifiers in the SELECT
17017d10d5a6Sdrh ** statement be resolved.
170279d5f63fSdrh */
17037d10d5a6Sdrh static void selectAddColumnTypeAndCollation(
17047d10d5a6Sdrh   Parse *pParse,        /* Parsing contexts */
1705186ad8ccSdrh   Table *pTab,          /* Add column type information to this table */
17067d10d5a6Sdrh   Select *pSelect       /* SELECT used to determine types and collations */
17077d10d5a6Sdrh ){
17087d10d5a6Sdrh   sqlite3 *db = pParse->db;
17097d10d5a6Sdrh   NameContext sNC;
17107d10d5a6Sdrh   Column *pCol;
17117d10d5a6Sdrh   CollSeq *pColl;
17127d10d5a6Sdrh   int i;
17137d10d5a6Sdrh   Expr *p;
17147d10d5a6Sdrh   struct ExprList_item *a;
1715186ad8ccSdrh   u64 szAll = 0;
17167d10d5a6Sdrh 
17177d10d5a6Sdrh   assert( pSelect!=0 );
17187d10d5a6Sdrh   assert( (pSelect->selFlags & SF_Resolved)!=0 );
1719186ad8ccSdrh   assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
17207d10d5a6Sdrh   if( db->mallocFailed ) return;
1721c43e8be8Sdrh   memset(&sNC, 0, sizeof(sNC));
1722b3bce662Sdanielk1977   sNC.pSrcList = pSelect->pSrc;
17237d10d5a6Sdrh   a = pSelect->pEList->a;
1724186ad8ccSdrh   for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
17257d10d5a6Sdrh     p = a[i].pExpr;
17261cb50c88Sdrh     if( pCol->zType==0 ){
172738b4149cSdrh       pCol->zType = sqlite3DbStrDup(db,
172838b4149cSdrh                         columnType(&sNC, p,0,0,0, &pCol->szEst));
17291cb50c88Sdrh     }
1730186ad8ccSdrh     szAll += pCol->szEst;
1731c60e9b82Sdanielk1977     pCol->affinity = sqlite3ExprAffinity(p);
173205883a34Sdrh     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
1733b3bf556eSdanielk1977     pColl = sqlite3ExprCollSeq(pParse, p);
17341cb50c88Sdrh     if( pColl && pCol->zColl==0 ){
173517435752Sdrh       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
17360202b29eSdanielk1977     }
173722f70c32Sdrh   }
1738186ad8ccSdrh   pTab->szTabRow = sqlite3LogEst(szAll*4);
17397d10d5a6Sdrh }
17407d10d5a6Sdrh 
17417d10d5a6Sdrh /*
17427d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes
17437d10d5a6Sdrh ** the result set of that SELECT.
17447d10d5a6Sdrh */
17457d10d5a6Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
17467d10d5a6Sdrh   Table *pTab;
17477d10d5a6Sdrh   sqlite3 *db = pParse->db;
17487d10d5a6Sdrh   int savedFlags;
17497d10d5a6Sdrh 
17507d10d5a6Sdrh   savedFlags = db->flags;
17517d10d5a6Sdrh   db->flags &= ~SQLITE_FullColNames;
17527d10d5a6Sdrh   db->flags |= SQLITE_ShortColNames;
17537d10d5a6Sdrh   sqlite3SelectPrep(pParse, pSelect, 0);
17547d10d5a6Sdrh   if( pParse->nErr ) return 0;
17557d10d5a6Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
17567d10d5a6Sdrh   db->flags = savedFlags;
17577d10d5a6Sdrh   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
17587d10d5a6Sdrh   if( pTab==0 ){
17597d10d5a6Sdrh     return 0;
17607d10d5a6Sdrh   }
1761373cc2ddSdrh   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
1762b2468954Sdrh   ** is disabled */
1763373cc2ddSdrh   assert( db->lookaside.bEnabled==0 );
17647d10d5a6Sdrh   pTab->nRef = 1;
17657d10d5a6Sdrh   pTab->zName = 0;
1766cfc9df76Sdan   pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
17678981b904Sdrh   sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
1768186ad8ccSdrh   selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
176922f70c32Sdrh   pTab->iPKey = -1;
17707ce72f69Sdrh   if( db->mallocFailed ){
17711feeaed2Sdan     sqlite3DeleteTable(db, pTab);
17727ce72f69Sdrh     return 0;
17737ce72f69Sdrh   }
177422f70c32Sdrh   return pTab;
177522f70c32Sdrh }
177622f70c32Sdrh 
177722f70c32Sdrh /*
1778d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1779d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1780d8bc7086Sdrh */
17814adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1782d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1783d8bc7086Sdrh   if( v==0 ){
17849ac7962aSdrh     v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
1785aceb31b1Sdrh     if( v ) sqlite3VdbeAddOp0(v, OP_Init);
1786e0e261a4Sdrh     if( pParse->pToplevel==0
1787e0e261a4Sdrh      && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
1788e0e261a4Sdrh     ){
1789e0e261a4Sdrh       pParse->okConstFactor = 1;
1790949f9cd5Sdrh     }
1791e0e261a4Sdrh 
1792d8bc7086Sdrh   }
1793d8bc7086Sdrh   return v;
1794d8bc7086Sdrh }
1795d8bc7086Sdrh 
179615007a99Sdrh 
1797d8bc7086Sdrh /*
17987b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
1799ec7429aeSdrh ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
18007b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
1801a2dc3b1aSdanielk1977 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1802a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute
1803a2dc3b1aSdanielk1977 ** the limit and offset.  If there is no limit and/or offset, then
1804a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative.
18057b58daeaSdrh **
1806d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if
1807ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset.  iLimit and
1808aa9ce707Sdrh ** iOffset should have been preset to appropriate default values (zero)
1809aa9ce707Sdrh ** prior to calling this routine.
1810aa9ce707Sdrh **
1811aa9ce707Sdrh ** The iOffset register (if it exists) is initialized to the value
1812aa9ce707Sdrh ** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
1813aa9ce707Sdrh ** iOffset+1 is initialized to LIMIT+OFFSET.
1814aa9ce707Sdrh **
1815ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
18167b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
18177b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
18187b58daeaSdrh ** SELECT statements.
18197b58daeaSdrh */
1820ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
182102afc861Sdrh   Vdbe *v = 0;
182202afc861Sdrh   int iLimit = 0;
182315007a99Sdrh   int iOffset;
18248b0cf38aSdrh   int n;
18250acb7e48Sdrh   if( p->iLimit ) return;
182615007a99Sdrh 
18277b58daeaSdrh   /*
18287b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
1829f7b5496eSdrh   ** controversy about what the correct behavior should be.
18307b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
18317b58daeaSdrh   ** no rows.
18327b58daeaSdrh   */
1833ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
1834373cc2ddSdrh   assert( p->pOffset==0 || p->pLimit!=0 );
1835a2dc3b1aSdanielk1977   if( p->pLimit ){
18360a07c107Sdrh     p->iLimit = iLimit = ++pParse->nMem;
183715007a99Sdrh     v = sqlite3GetVdbe(pParse);
1838aa9ce707Sdrh     assert( v!=0 );
18399b918ed1Sdrh     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
18409b918ed1Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
18419b918ed1Sdrh       VdbeComment((v, "LIMIT counter"));
1842456e4e4fSdrh       if( n==0 ){
1843076e85f5Sdrh         sqlite3VdbeGoto(v, iBreak);
1844613ba1eaSdrh       }else if( n>=0 && p->nSelectRow>(u64)n ){
1845613ba1eaSdrh         p->nSelectRow = n;
18469b918ed1Sdrh       }
18479b918ed1Sdrh     }else{
1848b7654111Sdrh       sqlite3ExprCode(pParse, p->pLimit, iLimit);
1849688852abSdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
1850d4e70ebdSdrh       VdbeComment((v, "LIMIT counter"));
185116897072Sdrh       sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
18529b918ed1Sdrh     }
1853a2dc3b1aSdanielk1977     if( p->pOffset ){
18540a07c107Sdrh       p->iOffset = iOffset = ++pParse->nMem;
1855b7654111Sdrh       pParse->nMem++;   /* Allocate an extra register for limit+offset */
1856b7654111Sdrh       sqlite3ExprCode(pParse, p->pOffset, iOffset);
1857688852abSdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
1858d4e70ebdSdrh       VdbeComment((v, "OFFSET counter"));
18598b0cf38aSdrh       sqlite3VdbeAddOp3(v, OP_SetIfNotPos, iOffset, iOffset, 0);
1860b7654111Sdrh       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
1861d4e70ebdSdrh       VdbeComment((v, "LIMIT+OFFSET"));
18628b0cf38aSdrh       sqlite3VdbeAddOp3(v, OP_SetIfNotPos, iLimit, iOffset+1, -1);
1863b7654111Sdrh     }
1864d59ba6ceSdrh   }
18657b58daeaSdrh }
18667b58daeaSdrh 
1867b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1868fbc4ee7bSdrh /*
1869fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
1870fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
1871fbc4ee7bSdrh ** the column has no default collating sequence.
1872fbc4ee7bSdrh **
1873fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
1874fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
1875fbc4ee7bSdrh */
1876dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1877fbc4ee7bSdrh   CollSeq *pRet;
1878dc1bdc4fSdanielk1977   if( p->pPrior ){
1879dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1880fbc4ee7bSdrh   }else{
1881fbc4ee7bSdrh     pRet = 0;
1882dc1bdc4fSdanielk1977   }
188310c081adSdrh   assert( iCol>=0 );
18842ec18a3cSdrh   /* iCol must be less than p->pEList->nExpr.  Otherwise an error would
18852ec18a3cSdrh   ** have been thrown during name resolution and we would not have gotten
18862ec18a3cSdrh   ** this far */
18872ec18a3cSdrh   if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
1888dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1889dc1bdc4fSdanielk1977   }
1890dc1bdc4fSdanielk1977   return pRet;
1891d3d39e93Sdrh }
1892d3d39e93Sdrh 
189353bed45eSdan /*
189453bed45eSdan ** The select statement passed as the second parameter is a compound SELECT
189553bed45eSdan ** with an ORDER BY clause. This function allocates and returns a KeyInfo
189653bed45eSdan ** structure suitable for implementing the ORDER BY.
189753bed45eSdan **
189853bed45eSdan ** Space to hold the KeyInfo structure is obtained from malloc. The calling
189953bed45eSdan ** function is responsible for ensuring that this structure is eventually
190053bed45eSdan ** freed.
190153bed45eSdan */
190253bed45eSdan static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
190353bed45eSdan   ExprList *pOrderBy = p->pOrderBy;
190453bed45eSdan   int nOrderBy = p->pOrderBy->nExpr;
190553bed45eSdan   sqlite3 *db = pParse->db;
190653bed45eSdan   KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
190753bed45eSdan   if( pRet ){
190853bed45eSdan     int i;
190953bed45eSdan     for(i=0; i<nOrderBy; i++){
191053bed45eSdan       struct ExprList_item *pItem = &pOrderBy->a[i];
191153bed45eSdan       Expr *pTerm = pItem->pExpr;
191253bed45eSdan       CollSeq *pColl;
191353bed45eSdan 
191453bed45eSdan       if( pTerm->flags & EP_Collate ){
191553bed45eSdan         pColl = sqlite3ExprCollSeq(pParse, pTerm);
191653bed45eSdan       }else{
191753bed45eSdan         pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
191853bed45eSdan         if( pColl==0 ) pColl = db->pDfltColl;
191953bed45eSdan         pOrderBy->a[i].pExpr =
192053bed45eSdan           sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
192153bed45eSdan       }
192253bed45eSdan       assert( sqlite3KeyInfoIsWriteable(pRet) );
192353bed45eSdan       pRet->aColl[i] = pColl;
192453bed45eSdan       pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
192553bed45eSdan     }
192653bed45eSdan   }
192753bed45eSdan 
192853bed45eSdan   return pRet;
192953bed45eSdan }
1930d3d39e93Sdrh 
1931781def29Sdrh #ifndef SQLITE_OMIT_CTE
1932781def29Sdrh /*
1933781def29Sdrh ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
1934781def29Sdrh ** query of the form:
1935781def29Sdrh **
1936781def29Sdrh **   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
1937781def29Sdrh **                         \___________/             \_______________/
1938781def29Sdrh **                           p->pPrior                      p
1939781def29Sdrh **
1940781def29Sdrh **
1941781def29Sdrh ** There is exactly one reference to the recursive-table in the FROM clause
19428a48b9c0Sdrh ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
1943781def29Sdrh **
1944781def29Sdrh ** The setup-query runs once to generate an initial set of rows that go
1945781def29Sdrh ** into a Queue table.  Rows are extracted from the Queue table one by
1946fe1c6bb9Sdrh ** one.  Each row extracted from Queue is output to pDest.  Then the single
1947fe1c6bb9Sdrh ** extracted row (now in the iCurrent table) becomes the content of the
1948fe1c6bb9Sdrh ** recursive-table for a recursive-query run.  The output of the recursive-query
1949781def29Sdrh ** is added back into the Queue table.  Then another row is extracted from Queue
1950781def29Sdrh ** and the iteration continues until the Queue table is empty.
1951781def29Sdrh **
1952781def29Sdrh ** If the compound query operator is UNION then no duplicate rows are ever
1953781def29Sdrh ** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
1954781def29Sdrh ** that have ever been inserted into Queue and causes duplicates to be
1955781def29Sdrh ** discarded.  If the operator is UNION ALL, then duplicates are allowed.
1956781def29Sdrh **
1957781def29Sdrh ** If the query has an ORDER BY, then entries in the Queue table are kept in
1958781def29Sdrh ** ORDER BY order and the first entry is extracted for each cycle.  Without
1959781def29Sdrh ** an ORDER BY, the Queue table is just a FIFO.
1960781def29Sdrh **
1961781def29Sdrh ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
1962781def29Sdrh ** have been output to pDest.  A LIMIT of zero means to output no rows and a
1963781def29Sdrh ** negative LIMIT means to output all rows.  If there is also an OFFSET clause
1964781def29Sdrh ** with a positive value, then the first OFFSET outputs are discarded rather
1965781def29Sdrh ** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
1966781def29Sdrh ** rows have been skipped.
1967781def29Sdrh */
1968781def29Sdrh static void generateWithRecursiveQuery(
1969781def29Sdrh   Parse *pParse,        /* Parsing context */
1970781def29Sdrh   Select *p,            /* The recursive SELECT to be coded */
1971781def29Sdrh   SelectDest *pDest     /* What to do with query results */
1972781def29Sdrh ){
1973781def29Sdrh   SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
1974781def29Sdrh   int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
1975781def29Sdrh   Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
1976781def29Sdrh   Select *pSetup = p->pPrior;   /* The setup query */
1977781def29Sdrh   int addrTop;                  /* Top of the loop */
1978781def29Sdrh   int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
1979edf83d1eSdrh   int iCurrent = 0;             /* The Current table */
1980781def29Sdrh   int regCurrent;               /* Register holding Current table */
1981781def29Sdrh   int iQueue;                   /* The Queue table */
1982781def29Sdrh   int iDistinct = 0;            /* To ensure unique results if UNION */
19838e1ee88cSdrh   int eDest = SRT_Fifo;         /* How to write to Queue */
1984781def29Sdrh   SelectDest destQueue;         /* SelectDest targetting the Queue table */
1985781def29Sdrh   int i;                        /* Loop counter */
1986781def29Sdrh   int rc;                       /* Result code */
1987fe1c6bb9Sdrh   ExprList *pOrderBy;           /* The ORDER BY clause */
1988aa9ce707Sdrh   Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
1989aa9ce707Sdrh   int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
1990781def29Sdrh 
1991781def29Sdrh   /* Obtain authorization to do a recursive query */
1992781def29Sdrh   if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
1993781def29Sdrh 
1994aa9ce707Sdrh   /* Process the LIMIT and OFFSET clauses, if they exist */
1995aa9ce707Sdrh   addrBreak = sqlite3VdbeMakeLabel(v);
1996aa9ce707Sdrh   computeLimitRegisters(pParse, p, addrBreak);
1997aa9ce707Sdrh   pLimit = p->pLimit;
1998aa9ce707Sdrh   pOffset = p->pOffset;
1999aa9ce707Sdrh   regLimit = p->iLimit;
2000aa9ce707Sdrh   regOffset = p->iOffset;
2001aa9ce707Sdrh   p->pLimit = p->pOffset = 0;
2002aa9ce707Sdrh   p->iLimit = p->iOffset = 0;
200353bed45eSdan   pOrderBy = p->pOrderBy;
2004781def29Sdrh 
2005781def29Sdrh   /* Locate the cursor number of the Current table */
2006781def29Sdrh   for(i=0; ALWAYS(i<pSrc->nSrc); i++){
20078a48b9c0Sdrh     if( pSrc->a[i].fg.isRecursive ){
2008781def29Sdrh       iCurrent = pSrc->a[i].iCursor;
2009781def29Sdrh       break;
2010781def29Sdrh     }
2011781def29Sdrh   }
2012781def29Sdrh 
2013fe1c6bb9Sdrh   /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
2014781def29Sdrh   ** the Distinct table must be exactly one greater than Queue in order
20158e1ee88cSdrh   ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
2016781def29Sdrh   iQueue = pParse->nTab++;
2017781def29Sdrh   if( p->op==TK_UNION ){
20188e1ee88cSdrh     eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
2019781def29Sdrh     iDistinct = pParse->nTab++;
2020fe1c6bb9Sdrh   }else{
20218e1ee88cSdrh     eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
2022781def29Sdrh   }
2023781def29Sdrh   sqlite3SelectDestInit(&destQueue, eDest, iQueue);
2024781def29Sdrh 
2025781def29Sdrh   /* Allocate cursors for Current, Queue, and Distinct. */
2026781def29Sdrh   regCurrent = ++pParse->nMem;
2027781def29Sdrh   sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
2028fe1c6bb9Sdrh   if( pOrderBy ){
202953bed45eSdan     KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
2030fe1c6bb9Sdrh     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
2031fe1c6bb9Sdrh                       (char*)pKeyInfo, P4_KEYINFO);
2032fe1c6bb9Sdrh     destQueue.pOrderBy = pOrderBy;
2033fe1c6bb9Sdrh   }else{
2034781def29Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
2035fe1c6bb9Sdrh   }
2036fe1c6bb9Sdrh   VdbeComment((v, "Queue table"));
2037781def29Sdrh   if( iDistinct ){
2038781def29Sdrh     p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
2039781def29Sdrh     p->selFlags |= SF_UsesEphemeral;
2040781def29Sdrh   }
2041781def29Sdrh 
204253bed45eSdan   /* Detach the ORDER BY clause from the compound SELECT */
204353bed45eSdan   p->pOrderBy = 0;
204453bed45eSdan 
2045781def29Sdrh   /* Store the results of the setup-query in Queue. */
2046d227a291Sdrh   pSetup->pNext = 0;
2047781def29Sdrh   rc = sqlite3Select(pParse, pSetup, &destQueue);
2048d227a291Sdrh   pSetup->pNext = p;
2049fe1c6bb9Sdrh   if( rc ) goto end_of_recursive_query;
2050781def29Sdrh 
2051781def29Sdrh   /* Find the next row in the Queue and output that row */
2052688852abSdrh   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
2053781def29Sdrh 
2054781def29Sdrh   /* Transfer the next row in Queue over to Current */
2055781def29Sdrh   sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
2056fe1c6bb9Sdrh   if( pOrderBy ){
2057fe1c6bb9Sdrh     sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
2058fe1c6bb9Sdrh   }else{
2059781def29Sdrh     sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
2060fe1c6bb9Sdrh   }
2061781def29Sdrh   sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
2062781def29Sdrh 
2063fe1c6bb9Sdrh   /* Output the single row in Current */
2064fe1c6bb9Sdrh   addrCont = sqlite3VdbeMakeLabel(v);
2065aa9ce707Sdrh   codeOffset(v, regOffset, addrCont);
2066fe1c6bb9Sdrh   selectInnerLoop(pParse, p, p->pEList, iCurrent,
2067079a3072Sdrh       0, 0, pDest, addrCont, addrBreak);
2068688852abSdrh   if( regLimit ){
206916897072Sdrh     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
2070688852abSdrh     VdbeCoverage(v);
2071688852abSdrh   }
2072fe1c6bb9Sdrh   sqlite3VdbeResolveLabel(v, addrCont);
2073fe1c6bb9Sdrh 
2074781def29Sdrh   /* Execute the recursive SELECT taking the single row in Current as
2075781def29Sdrh   ** the value for the recursive-table. Store the results in the Queue.
2076781def29Sdrh   */
2077b63ce02fSdrh   if( p->selFlags & SF_Aggregate ){
2078b63ce02fSdrh     sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
2079b63ce02fSdrh   }else{
2080781def29Sdrh     p->pPrior = 0;
2081781def29Sdrh     sqlite3Select(pParse, p, &destQueue);
2082781def29Sdrh     assert( p->pPrior==0 );
2083781def29Sdrh     p->pPrior = pSetup;
2084b63ce02fSdrh   }
2085781def29Sdrh 
2086781def29Sdrh   /* Keep running the loop until the Queue is empty */
2087076e85f5Sdrh   sqlite3VdbeGoto(v, addrTop);
2088781def29Sdrh   sqlite3VdbeResolveLabel(v, addrBreak);
2089fe1c6bb9Sdrh 
2090fe1c6bb9Sdrh end_of_recursive_query:
20919afccba2Sdan   sqlite3ExprListDelete(pParse->db, p->pOrderBy);
2092fe1c6bb9Sdrh   p->pOrderBy = pOrderBy;
2093aa9ce707Sdrh   p->pLimit = pLimit;
2094aa9ce707Sdrh   p->pOffset = pOffset;
2095fe1c6bb9Sdrh   return;
2096781def29Sdrh }
2097b68b9778Sdan #endif /* SQLITE_OMIT_CTE */
2098781def29Sdrh 
2099781def29Sdrh /* Forward references */
2100b21e7c70Sdrh static int multiSelectOrderBy(
2101b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
2102b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
2103a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
2104b21e7c70Sdrh );
2105b21e7c70Sdrh 
210645f54a57Sdrh /*
210745f54a57Sdrh ** Handle the special case of a compound-select that originates from a
210845f54a57Sdrh ** VALUES clause.  By handling this as a special case, we avoid deep
210945f54a57Sdrh ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
211045f54a57Sdrh ** on a VALUES clause.
211145f54a57Sdrh **
211245f54a57Sdrh ** Because the Select object originates from a VALUES clause:
211345f54a57Sdrh **   (1) It has no LIMIT or OFFSET
211445f54a57Sdrh **   (2) All terms are UNION ALL
211545f54a57Sdrh **   (3) There is no ORDER BY clause
211645f54a57Sdrh */
211745f54a57Sdrh static int multiSelectValues(
211845f54a57Sdrh   Parse *pParse,        /* Parsing context */
211945f54a57Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
212045f54a57Sdrh   SelectDest *pDest     /* What to do with query results */
212145f54a57Sdrh ){
212245f54a57Sdrh   Select *pPrior;
212345f54a57Sdrh   int nRow = 1;
212445f54a57Sdrh   int rc = 0;
2125772460fdSdrh   assert( p->selFlags & SF_MultiValue );
212645f54a57Sdrh   do{
212745f54a57Sdrh     assert( p->selFlags & SF_Values );
212845f54a57Sdrh     assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
212945f54a57Sdrh     assert( p->pLimit==0 );
213045f54a57Sdrh     assert( p->pOffset==0 );
2131923cadb1Sdan     assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
213245f54a57Sdrh     if( p->pPrior==0 ) break;
213345f54a57Sdrh     assert( p->pPrior->pNext==p );
213445f54a57Sdrh     p = p->pPrior;
213545f54a57Sdrh     nRow++;
213645f54a57Sdrh   }while(1);
213745f54a57Sdrh   while( p ){
213845f54a57Sdrh     pPrior = p->pPrior;
213945f54a57Sdrh     p->pPrior = 0;
214045f54a57Sdrh     rc = sqlite3Select(pParse, p, pDest);
214145f54a57Sdrh     p->pPrior = pPrior;
214245f54a57Sdrh     if( rc ) break;
214345f54a57Sdrh     p->nSelectRow = nRow;
214445f54a57Sdrh     p = p->pNext;
214545f54a57Sdrh   }
214645f54a57Sdrh   return rc;
214745f54a57Sdrh }
2148b21e7c70Sdrh 
2149d3d39e93Sdrh /*
215016ee60ffSdrh ** This routine is called to process a compound query form from
215116ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
215216ee60ffSdrh ** INTERSECT
2153c926afbcSdrh **
2154e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
2155e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
2156e78e8284Sdrh ** in which case this routine will be called recursively.
2157e78e8284Sdrh **
2158e78e8284Sdrh ** The results of the total query are to be written into a destination
2159e78e8284Sdrh ** of type eDest with parameter iParm.
2160e78e8284Sdrh **
2161e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
2162e78e8284Sdrh **
2163e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
2164e78e8284Sdrh **
2165e78e8284Sdrh ** This statement is parsed up as follows:
2166e78e8284Sdrh **
2167e78e8284Sdrh **     SELECT c FROM t3
2168e78e8284Sdrh **      |
2169e78e8284Sdrh **      `----->  SELECT b FROM t2
2170e78e8284Sdrh **                |
21714b11c6d3Sjplyon **                `------>  SELECT a FROM t1
2172e78e8284Sdrh **
2173e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
2174e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
2175e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
2176e78e8284Sdrh **
2177e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
2178e78e8284Sdrh ** individual selects always group from left to right.
217982c3d636Sdrh */
218084ac9d02Sdanielk1977 static int multiSelect(
2181fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
2182fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
2183a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
218484ac9d02Sdanielk1977 ){
218584ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
218610e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
218710e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
21881013c932Sdrh   SelectDest dest;      /* Alternative data destination */
2189eca7e01aSdanielk1977   Select *pDelete = 0;  /* Chain of simple selects to delete */
2190633e6d57Sdrh   sqlite3 *db;          /* Database connection */
21917f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN
2192edf83d1eSdrh   int iSub1 = 0;        /* EQP id of left-hand query */
2193edf83d1eSdrh   int iSub2 = 0;        /* EQP id of right-hand query */
21947f61e92cSdan #endif
219582c3d636Sdrh 
21967b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
2197fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
219882c3d636Sdrh   */
2199701bb3b4Sdrh   assert( p && p->pPrior );  /* Calling function guarantees this much */
2200eae73fbfSdan   assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
2201633e6d57Sdrh   db = pParse->db;
2202d8bc7086Sdrh   pPrior = p->pPrior;
2203bc10377aSdrh   dest = *pDest;
2204d8bc7086Sdrh   if( pPrior->pOrderBy ){
22054adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
2206da93d238Sdrh       selectOpName(p->op));
220784ac9d02Sdanielk1977     rc = 1;
220884ac9d02Sdanielk1977     goto multi_select_end;
220982c3d636Sdrh   }
2210a2dc3b1aSdanielk1977   if( pPrior->pLimit ){
22114adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
22127b58daeaSdrh       selectOpName(p->op));
221384ac9d02Sdanielk1977     rc = 1;
221484ac9d02Sdanielk1977     goto multi_select_end;
22157b58daeaSdrh   }
221682c3d636Sdrh 
22174adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
2218701bb3b4Sdrh   assert( v!=0 );  /* The VDBE already created by calling function */
2219d8bc7086Sdrh 
22201cc3d75fSdrh   /* Create the destination temporary table if necessary
22211cc3d75fSdrh   */
22226c8c8ce0Sdanielk1977   if( dest.eDest==SRT_EphemTab ){
2223b4964b72Sdanielk1977     assert( p->pEList );
22242b596da8Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
2225d4187c71Sdrh     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
22266c8c8ce0Sdanielk1977     dest.eDest = SRT_Table;
22271cc3d75fSdrh   }
22281cc3d75fSdrh 
222945f54a57Sdrh   /* Special handling for a compound-select that originates as a VALUES clause.
223045f54a57Sdrh   */
2231772460fdSdrh   if( p->selFlags & SF_MultiValue ){
223245f54a57Sdrh     rc = multiSelectValues(pParse, p, &dest);
223345f54a57Sdrh     goto multi_select_end;
223445f54a57Sdrh   }
223545f54a57Sdrh 
2236f6e369a1Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
2237f6e369a1Sdrh   ** in their result sets.
2238f6e369a1Sdrh   */
2239f6e369a1Sdrh   assert( p->pEList && pPrior->pEList );
2240923cadb1Sdan   assert( p->pEList->nExpr==pPrior->pEList->nExpr );
2241f6e369a1Sdrh 
2242eede6a53Sdan #ifndef SQLITE_OMIT_CTE
2243eae73fbfSdan   if( p->selFlags & SF_Recursive ){
2244781def29Sdrh     generateWithRecursiveQuery(pParse, p, &dest);
22458ce7184bSdan   }else
22468ce7184bSdan #endif
2247f6e369a1Sdrh 
2248a9671a22Sdrh   /* Compound SELECTs that have an ORDER BY clause are handled separately.
2249a9671a22Sdrh   */
2250f6e369a1Sdrh   if( p->pOrderBy ){
2251a9671a22Sdrh     return multiSelectOrderBy(pParse, p, pDest);
2252eede6a53Sdan   }else
2253f6e369a1Sdrh 
2254f46f905aSdrh   /* Generate code for the left and right SELECT statements.
2255d8bc7086Sdrh   */
225682c3d636Sdrh   switch( p->op ){
2257f46f905aSdrh     case TK_ALL: {
2258ec7429aeSdrh       int addr = 0;
225995aa47b1Sdrh       int nLimit;
2260a2dc3b1aSdanielk1977       assert( !pPrior->pLimit );
2261547180baSdrh       pPrior->iLimit = p->iLimit;
2262547180baSdrh       pPrior->iOffset = p->iOffset;
2263a2dc3b1aSdanielk1977       pPrior->pLimit = p->pLimit;
2264a2dc3b1aSdanielk1977       pPrior->pOffset = p->pOffset;
22657f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
22667d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &dest);
2267ad68cb6bSdanielk1977       p->pLimit = 0;
2268ad68cb6bSdanielk1977       p->pOffset = 0;
226984ac9d02Sdanielk1977       if( rc ){
227084ac9d02Sdanielk1977         goto multi_select_end;
227184ac9d02Sdanielk1977       }
2272f46f905aSdrh       p->pPrior = 0;
22737b58daeaSdrh       p->iLimit = pPrior->iLimit;
22747b58daeaSdrh       p->iOffset = pPrior->iOffset;
227592b01d53Sdrh       if( p->iLimit ){
227616897072Sdrh         addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
2277d4e70ebdSdrh         VdbeComment((v, "Jump ahead if LIMIT reached"));
22789f1ef45fSdrh         if( p->iOffset ){
22798b0cf38aSdrh           sqlite3VdbeAddOp3(v, OP_SetIfNotPos, p->iOffset, p->iOffset, 0);
22809f1ef45fSdrh           sqlite3VdbeAddOp3(v, OP_Add, p->iLimit, p->iOffset, p->iOffset+1);
22818b0cf38aSdrh           sqlite3VdbeAddOp3(v, OP_SetIfNotPos, p->iLimit, p->iOffset+1, -1);
22829f1ef45fSdrh         }
2283ec7429aeSdrh       }
22847f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
22857d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &dest);
2286373cc2ddSdrh       testcase( rc!=SQLITE_OK );
2287eca7e01aSdanielk1977       pDelete = p->pPrior;
2288f46f905aSdrh       p->pPrior = pPrior;
228995aa47b1Sdrh       p->nSelectRow += pPrior->nSelectRow;
229095aa47b1Sdrh       if( pPrior->pLimit
229195aa47b1Sdrh        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
2292613ba1eaSdrh        && nLimit>0 && p->nSelectRow > (u64)nLimit
229395aa47b1Sdrh       ){
2294c63367efSdrh         p->nSelectRow = nLimit;
229595aa47b1Sdrh       }
2296ec7429aeSdrh       if( addr ){
2297ec7429aeSdrh         sqlite3VdbeJumpHere(v, addr);
2298ec7429aeSdrh       }
2299f46f905aSdrh       break;
2300f46f905aSdrh     }
230182c3d636Sdrh     case TK_EXCEPT:
230282c3d636Sdrh     case TK_UNION: {
2303d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
2304ea678832Sdrh       u8 op = 0;       /* One of the SRT_ operations to apply to self */
2305d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
2306a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
2307dc1bdc4fSdanielk1977       int addr;
23086c8c8ce0Sdanielk1977       SelectDest uniondest;
230982c3d636Sdrh 
2310373cc2ddSdrh       testcase( p->op==TK_EXCEPT );
2311373cc2ddSdrh       testcase( p->op==TK_UNION );
231293a960a0Sdrh       priorOp = SRT_Union;
2313d227a291Sdrh       if( dest.eDest==priorOp ){
2314d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
2315c926afbcSdrh         ** right.
2316d8bc7086Sdrh         */
2317e2f02bacSdrh         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
2318e2f02bacSdrh         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
23192b596da8Sdrh         unionTab = dest.iSDParm;
232082c3d636Sdrh       }else{
2321d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
2322d8bc7086Sdrh         ** intermediate results.
2323d8bc7086Sdrh         */
232482c3d636Sdrh         unionTab = pParse->nTab++;
232593a960a0Sdrh         assert( p->pOrderBy==0 );
232666a5167bSdrh         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
2327b9bb7c18Sdrh         assert( p->addrOpenEphm[0] == -1 );
2328b9bb7c18Sdrh         p->addrOpenEphm[0] = addr;
2329d227a291Sdrh         findRightmost(p)->selFlags |= SF_UsesEphemeral;
233084ac9d02Sdanielk1977         assert( p->pEList );
2331d8bc7086Sdrh       }
2332d8bc7086Sdrh 
2333d8bc7086Sdrh       /* Code the SELECT statements to our left
2334d8bc7086Sdrh       */
2335b3bce662Sdanielk1977       assert( !pPrior->pOrderBy );
23361013c932Sdrh       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
23377f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
23387d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &uniondest);
233984ac9d02Sdanielk1977       if( rc ){
234084ac9d02Sdanielk1977         goto multi_select_end;
234184ac9d02Sdanielk1977       }
2342d8bc7086Sdrh 
2343d8bc7086Sdrh       /* Code the current SELECT statement
2344d8bc7086Sdrh       */
23454cfb22f7Sdrh       if( p->op==TK_EXCEPT ){
23464cfb22f7Sdrh         op = SRT_Except;
23474cfb22f7Sdrh       }else{
23484cfb22f7Sdrh         assert( p->op==TK_UNION );
23494cfb22f7Sdrh         op = SRT_Union;
2350d8bc7086Sdrh       }
235182c3d636Sdrh       p->pPrior = 0;
2352a2dc3b1aSdanielk1977       pLimit = p->pLimit;
2353a2dc3b1aSdanielk1977       p->pLimit = 0;
2354a2dc3b1aSdanielk1977       pOffset = p->pOffset;
2355a2dc3b1aSdanielk1977       p->pOffset = 0;
23566c8c8ce0Sdanielk1977       uniondest.eDest = op;
23577f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
23587d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &uniondest);
2359373cc2ddSdrh       testcase( rc!=SQLITE_OK );
23605bd1bf2eSdrh       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
23615bd1bf2eSdrh       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
2362633e6d57Sdrh       sqlite3ExprListDelete(db, p->pOrderBy);
2363eca7e01aSdanielk1977       pDelete = p->pPrior;
236482c3d636Sdrh       p->pPrior = pPrior;
2365a9671a22Sdrh       p->pOrderBy = 0;
236695aa47b1Sdrh       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
2367633e6d57Sdrh       sqlite3ExprDelete(db, p->pLimit);
2368a2dc3b1aSdanielk1977       p->pLimit = pLimit;
2369a2dc3b1aSdanielk1977       p->pOffset = pOffset;
237092b01d53Sdrh       p->iLimit = 0;
237192b01d53Sdrh       p->iOffset = 0;
2372d8bc7086Sdrh 
2373d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
2374d8bc7086Sdrh       ** it is that we currently need.
2375d8bc7086Sdrh       */
23762b596da8Sdrh       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
2377373cc2ddSdrh       if( dest.eDest!=priorOp ){
23786b56344dSdrh         int iCont, iBreak, iStart;
237982c3d636Sdrh         assert( p->pEList );
23807d10d5a6Sdrh         if( dest.eDest==SRT_Output ){
238192378253Sdrh           Select *pFirst = p;
238292378253Sdrh           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
23839a8941fcSdan           generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
238441202ccaSdrh         }
23854adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
23864adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
2387ec7429aeSdrh         computeLimitRegisters(pParse, p, iBreak);
2388688852abSdrh         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
23894adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
2390340309fdSdrh         selectInnerLoop(pParse, p, p->pEList, unionTab,
2391e8e4af76Sdrh                         0, 0, &dest, iCont, iBreak);
23924adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
2393688852abSdrh         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
23944adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
239566a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
239682c3d636Sdrh       }
239782c3d636Sdrh       break;
239882c3d636Sdrh     }
2399373cc2ddSdrh     default: assert( p->op==TK_INTERSECT ); {
240082c3d636Sdrh       int tab1, tab2;
24016b56344dSdrh       int iCont, iBreak, iStart;
2402a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset;
2403dc1bdc4fSdanielk1977       int addr;
24041013c932Sdrh       SelectDest intersectdest;
24059cbf3425Sdrh       int r1;
240682c3d636Sdrh 
2407d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
24086206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
2409d8bc7086Sdrh       ** by allocating the tables we will need.
2410d8bc7086Sdrh       */
241182c3d636Sdrh       tab1 = pParse->nTab++;
241282c3d636Sdrh       tab2 = pParse->nTab++;
241393a960a0Sdrh       assert( p->pOrderBy==0 );
2414dc1bdc4fSdanielk1977 
241566a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
2416b9bb7c18Sdrh       assert( p->addrOpenEphm[0] == -1 );
2417b9bb7c18Sdrh       p->addrOpenEphm[0] = addr;
2418d227a291Sdrh       findRightmost(p)->selFlags |= SF_UsesEphemeral;
241984ac9d02Sdanielk1977       assert( p->pEList );
2420d8bc7086Sdrh 
2421d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
2422d8bc7086Sdrh       */
24231013c932Sdrh       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
24247f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
24257d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &intersectdest);
242684ac9d02Sdanielk1977       if( rc ){
242784ac9d02Sdanielk1977         goto multi_select_end;
242884ac9d02Sdanielk1977       }
2429d8bc7086Sdrh 
2430d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
2431d8bc7086Sdrh       */
243266a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
2433b9bb7c18Sdrh       assert( p->addrOpenEphm[1] == -1 );
2434b9bb7c18Sdrh       p->addrOpenEphm[1] = addr;
243582c3d636Sdrh       p->pPrior = 0;
2436a2dc3b1aSdanielk1977       pLimit = p->pLimit;
2437a2dc3b1aSdanielk1977       p->pLimit = 0;
2438a2dc3b1aSdanielk1977       pOffset = p->pOffset;
2439a2dc3b1aSdanielk1977       p->pOffset = 0;
24402b596da8Sdrh       intersectdest.iSDParm = tab2;
24417f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
24427d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &intersectdest);
2443373cc2ddSdrh       testcase( rc!=SQLITE_OK );
2444eca7e01aSdanielk1977       pDelete = p->pPrior;
244582c3d636Sdrh       p->pPrior = pPrior;
244695aa47b1Sdrh       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
2447633e6d57Sdrh       sqlite3ExprDelete(db, p->pLimit);
2448a2dc3b1aSdanielk1977       p->pLimit = pLimit;
2449a2dc3b1aSdanielk1977       p->pOffset = pOffset;
2450d8bc7086Sdrh 
2451d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
2452d8bc7086Sdrh       ** tables.
2453d8bc7086Sdrh       */
245482c3d636Sdrh       assert( p->pEList );
24557d10d5a6Sdrh       if( dest.eDest==SRT_Output ){
245692378253Sdrh         Select *pFirst = p;
245792378253Sdrh         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
24589a8941fcSdan         generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
245941202ccaSdrh       }
24604adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
24614adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
2462ec7429aeSdrh       computeLimitRegisters(pParse, p, iBreak);
2463688852abSdrh       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
24649cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
24659cbf3425Sdrh       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
2466688852abSdrh       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
24679cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
2468340309fdSdrh       selectInnerLoop(pParse, p, p->pEList, tab1,
2469e8e4af76Sdrh                       0, 0, &dest, iCont, iBreak);
24704adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
2471688852abSdrh       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
24724adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
247366a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
247466a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
247582c3d636Sdrh       break;
247682c3d636Sdrh     }
247782c3d636Sdrh   }
24788cdbf836Sdrh 
24797f61e92cSdan   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
24807f61e92cSdan 
2481a9671a22Sdrh   /* Compute collating sequences used by
2482a9671a22Sdrh   ** temporary tables needed to implement the compound select.
2483a9671a22Sdrh   ** Attach the KeyInfo structure to all temporary tables.
24848cdbf836Sdrh   **
24858cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
24868cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
24878cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
24888cdbf836Sdrh   ** no temp tables are required.
2489fbc4ee7bSdrh   */
24907d10d5a6Sdrh   if( p->selFlags & SF_UsesEphemeral ){
2491fbc4ee7bSdrh     int i;                        /* Loop counter */
2492fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
24930342b1f5Sdrh     Select *pLoop;                /* For looping through SELECT statements */
2494f68d7d17Sdrh     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
249593a960a0Sdrh     int nCol;                     /* Number of columns in result set */
2496fbc4ee7bSdrh 
2497d227a291Sdrh     assert( p->pNext==0 );
249893a960a0Sdrh     nCol = p->pEList->nExpr;
2499ad124329Sdrh     pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
2500dc1bdc4fSdanielk1977     if( !pKeyInfo ){
2501dc1bdc4fSdanielk1977       rc = SQLITE_NOMEM;
2502dc1bdc4fSdanielk1977       goto multi_select_end;
2503dc1bdc4fSdanielk1977     }
25040342b1f5Sdrh     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
25050342b1f5Sdrh       *apColl = multiSelectCollSeq(pParse, p, i);
25060342b1f5Sdrh       if( 0==*apColl ){
2507633e6d57Sdrh         *apColl = db->pDfltColl;
2508dc1bdc4fSdanielk1977       }
2509dc1bdc4fSdanielk1977     }
2510dc1bdc4fSdanielk1977 
25110342b1f5Sdrh     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
25120342b1f5Sdrh       for(i=0; i<2; i++){
2513b9bb7c18Sdrh         int addr = pLoop->addrOpenEphm[i];
25140342b1f5Sdrh         if( addr<0 ){
25150342b1f5Sdrh           /* If [0] is unused then [1] is also unused.  So we can
25160342b1f5Sdrh           ** always safely abort as soon as the first unused slot is found */
2517b9bb7c18Sdrh           assert( pLoop->addrOpenEphm[1]<0 );
25180342b1f5Sdrh           break;
25190342b1f5Sdrh         }
25200342b1f5Sdrh         sqlite3VdbeChangeP2(v, addr, nCol);
25212ec2fb22Sdrh         sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
25222ec2fb22Sdrh                             P4_KEYINFO);
25230ee5a1e7Sdrh         pLoop->addrOpenEphm[i] = -1;
25240342b1f5Sdrh       }
2525dc1bdc4fSdanielk1977     }
25262ec2fb22Sdrh     sqlite3KeyInfoUnref(pKeyInfo);
2527dc1bdc4fSdanielk1977   }
2528dc1bdc4fSdanielk1977 
2529dc1bdc4fSdanielk1977 multi_select_end:
25302b596da8Sdrh   pDest->iSdst = dest.iSdst;
25312b596da8Sdrh   pDest->nSdst = dest.nSdst;
2532633e6d57Sdrh   sqlite3SelectDelete(db, pDelete);
253384ac9d02Sdanielk1977   return rc;
25342282792aSdrh }
2535b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
25362282792aSdrh 
2537b21e7c70Sdrh /*
253889b31d73Smistachkin ** Error message for when two or more terms of a compound select have different
253989b31d73Smistachkin ** size result sets.
254089b31d73Smistachkin */
254189b31d73Smistachkin void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
254289b31d73Smistachkin   if( p->selFlags & SF_Values ){
254389b31d73Smistachkin     sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
254489b31d73Smistachkin   }else{
254589b31d73Smistachkin     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
254689b31d73Smistachkin       " do not have the same number of result columns", selectOpName(p->op));
254789b31d73Smistachkin   }
254889b31d73Smistachkin }
254989b31d73Smistachkin 
255089b31d73Smistachkin /*
2551b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a
2552b21e7c70Sdrh ** SELECT statment.
25530acb7e48Sdrh **
25542b596da8Sdrh ** The data to be output is contained in pIn->iSdst.  There are
25552b596da8Sdrh ** pIn->nSdst columns to be output.  pDest is where the output should
25560acb7e48Sdrh ** be sent.
25570acb7e48Sdrh **
25580acb7e48Sdrh ** regReturn is the number of the register holding the subroutine
25590acb7e48Sdrh ** return address.
25600acb7e48Sdrh **
2561f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that
25620acb7e48Sdrh ** records the previous output.  mem[regPrev] is a flag that is false
25630acb7e48Sdrh ** if there has been no previous output.  If regPrev>0 then code is
25640acb7e48Sdrh ** generated to suppress duplicates.  pKeyInfo is used for comparing
25650acb7e48Sdrh ** keys.
25660acb7e48Sdrh **
25670acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to
25680acb7e48Sdrh ** iBreak.
2569b21e7c70Sdrh */
25700acb7e48Sdrh static int generateOutputSubroutine(
257192b01d53Sdrh   Parse *pParse,          /* Parsing context */
257292b01d53Sdrh   Select *p,              /* The SELECT statement */
257392b01d53Sdrh   SelectDest *pIn,        /* Coroutine supplying data */
257492b01d53Sdrh   SelectDest *pDest,      /* Where to send the data */
257592b01d53Sdrh   int regReturn,          /* The return address register */
25760acb7e48Sdrh   int regPrev,            /* Previous result register.  No uniqueness if 0 */
25770acb7e48Sdrh   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
257892b01d53Sdrh   int iBreak              /* Jump here if we hit the LIMIT */
2579b21e7c70Sdrh ){
2580b21e7c70Sdrh   Vdbe *v = pParse->pVdbe;
258192b01d53Sdrh   int iContinue;
258292b01d53Sdrh   int addr;
2583b21e7c70Sdrh 
258492b01d53Sdrh   addr = sqlite3VdbeCurrentAddr(v);
258592b01d53Sdrh   iContinue = sqlite3VdbeMakeLabel(v);
25860acb7e48Sdrh 
25870acb7e48Sdrh   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
25880acb7e48Sdrh   */
25890acb7e48Sdrh   if( regPrev ){
2590728e0f91Sdrh     int addr1, addr2;
2591728e0f91Sdrh     addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
2592728e0f91Sdrh     addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
25932ec2fb22Sdrh                               (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
2594728e0f91Sdrh     sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
2595728e0f91Sdrh     sqlite3VdbeJumpHere(v, addr1);
2596e8e4af76Sdrh     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
2597ec86c724Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
25980acb7e48Sdrh   }
25991f9caa41Sdanielk1977   if( pParse->db->mallocFailed ) return 0;
26000acb7e48Sdrh 
2601d5578433Smistachkin   /* Suppress the first OFFSET entries if there is an OFFSET clause
26020acb7e48Sdrh   */
2603aa9ce707Sdrh   codeOffset(v, p->iOffset, iContinue);
2604b21e7c70Sdrh 
2605e2248cfdSdrh   assert( pDest->eDest!=SRT_Exists );
2606e2248cfdSdrh   assert( pDest->eDest!=SRT_Table );
2607b21e7c70Sdrh   switch( pDest->eDest ){
2608b21e7c70Sdrh     /* Store the result as data using a unique key.
2609b21e7c70Sdrh     */
2610b21e7c70Sdrh     case SRT_EphemTab: {
2611b21e7c70Sdrh       int r1 = sqlite3GetTempReg(pParse);
2612b21e7c70Sdrh       int r2 = sqlite3GetTempReg(pParse);
26132b596da8Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
26142b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
26152b596da8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
2616b21e7c70Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
2617b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r2);
2618b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
2619b21e7c70Sdrh       break;
2620b21e7c70Sdrh     }
2621b21e7c70Sdrh 
2622b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY
2623b21e7c70Sdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
2624b21e7c70Sdrh     ** then there should be a single item on the stack.  Write this
2625b21e7c70Sdrh     ** item into the set table with bogus data.
2626b21e7c70Sdrh     */
2627b21e7c70Sdrh     case SRT_Set: {
26286fccc35aSdrh       int r1;
26299af8646dSdrh       assert( pIn->nSdst==1 || pParse->nErr>0 );
2630634d81deSdrh       pDest->affSdst =
26312b596da8Sdrh          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
2632b21e7c70Sdrh       r1 = sqlite3GetTempReg(pParse);
2633634d81deSdrh       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
26342b596da8Sdrh       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
26352b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
2636b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
2637b21e7c70Sdrh       break;
2638b21e7c70Sdrh     }
2639b21e7c70Sdrh 
2640b21e7c70Sdrh     /* If this is a scalar select that is part of an expression, then
2641b21e7c70Sdrh     ** store the results in the appropriate memory cell and break out
2642b21e7c70Sdrh     ** of the scan loop.
2643b21e7c70Sdrh     */
2644b21e7c70Sdrh     case SRT_Mem: {
2645a276e3fdSdrh       assert( pIn->nSdst==1 || pParse->nErr>0 );  testcase( pIn->nSdst!=1 );
26462b596da8Sdrh       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
2647b21e7c70Sdrh       /* The LIMIT clause will jump out of the loop for us */
2648b21e7c70Sdrh       break;
2649b21e7c70Sdrh     }
2650b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
2651b21e7c70Sdrh 
26527d10d5a6Sdrh     /* The results are stored in a sequence of registers
26532b596da8Sdrh     ** starting at pDest->iSdst.  Then the co-routine yields.
2654b21e7c70Sdrh     */
265592b01d53Sdrh     case SRT_Coroutine: {
26562b596da8Sdrh       if( pDest->iSdst==0 ){
26572b596da8Sdrh         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
26582b596da8Sdrh         pDest->nSdst = pIn->nSdst;
2659b21e7c70Sdrh       }
26604b79bde7Sdan       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
26612b596da8Sdrh       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
266292b01d53Sdrh       break;
266392b01d53Sdrh     }
266492b01d53Sdrh 
2665ccfcbceaSdrh     /* If none of the above, then the result destination must be
2666ccfcbceaSdrh     ** SRT_Output.  This routine is never called with any other
2667ccfcbceaSdrh     ** destination other than the ones handled above or SRT_Output.
2668ccfcbceaSdrh     **
2669ccfcbceaSdrh     ** For SRT_Output, results are stored in a sequence of registers.
2670ccfcbceaSdrh     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
2671ccfcbceaSdrh     ** return the next row of result.
26727d10d5a6Sdrh     */
2673ccfcbceaSdrh     default: {
2674ccfcbceaSdrh       assert( pDest->eDest==SRT_Output );
26752b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
26762b596da8Sdrh       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
2677b21e7c70Sdrh       break;
2678b21e7c70Sdrh     }
2679b21e7c70Sdrh   }
268092b01d53Sdrh 
268192b01d53Sdrh   /* Jump to the end of the loop if the LIMIT is reached.
268292b01d53Sdrh   */
268392b01d53Sdrh   if( p->iLimit ){
268416897072Sdrh     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
268592b01d53Sdrh   }
268692b01d53Sdrh 
268792b01d53Sdrh   /* Generate the subroutine return
268892b01d53Sdrh   */
26890acb7e48Sdrh   sqlite3VdbeResolveLabel(v, iContinue);
269092b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
269192b01d53Sdrh 
269292b01d53Sdrh   return addr;
2693b21e7c70Sdrh }
2694b21e7c70Sdrh 
2695b21e7c70Sdrh /*
2696b21e7c70Sdrh ** Alternative compound select code generator for cases when there
2697b21e7c70Sdrh ** is an ORDER BY clause.
2698b21e7c70Sdrh **
2699b21e7c70Sdrh ** We assume a query of the following form:
2700b21e7c70Sdrh **
2701b21e7c70Sdrh **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
2702b21e7c70Sdrh **
2703b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
2704b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as
2705b21e7c70Sdrh ** co-routines.  Then run the co-routines in parallel and merge the results
2706b21e7c70Sdrh ** into the output.  In addition to the two coroutines (called selectA and
2707b21e7c70Sdrh ** selectB) there are 7 subroutines:
2708b21e7c70Sdrh **
2709b21e7c70Sdrh **    outA:    Move the output of the selectA coroutine into the output
2710b21e7c70Sdrh **             of the compound query.
2711b21e7c70Sdrh **
2712b21e7c70Sdrh **    outB:    Move the output of the selectB coroutine into the output
2713b21e7c70Sdrh **             of the compound query.  (Only generated for UNION and
2714b21e7c70Sdrh **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
2715b21e7c70Sdrh **             appears only in B.)
2716b21e7c70Sdrh **
2717b21e7c70Sdrh **    AltB:    Called when there is data from both coroutines and A<B.
2718b21e7c70Sdrh **
2719b21e7c70Sdrh **    AeqB:    Called when there is data from both coroutines and A==B.
2720b21e7c70Sdrh **
2721b21e7c70Sdrh **    AgtB:    Called when there is data from both coroutines and A>B.
2722b21e7c70Sdrh **
2723b21e7c70Sdrh **    EofA:    Called when data is exhausted from selectA.
2724b21e7c70Sdrh **
2725b21e7c70Sdrh **    EofB:    Called when data is exhausted from selectB.
2726b21e7c70Sdrh **
2727b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which
2728b21e7c70Sdrh ** <operator> is used:
2729b21e7c70Sdrh **
2730b21e7c70Sdrh **
2731b21e7c70Sdrh **             UNION ALL         UNION            EXCEPT          INTERSECT
2732b21e7c70Sdrh **          -------------  -----------------  --------------  -----------------
2733b21e7c70Sdrh **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
2734b21e7c70Sdrh **
27350acb7e48Sdrh **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
2736b21e7c70Sdrh **
2737b21e7c70Sdrh **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
2738b21e7c70Sdrh **
27390acb7e48Sdrh **   EofA:   outB, nextB      outB, nextB          halt             halt
2740b21e7c70Sdrh **
27410acb7e48Sdrh **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
27420acb7e48Sdrh **
27430acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
27440acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes
27450acb7e48Sdrh ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
27460acb7e48Sdrh ** following nextX causes a jump to the end of the select processing.
27470acb7e48Sdrh **
27480acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
27490acb7e48Sdrh ** within the output subroutine.  The regPrev register set holds the previously
27500acb7e48Sdrh ** output value.  A comparison is made against this value and the output
27510acb7e48Sdrh ** is skipped if the next results would be the same as the previous.
2752b21e7c70Sdrh **
2753b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven
2754b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom.  Like this:
2755b21e7c70Sdrh **
2756b21e7c70Sdrh **          goto Init
2757b21e7c70Sdrh **     coA: coroutine for left query (A)
2758b21e7c70Sdrh **     coB: coroutine for right query (B)
2759b21e7c70Sdrh **    outA: output one row of A
2760b21e7c70Sdrh **    outB: output one row of B (UNION and UNION ALL only)
2761b21e7c70Sdrh **    EofA: ...
2762b21e7c70Sdrh **    EofB: ...
2763b21e7c70Sdrh **    AltB: ...
2764b21e7c70Sdrh **    AeqB: ...
2765b21e7c70Sdrh **    AgtB: ...
2766b21e7c70Sdrh **    Init: initialize coroutine registers
2767b21e7c70Sdrh **          yield coA
2768b21e7c70Sdrh **          if eof(A) goto EofA
2769b21e7c70Sdrh **          yield coB
2770b21e7c70Sdrh **          if eof(B) goto EofB
2771b21e7c70Sdrh **    Cmpr: Compare A, B
2772b21e7c70Sdrh **          Jump AltB, AeqB, AgtB
2773b21e7c70Sdrh **     End: ...
2774b21e7c70Sdrh **
2775b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
2776b21e7c70Sdrh ** actually called using Gosub and they do not Return.  EofA and EofB loop
2777b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
2778b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB.
2779b21e7c70Sdrh */
2780de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
2781b21e7c70Sdrh static int multiSelectOrderBy(
2782b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
2783b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
2784a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
2785b21e7c70Sdrh ){
27860acb7e48Sdrh   int i, j;             /* Loop counters */
2787b21e7c70Sdrh   Select *pPrior;       /* Another SELECT immediately to our left */
2788b21e7c70Sdrh   Vdbe *v;              /* Generate code to this VDBE */
2789b21e7c70Sdrh   SelectDest destA;     /* Destination for coroutine A */
2790b21e7c70Sdrh   SelectDest destB;     /* Destination for coroutine B */
279192b01d53Sdrh   int regAddrA;         /* Address register for select-A coroutine */
279292b01d53Sdrh   int regAddrB;         /* Address register for select-B coroutine */
279392b01d53Sdrh   int addrSelectA;      /* Address of the select-A coroutine */
279492b01d53Sdrh   int addrSelectB;      /* Address of the select-B coroutine */
279592b01d53Sdrh   int regOutA;          /* Address register for the output-A subroutine */
279692b01d53Sdrh   int regOutB;          /* Address register for the output-B subroutine */
279792b01d53Sdrh   int addrOutA;         /* Address of the output-A subroutine */
2798b27b7f5dSdrh   int addrOutB = 0;     /* Address of the output-B subroutine */
279992b01d53Sdrh   int addrEofA;         /* Address of the select-A-exhausted subroutine */
280081cf13ecSdrh   int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
280192b01d53Sdrh   int addrEofB;         /* Address of the select-B-exhausted subroutine */
280292b01d53Sdrh   int addrAltB;         /* Address of the A<B subroutine */
280392b01d53Sdrh   int addrAeqB;         /* Address of the A==B subroutine */
280492b01d53Sdrh   int addrAgtB;         /* Address of the A>B subroutine */
280592b01d53Sdrh   int regLimitA;        /* Limit register for select-A */
280692b01d53Sdrh   int regLimitB;        /* Limit register for select-A */
28070acb7e48Sdrh   int regPrev;          /* A range of registers to hold previous output */
280892b01d53Sdrh   int savedLimit;       /* Saved value of p->iLimit */
280992b01d53Sdrh   int savedOffset;      /* Saved value of p->iOffset */
281092b01d53Sdrh   int labelCmpr;        /* Label for the start of the merge algorithm */
281192b01d53Sdrh   int labelEnd;         /* Label for the end of the overall SELECT stmt */
2812728e0f91Sdrh   int addr1;            /* Jump instructions that get retargetted */
281392b01d53Sdrh   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
281496067816Sdrh   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
28150acb7e48Sdrh   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
28160acb7e48Sdrh   sqlite3 *db;          /* Database connection */
28170acb7e48Sdrh   ExprList *pOrderBy;   /* The ORDER BY clause */
28180acb7e48Sdrh   int nOrderBy;         /* Number of terms in the ORDER BY clause */
28190acb7e48Sdrh   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
28207f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN
28217f61e92cSdan   int iSub1;            /* EQP id of left-hand query */
28227f61e92cSdan   int iSub2;            /* EQP id of right-hand query */
28237f61e92cSdan #endif
2824b21e7c70Sdrh 
282592b01d53Sdrh   assert( p->pOrderBy!=0 );
282696067816Sdrh   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
28270acb7e48Sdrh   db = pParse->db;
282892b01d53Sdrh   v = pParse->pVdbe;
2829ccfcbceaSdrh   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
283092b01d53Sdrh   labelEnd = sqlite3VdbeMakeLabel(v);
283192b01d53Sdrh   labelCmpr = sqlite3VdbeMakeLabel(v);
28320acb7e48Sdrh 
2833b21e7c70Sdrh 
283492b01d53Sdrh   /* Patch up the ORDER BY clause
283592b01d53Sdrh   */
283692b01d53Sdrh   op = p->op;
2837b21e7c70Sdrh   pPrior = p->pPrior;
283892b01d53Sdrh   assert( pPrior->pOrderBy==0 );
28390acb7e48Sdrh   pOrderBy = p->pOrderBy;
284093a960a0Sdrh   assert( pOrderBy );
28410acb7e48Sdrh   nOrderBy = pOrderBy->nExpr;
284293a960a0Sdrh 
28430acb7e48Sdrh   /* For operators other than UNION ALL we have to make sure that
28440acb7e48Sdrh   ** the ORDER BY clause covers every term of the result set.  Add
28450acb7e48Sdrh   ** terms to the ORDER BY clause as necessary.
28460acb7e48Sdrh   */
28470acb7e48Sdrh   if( op!=TK_ALL ){
28480acb7e48Sdrh     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
28497d10d5a6Sdrh       struct ExprList_item *pItem;
28507d10d5a6Sdrh       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
2851c2acc4e4Sdrh         assert( pItem->u.x.iOrderByCol>0 );
2852c2acc4e4Sdrh         if( pItem->u.x.iOrderByCol==i ) break;
28530acb7e48Sdrh       }
28540acb7e48Sdrh       if( j==nOrderBy ){
2855b7916a78Sdrh         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
28560acb7e48Sdrh         if( pNew==0 ) return SQLITE_NOMEM;
28570acb7e48Sdrh         pNew->flags |= EP_IntValue;
285833e619fcSdrh         pNew->u.iValue = i;
2859b7916a78Sdrh         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
2860c2acc4e4Sdrh         if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
28610acb7e48Sdrh       }
28620acb7e48Sdrh     }
28630acb7e48Sdrh   }
28640acb7e48Sdrh 
28650acb7e48Sdrh   /* Compute the comparison permutation and keyinfo that is used with
286610c081adSdrh   ** the permutation used to determine if the next
28670acb7e48Sdrh   ** row of results comes from selectA or selectB.  Also add explicit
28680acb7e48Sdrh   ** collations to the ORDER BY clause terms so that when the subqueries
28690acb7e48Sdrh   ** to the right and the left are evaluated, they use the correct
28700acb7e48Sdrh   ** collation.
28710acb7e48Sdrh   */
28720acb7e48Sdrh   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
28730acb7e48Sdrh   if( aPermute ){
28747d10d5a6Sdrh     struct ExprList_item *pItem;
28757d10d5a6Sdrh     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
28766736618aSdrh       assert( pItem->u.x.iOrderByCol>0 );
28772ec18a3cSdrh       assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
2878c2acc4e4Sdrh       aPermute[i] = pItem->u.x.iOrderByCol - 1;
28790acb7e48Sdrh     }
288053bed45eSdan     pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
28810acb7e48Sdrh   }else{
28820acb7e48Sdrh     pKeyMerge = 0;
28830acb7e48Sdrh   }
28840acb7e48Sdrh 
28850acb7e48Sdrh   /* Reattach the ORDER BY clause to the query.
28860acb7e48Sdrh   */
28870acb7e48Sdrh   p->pOrderBy = pOrderBy;
28886ab3a2ecSdanielk1977   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
28890acb7e48Sdrh 
28900acb7e48Sdrh   /* Allocate a range of temporary registers and the KeyInfo needed
28910acb7e48Sdrh   ** for the logic that removes duplicate result rows when the
28920acb7e48Sdrh   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
28930acb7e48Sdrh   */
28940acb7e48Sdrh   if( op==TK_ALL ){
28950acb7e48Sdrh     regPrev = 0;
28960acb7e48Sdrh   }else{
28970acb7e48Sdrh     int nExpr = p->pEList->nExpr;
28981c0dc825Sdrh     assert( nOrderBy>=nExpr || db->mallocFailed );
2899c8ac0d16Sdrh     regPrev = pParse->nMem+1;
2900c8ac0d16Sdrh     pParse->nMem += nExpr+1;
29010acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
2902ad124329Sdrh     pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
29030acb7e48Sdrh     if( pKeyDup ){
29042ec2fb22Sdrh       assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
29050acb7e48Sdrh       for(i=0; i<nExpr; i++){
29060acb7e48Sdrh         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
29070acb7e48Sdrh         pKeyDup->aSortOrder[i] = 0;
29080acb7e48Sdrh       }
29090acb7e48Sdrh     }
29100acb7e48Sdrh   }
291192b01d53Sdrh 
291292b01d53Sdrh   /* Separate the left and the right query from one another
291392b01d53Sdrh   */
291492b01d53Sdrh   p->pPrior = 0;
2915d227a291Sdrh   pPrior->pNext = 0;
29167d10d5a6Sdrh   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
29170acb7e48Sdrh   if( pPrior->pPrior==0 ){
29187d10d5a6Sdrh     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
29190acb7e48Sdrh   }
292092b01d53Sdrh 
292192b01d53Sdrh   /* Compute the limit registers */
292292b01d53Sdrh   computeLimitRegisters(pParse, p, labelEnd);
29230acb7e48Sdrh   if( p->iLimit && op==TK_ALL ){
292492b01d53Sdrh     regLimitA = ++pParse->nMem;
292592b01d53Sdrh     regLimitB = ++pParse->nMem;
292692b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
292792b01d53Sdrh                                   regLimitA);
292892b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
292992b01d53Sdrh   }else{
293092b01d53Sdrh     regLimitA = regLimitB = 0;
293192b01d53Sdrh   }
2932633e6d57Sdrh   sqlite3ExprDelete(db, p->pLimit);
29330acb7e48Sdrh   p->pLimit = 0;
2934633e6d57Sdrh   sqlite3ExprDelete(db, p->pOffset);
29350acb7e48Sdrh   p->pOffset = 0;
293692b01d53Sdrh 
2937b21e7c70Sdrh   regAddrA = ++pParse->nMem;
2938b21e7c70Sdrh   regAddrB = ++pParse->nMem;
2939b21e7c70Sdrh   regOutA = ++pParse->nMem;
2940b21e7c70Sdrh   regOutB = ++pParse->nMem;
2941b21e7c70Sdrh   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
2942b21e7c70Sdrh   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
2943b21e7c70Sdrh 
294492b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement to the
29450acb7e48Sdrh   ** left of the compound operator - the "A" select.
29460acb7e48Sdrh   */
2947ed71a839Sdrh   addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
2948728e0f91Sdrh   addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
2949ed71a839Sdrh   VdbeComment((v, "left SELECT"));
295092b01d53Sdrh   pPrior->iLimit = regLimitA;
29517f61e92cSdan   explainSetInteger(iSub1, pParse->iNextSelectId);
29527d10d5a6Sdrh   sqlite3Select(pParse, pPrior, &destA);
295381cf13ecSdrh   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
2954728e0f91Sdrh   sqlite3VdbeJumpHere(v, addr1);
2955b21e7c70Sdrh 
295692b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement on
295792b01d53Sdrh   ** the right - the "B" select
295892b01d53Sdrh   */
2959ed71a839Sdrh   addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
2960728e0f91Sdrh   addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
2961ed71a839Sdrh   VdbeComment((v, "right SELECT"));
296292b01d53Sdrh   savedLimit = p->iLimit;
296392b01d53Sdrh   savedOffset = p->iOffset;
296492b01d53Sdrh   p->iLimit = regLimitB;
296592b01d53Sdrh   p->iOffset = 0;
29667f61e92cSdan   explainSetInteger(iSub2, pParse->iNextSelectId);
29677d10d5a6Sdrh   sqlite3Select(pParse, p, &destB);
296892b01d53Sdrh   p->iLimit = savedLimit;
296992b01d53Sdrh   p->iOffset = savedOffset;
297081cf13ecSdrh   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
2971b21e7c70Sdrh 
297292b01d53Sdrh   /* Generate a subroutine that outputs the current row of the A
29730acb7e48Sdrh   ** select as the next output row of the compound select.
297492b01d53Sdrh   */
2975b21e7c70Sdrh   VdbeNoopComment((v, "Output routine for A"));
29760acb7e48Sdrh   addrOutA = generateOutputSubroutine(pParse,
29770acb7e48Sdrh                  p, &destA, pDest, regOutA,
29782ec2fb22Sdrh                  regPrev, pKeyDup, labelEnd);
2979b21e7c70Sdrh 
298092b01d53Sdrh   /* Generate a subroutine that outputs the current row of the B
29810acb7e48Sdrh   ** select as the next output row of the compound select.
298292b01d53Sdrh   */
29830acb7e48Sdrh   if( op==TK_ALL || op==TK_UNION ){
2984b21e7c70Sdrh     VdbeNoopComment((v, "Output routine for B"));
29850acb7e48Sdrh     addrOutB = generateOutputSubroutine(pParse,
29860acb7e48Sdrh                  p, &destB, pDest, regOutB,
29872ec2fb22Sdrh                  regPrev, pKeyDup, labelEnd);
29880acb7e48Sdrh   }
29892ec2fb22Sdrh   sqlite3KeyInfoUnref(pKeyDup);
2990b21e7c70Sdrh 
299192b01d53Sdrh   /* Generate a subroutine to run when the results from select A
299292b01d53Sdrh   ** are exhausted and only data in select B remains.
299392b01d53Sdrh   */
299492b01d53Sdrh   if( op==TK_EXCEPT || op==TK_INTERSECT ){
299581cf13ecSdrh     addrEofA_noB = addrEofA = labelEnd;
299692b01d53Sdrh   }else{
299781cf13ecSdrh     VdbeNoopComment((v, "eof-A subroutine"));
299881cf13ecSdrh     addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
299981cf13ecSdrh     addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
3000688852abSdrh                                      VdbeCoverage(v);
3001076e85f5Sdrh     sqlite3VdbeGoto(v, addrEofA);
300295aa47b1Sdrh     p->nSelectRow += pPrior->nSelectRow;
3003b21e7c70Sdrh   }
3004b21e7c70Sdrh 
300592b01d53Sdrh   /* Generate a subroutine to run when the results from select B
300692b01d53Sdrh   ** are exhausted and only data in select A remains.
300792b01d53Sdrh   */
3008b21e7c70Sdrh   if( op==TK_INTERSECT ){
300992b01d53Sdrh     addrEofB = addrEofA;
301095aa47b1Sdrh     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
3011b21e7c70Sdrh   }else{
301292b01d53Sdrh     VdbeNoopComment((v, "eof-B subroutine"));
301381cf13ecSdrh     addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
3014688852abSdrh     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
3015076e85f5Sdrh     sqlite3VdbeGoto(v, addrEofB);
3016b21e7c70Sdrh   }
3017b21e7c70Sdrh 
301892b01d53Sdrh   /* Generate code to handle the case of A<B
301992b01d53Sdrh   */
3020b21e7c70Sdrh   VdbeNoopComment((v, "A-lt-B subroutine"));
30210acb7e48Sdrh   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
3022688852abSdrh   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
3023076e85f5Sdrh   sqlite3VdbeGoto(v, labelCmpr);
3024b21e7c70Sdrh 
302592b01d53Sdrh   /* Generate code to handle the case of A==B
302692b01d53Sdrh   */
3027b21e7c70Sdrh   if( op==TK_ALL ){
3028b21e7c70Sdrh     addrAeqB = addrAltB;
30290acb7e48Sdrh   }else if( op==TK_INTERSECT ){
30300acb7e48Sdrh     addrAeqB = addrAltB;
30310acb7e48Sdrh     addrAltB++;
303292b01d53Sdrh   }else{
3033b21e7c70Sdrh     VdbeNoopComment((v, "A-eq-B subroutine"));
30340acb7e48Sdrh     addrAeqB =
3035688852abSdrh     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
3036076e85f5Sdrh     sqlite3VdbeGoto(v, labelCmpr);
303792b01d53Sdrh   }
3038b21e7c70Sdrh 
303992b01d53Sdrh   /* Generate code to handle the case of A>B
304092b01d53Sdrh   */
3041b21e7c70Sdrh   VdbeNoopComment((v, "A-gt-B subroutine"));
3042b21e7c70Sdrh   addrAgtB = sqlite3VdbeCurrentAddr(v);
3043b21e7c70Sdrh   if( op==TK_ALL || op==TK_UNION ){
3044b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
304592b01d53Sdrh   }
3046688852abSdrh   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
3047076e85f5Sdrh   sqlite3VdbeGoto(v, labelCmpr);
3048b21e7c70Sdrh 
304992b01d53Sdrh   /* This code runs once to initialize everything.
305092b01d53Sdrh   */
3051728e0f91Sdrh   sqlite3VdbeJumpHere(v, addr1);
3052688852abSdrh   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
3053688852abSdrh   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
305492b01d53Sdrh 
305592b01d53Sdrh   /* Implement the main merge loop
305692b01d53Sdrh   */
305792b01d53Sdrh   sqlite3VdbeResolveLabel(v, labelCmpr);
30580acb7e48Sdrh   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
30592b596da8Sdrh   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
30602ec2fb22Sdrh                          (char*)pKeyMerge, P4_KEYINFO);
3061953f7611Sdrh   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
3062688852abSdrh   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
306392b01d53Sdrh 
306492b01d53Sdrh   /* Jump to the this point in order to terminate the query.
306592b01d53Sdrh   */
3066b21e7c70Sdrh   sqlite3VdbeResolveLabel(v, labelEnd);
3067b21e7c70Sdrh 
306892b01d53Sdrh   /* Set the number of output columns
306992b01d53Sdrh   */
30707d10d5a6Sdrh   if( pDest->eDest==SRT_Output ){
30710acb7e48Sdrh     Select *pFirst = pPrior;
307292b01d53Sdrh     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
30739a8941fcSdan     generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
3074b21e7c70Sdrh   }
307592b01d53Sdrh 
30760acb7e48Sdrh   /* Reassembly the compound query so that it will be freed correctly
30770acb7e48Sdrh   ** by the calling function */
30785e7ad508Sdanielk1977   if( p->pPrior ){
3079633e6d57Sdrh     sqlite3SelectDelete(db, p->pPrior);
30805e7ad508Sdanielk1977   }
30810acb7e48Sdrh   p->pPrior = pPrior;
3082d227a291Sdrh   pPrior->pNext = p;
308392b01d53Sdrh 
308492b01d53Sdrh   /*** TBD:  Insert subroutine calls to close cursors on incomplete
308592b01d53Sdrh   **** subqueries ****/
30867f61e92cSdan   explainComposite(pParse, p->op, iSub1, iSub2, 0);
30873dc4cc66Sdrh   return pParse->nErr!=0;
308892b01d53Sdrh }
3089de3e41e3Sdanielk1977 #endif
3090b21e7c70Sdrh 
30913514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
309217435752Sdrh /* Forward Declarations */
309317435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*);
3094d12b6363Sdrh static void substSelect(sqlite3*, Select *, int, ExprList*, int);
309517435752Sdrh 
30962282792aSdrh /*
3097832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
30986a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
309984e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
31006a3ea0e6Sdrh ** unchanged.)
3101832508b7Sdrh **
3102832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
3103832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
3104832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
3105832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
3106832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
3107832508b7Sdrh ** of the subquery rather the result set of the subquery.
3108832508b7Sdrh */
3109b7916a78Sdrh static Expr *substExpr(
311017435752Sdrh   sqlite3 *db,        /* Report malloc errors to this connection */
311117435752Sdrh   Expr *pExpr,        /* Expr in which substitution occurs */
311217435752Sdrh   int iTable,         /* Table to be substituted */
311317435752Sdrh   ExprList *pEList    /* Substitute expressions */
311417435752Sdrh ){
3115b7916a78Sdrh   if( pExpr==0 ) return 0;
311650350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
311750350a15Sdrh     if( pExpr->iColumn<0 ){
311850350a15Sdrh       pExpr->op = TK_NULL;
311950350a15Sdrh     }else{
3120832508b7Sdrh       Expr *pNew;
312184e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
31226ab3a2ecSdanielk1977       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
3123b7916a78Sdrh       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
3124b7916a78Sdrh       sqlite3ExprDelete(db, pExpr);
3125b7916a78Sdrh       pExpr = pNew;
312650350a15Sdrh     }
3127832508b7Sdrh   }else{
3128b7916a78Sdrh     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
3129b7916a78Sdrh     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
31306ab3a2ecSdanielk1977     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
3131d12b6363Sdrh       substSelect(db, pExpr->x.pSelect, iTable, pEList, 1);
31326ab3a2ecSdanielk1977     }else{
31336ab3a2ecSdanielk1977       substExprList(db, pExpr->x.pList, iTable, pEList);
31346ab3a2ecSdanielk1977     }
3135832508b7Sdrh   }
3136b7916a78Sdrh   return pExpr;
3137832508b7Sdrh }
313817435752Sdrh static void substExprList(
313917435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
314017435752Sdrh   ExprList *pList,     /* List to scan and in which to make substitutes */
314117435752Sdrh   int iTable,          /* Table to be substituted */
314217435752Sdrh   ExprList *pEList     /* Substitute values */
314317435752Sdrh ){
3144832508b7Sdrh   int i;
3145832508b7Sdrh   if( pList==0 ) return;
3146832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
3147b7916a78Sdrh     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
3148832508b7Sdrh   }
3149832508b7Sdrh }
315017435752Sdrh static void substSelect(
315117435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
315217435752Sdrh   Select *p,           /* SELECT statement in which to make substitutions */
315317435752Sdrh   int iTable,          /* Table to be replaced */
3154d12b6363Sdrh   ExprList *pEList,    /* Substitute values */
3155d12b6363Sdrh   int doPrior          /* Do substitutes on p->pPrior too */
315617435752Sdrh ){
3157588a9a1aSdrh   SrcList *pSrc;
3158588a9a1aSdrh   struct SrcList_item *pItem;
3159588a9a1aSdrh   int i;
3160b3bce662Sdanielk1977   if( !p ) return;
3161d12b6363Sdrh   do{
316217435752Sdrh     substExprList(db, p->pEList, iTable, pEList);
316317435752Sdrh     substExprList(db, p->pGroupBy, iTable, pEList);
316417435752Sdrh     substExprList(db, p->pOrderBy, iTable, pEList);
3165b7916a78Sdrh     p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
3166b7916a78Sdrh     p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
3167588a9a1aSdrh     pSrc = p->pSrc;
31682906490bSdrh     assert( pSrc!=0 );
3169588a9a1aSdrh     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
3170d12b6363Sdrh       substSelect(db, pItem->pSelect, iTable, pEList, 1);
3171d12b6363Sdrh       if( pItem->fg.isTabFunc ){
3172d12b6363Sdrh         substExprList(db, pItem->u1.pFuncArg, iTable, pEList);
3173588a9a1aSdrh       }
3174588a9a1aSdrh     }
3175d12b6363Sdrh   }while( doPrior && (p = p->pPrior)!=0 );
3176b3bce662Sdanielk1977 }
31773514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
3178832508b7Sdrh 
31793514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3180832508b7Sdrh /*
3181630d296cSdrh ** This routine attempts to flatten subqueries as a performance optimization.
3182630d296cSdrh ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
31831350b030Sdrh **
31841350b030Sdrh ** To understand the concept of flattening, consider the following
31851350b030Sdrh ** query:
31861350b030Sdrh **
31871350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
31881350b030Sdrh **
31891350b030Sdrh ** The default way of implementing this query is to execute the
31901350b030Sdrh ** subquery first and store the results in a temporary table, then
31911350b030Sdrh ** run the outer query on that temporary table.  This requires two
31921350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
31931350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
3194832508b7Sdrh ** optimized.
31951350b030Sdrh **
3196832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
31971350b030Sdrh ** a single flat select, like this:
31981350b030Sdrh **
31991350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
32001350b030Sdrh **
320160ec914cSpeter.d.reid ** The code generated for this simplification gives the same result
3202832508b7Sdrh ** but only has to scan the data once.  And because indices might
3203832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
3204832508b7Sdrh ** avoided.
32051350b030Sdrh **
3206832508b7Sdrh ** Flattening is only attempted if all of the following are true:
32071350b030Sdrh **
3208832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
32091350b030Sdrh **
3210885a5b03Sdrh **   (2)  The subquery is not an aggregate or (2a) the outer query is not a join
3211885a5b03Sdrh **        and (2b) the outer query does not use subqueries other than the one
3212885a5b03Sdrh **        FROM-clause subquery that is a candidate for flattening.  (2b is
3213885a5b03Sdrh **        due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
3214832508b7Sdrh **
32152b300d5dSdrh **   (3)  The subquery is not the right operand of a left outer join
321649ad330dSdan **        (Originally ticket #306.  Strengthened by ticket #3300)
3217832508b7Sdrh **
321849ad330dSdan **   (4)  The subquery is not DISTINCT.
3219832508b7Sdrh **
322049ad330dSdan **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
322149ad330dSdan **        sub-queries that were excluded from this optimization. Restriction
322249ad330dSdan **        (4) has since been expanded to exclude all DISTINCT subqueries.
3223832508b7Sdrh **
3224832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
3225832508b7Sdrh **        DISTINCT.
3226832508b7Sdrh **
3227630d296cSdrh **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
3228630d296cSdrh **        A FROM clause, consider adding a FROM close with the special
3229630d296cSdrh **        table sqlite_once that consists of a single row containing a
3230630d296cSdrh **        single NULL.
323108192d5fSdrh **
3232df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
3233df199a25Sdrh **
3234df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
3235df199a25Sdrh **        aggregates.
3236df199a25Sdrh **
32376092d2bcSdrh **  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
32386092d2bcSdrh **        accidently carried the comment forward until 2014-09-15.  Original
323938b4149cSdrh **        text: "The subquery does not use aggregates or the outer query
324038b4149cSdrh **        does not use LIMIT."
3241df199a25Sdrh **
3242174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
3243174b6195Sdrh **
32447b688edeSdrh **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
32452b300d5dSdrh **        a separate restriction deriving from ticket #350.
32463fc673e6Sdrh **
324749ad330dSdan **  (13)  The subquery and outer query do not both use LIMIT.
3248ac83963aSdrh **
324949ad330dSdan **  (14)  The subquery does not use OFFSET.
3250ac83963aSdrh **
3251ad91c6cdSdrh **  (15)  The outer query is not part of a compound select or the
3252f3913278Sdrh **        subquery does not have a LIMIT clause.
3253f3913278Sdrh **        (See ticket #2339 and ticket [02a8e81d44]).
3254ad91c6cdSdrh **
3255c52e355dSdrh **  (16)  The outer query is not an aggregate or the subquery does
3256c52e355dSdrh **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
3257c52e355dSdrh **        until we introduced the group_concat() function.
3258c52e355dSdrh **
3259f23329a2Sdanielk1977 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
32604914cf92Sdanielk1977 **        compound clause made up entirely of non-aggregate queries, and
3261f23329a2Sdanielk1977 **        the parent query:
3262f23329a2Sdanielk1977 **
3263f23329a2Sdanielk1977 **          * is not itself part of a compound select,
3264f23329a2Sdanielk1977 **          * is not an aggregate or DISTINCT query, and
3265630d296cSdrh **          * is not a join
3266f23329a2Sdanielk1977 **
32674914cf92Sdanielk1977 **        The parent and sub-query may contain WHERE clauses. Subject to
32684914cf92Sdanielk1977 **        rules (11), (13) and (14), they may also contain ORDER BY,
3269630d296cSdrh **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
3270630d296cSdrh **        operator other than UNION ALL because all the other compound
3271630d296cSdrh **        operators have an implied DISTINCT which is disallowed by
3272630d296cSdrh **        restriction (4).
3273f23329a2Sdanielk1977 **
327467c70142Sdan **        Also, each component of the sub-query must return the same number
327567c70142Sdan **        of result columns. This is actually a requirement for any compound
327667c70142Sdan **        SELECT statement, but all the code here does is make sure that no
327767c70142Sdan **        such (illegal) sub-query is flattened. The caller will detect the
327867c70142Sdan **        syntax error and return a detailed message.
327967c70142Sdan **
328049fc1f60Sdanielk1977 **  (18)  If the sub-query is a compound select, then all terms of the
328149fc1f60Sdanielk1977 **        ORDER by clause of the parent must be simple references to
328249fc1f60Sdanielk1977 **        columns of the sub-query.
328349fc1f60Sdanielk1977 **
3284229cf702Sdrh **  (19)  The subquery does not use LIMIT or the outer query does not
3285229cf702Sdrh **        have a WHERE clause.
3286229cf702Sdrh **
3287e8902a70Sdrh **  (20)  If the sub-query is a compound select, then it must not use
3288e8902a70Sdrh **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
3289e8902a70Sdrh **        somewhat by saying that the terms of the ORDER BY clause must
3290630d296cSdrh **        appear as unmodified result columns in the outer query.  But we
3291e8902a70Sdrh **        have other optimizations in mind to deal with that case.
3292e8902a70Sdrh **
3293a91491e5Sshaneh **  (21)  The subquery does not use LIMIT or the outer query is not
3294a91491e5Sshaneh **        DISTINCT.  (See ticket [752e1646fc]).
3295a91491e5Sshaneh **
32968290c2adSdan **  (22)  The subquery is not a recursive CTE.
32978290c2adSdan **
32988290c2adSdan **  (23)  The parent is not a recursive CTE, or the sub-query is not a
32998290c2adSdan **        compound query. This restriction is because transforming the
33008290c2adSdan **        parent to a compound query confuses the code that handles
33018290c2adSdan **        recursive queries in multiSelect().
33028290c2adSdan **
33039588ad95Sdrh **  (24)  The subquery is not an aggregate that uses the built-in min() or
33049588ad95Sdrh **        or max() functions.  (Without this restriction, a query like:
33059588ad95Sdrh **        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
33069588ad95Sdrh **        return the value X for which Y was maximal.)
33079588ad95Sdrh **
33088290c2adSdan **
3309832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
3310832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
3311832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
3312832508b7Sdrh **
3313665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
3314832508b7Sdrh ** If flattening is attempted this routine returns 1.
3315832508b7Sdrh **
3316832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
3317832508b7Sdrh ** the subquery before this routine runs.
33181350b030Sdrh */
33198c74a8caSdrh static int flattenSubquery(
3320524cc21eSdanielk1977   Parse *pParse,       /* Parsing context */
33218c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
33228c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
33238c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
33248c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
33258c74a8caSdrh ){
3326524cc21eSdanielk1977   const char *zSavedAuthContext = pParse->zAuthContext;
3327d12b6363Sdrh   Select *pParent;    /* Current UNION ALL term of the other query */
33280bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
3329f23329a2Sdanielk1977   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
3330ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
3331ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
33320bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
33336a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
333491bb0eedSdrh   int i;              /* Loop counter */
333591bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
333691bb0eedSdrh   struct SrcList_item *pSubitem;   /* The subquery */
3337524cc21eSdanielk1977   sqlite3 *db = pParse->db;
33381350b030Sdrh 
3339832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
3340832508b7Sdrh   */
3341a78c22c4Sdrh   assert( p!=0 );
3342a78c22c4Sdrh   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
33437e5418e4Sdrh   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
3344832508b7Sdrh   pSrc = p->pSrc;
3345ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
334691bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
334749fc1f60Sdanielk1977   iParent = pSubitem->iCursor;
334891bb0eedSdrh   pSub = pSubitem->pSelect;
3349832508b7Sdrh   assert( pSub!=0 );
3350885a5b03Sdrh   if( subqueryIsAgg ){
3351885a5b03Sdrh     if( isAgg ) return 0;                                /* Restriction (1)   */
3352885a5b03Sdrh     if( pSrc->nSrc>1 ) return 0;                         /* Restriction (2a)  */
3353885a5b03Sdrh     if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
33542308ed38Sdrh      || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
33552308ed38Sdrh      || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
3356885a5b03Sdrh     ){
3357885a5b03Sdrh       return 0;                                          /* Restriction (2b)  */
3358885a5b03Sdrh     }
3359885a5b03Sdrh   }
3360885a5b03Sdrh 
3361832508b7Sdrh   pSubSrc = pSub->pSrc;
3362832508b7Sdrh   assert( pSubSrc );
3363ac83963aSdrh   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
336460ec914cSpeter.d.reid   ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
3365ac83963aSdrh   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
3366ac83963aSdrh   ** became arbitrary expressions, we were forced to add restrictions (13)
3367ac83963aSdrh   ** and (14). */
3368ac83963aSdrh   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
3369ac83963aSdrh   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
3370d227a291Sdrh   if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
3371ad91c6cdSdrh     return 0;                                            /* Restriction (15) */
3372ad91c6cdSdrh   }
3373ac83963aSdrh   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
337449ad330dSdan   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
337549ad330dSdan   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
337649ad330dSdan      return 0;         /* Restrictions (8)(9) */
3377df199a25Sdrh   }
33787d10d5a6Sdrh   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
33797d10d5a6Sdrh      return 0;         /* Restriction (6)  */
33807d10d5a6Sdrh   }
33817d10d5a6Sdrh   if( p->pOrderBy && pSub->pOrderBy ){
3382ac83963aSdrh      return 0;                                           /* Restriction (11) */
3383ac83963aSdrh   }
3384c52e355dSdrh   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
3385229cf702Sdrh   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
3386a91491e5Sshaneh   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
3387a91491e5Sshaneh      return 0;         /* Restriction (21) */
3388a91491e5Sshaneh   }
33899588ad95Sdrh   testcase( pSub->selFlags & SF_Recursive );
33909588ad95Sdrh   testcase( pSub->selFlags & SF_MinMaxAgg );
33919588ad95Sdrh   if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
33929588ad95Sdrh     return 0; /* Restrictions (22) and (24) */
33939588ad95Sdrh   }
33949588ad95Sdrh   if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
33959588ad95Sdrh     return 0; /* Restriction (23) */
33969588ad95Sdrh   }
3397832508b7Sdrh 
33982b300d5dSdrh   /* OBSOLETE COMMENT 1:
33992b300d5dSdrh   ** Restriction 3:  If the subquery is a join, make sure the subquery is
34008af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
34018af4d3acSdrh   ** is not allowed:
34028af4d3acSdrh   **
34038af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
34048af4d3acSdrh   **
34058af4d3acSdrh   ** If we flatten the above, we would get
34068af4d3acSdrh   **
34078af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
34088af4d3acSdrh   **
34098af4d3acSdrh   ** which is not at all the same thing.
34102b300d5dSdrh   **
34112b300d5dSdrh   ** OBSOLETE COMMENT 2:
34122b300d5dSdrh   ** Restriction 12:  If the subquery is the right operand of a left outer
34133fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
34143fc673e6Sdrh   ** An examples of why this is not allowed:
34153fc673e6Sdrh   **
34163fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
34173fc673e6Sdrh   **
34183fc673e6Sdrh   ** If we flatten the above, we would get
34193fc673e6Sdrh   **
34203fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
34213fc673e6Sdrh   **
34223fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
34233fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
34242b300d5dSdrh   **
34252b300d5dSdrh   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
34262b300d5dSdrh   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
34272b300d5dSdrh   ** is fraught with danger.  Best to avoid the whole thing.  If the
34282b300d5dSdrh   ** subquery is the right term of a LEFT JOIN, then do not flatten.
34293fc673e6Sdrh   */
34308a48b9c0Sdrh   if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
34313fc673e6Sdrh     return 0;
34323fc673e6Sdrh   }
34333fc673e6Sdrh 
3434f23329a2Sdanielk1977   /* Restriction 17: If the sub-query is a compound SELECT, then it must
3435f23329a2Sdanielk1977   ** use only the UNION ALL operator. And none of the simple select queries
3436f23329a2Sdanielk1977   ** that make up the compound SELECT are allowed to be aggregate or distinct
3437f23329a2Sdanielk1977   ** queries.
3438f23329a2Sdanielk1977   */
3439f23329a2Sdanielk1977   if( pSub->pPrior ){
3440e8902a70Sdrh     if( pSub->pOrderBy ){
3441e8902a70Sdrh       return 0;  /* Restriction 20 */
3442e8902a70Sdrh     }
3443e2f02bacSdrh     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
3444f23329a2Sdanielk1977       return 0;
3445f23329a2Sdanielk1977     }
3446f23329a2Sdanielk1977     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
3447ccfcbceaSdrh       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
3448ccfcbceaSdrh       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
34494b3ac73cSdrh       assert( pSub->pSrc!=0 );
34502ec18a3cSdrh       assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
34517d10d5a6Sdrh       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
345280b3c548Sdanielk1977        || (pSub1->pPrior && pSub1->op!=TK_ALL)
34534b3ac73cSdrh        || pSub1->pSrc->nSrc<1
345480b3c548Sdanielk1977       ){
3455f23329a2Sdanielk1977         return 0;
3456f23329a2Sdanielk1977       }
34574b3ac73cSdrh       testcase( pSub1->pSrc->nSrc>1 );
3458f23329a2Sdanielk1977     }
345949fc1f60Sdanielk1977 
346049fc1f60Sdanielk1977     /* Restriction 18. */
346149fc1f60Sdanielk1977     if( p->pOrderBy ){
346249fc1f60Sdanielk1977       int ii;
346349fc1f60Sdanielk1977       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
3464c2acc4e4Sdrh         if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
346549fc1f60Sdanielk1977       }
346649fc1f60Sdanielk1977     }
3467f23329a2Sdanielk1977   }
3468f23329a2Sdanielk1977 
34697d10d5a6Sdrh   /***** If we reach this point, flattening is permitted. *****/
3470eb9b884cSdrh   SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
3471eb9b884cSdrh                    pSub->zSelName, pSub, iFrom));
34727d10d5a6Sdrh 
34737d10d5a6Sdrh   /* Authorize the subquery */
3474524cc21eSdanielk1977   pParse->zAuthContext = pSubitem->zName;
3475a2acb0d7Sdrh   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
3476a2acb0d7Sdrh   testcase( i==SQLITE_DENY );
3477524cc21eSdanielk1977   pParse->zAuthContext = zSavedAuthContext;
3478524cc21eSdanielk1977 
34797d10d5a6Sdrh   /* If the sub-query is a compound SELECT statement, then (by restrictions
34807d10d5a6Sdrh   ** 17 and 18 above) it must be a UNION ALL and the parent query must
34817d10d5a6Sdrh   ** be of the form:
3482f23329a2Sdanielk1977   **
3483f23329a2Sdanielk1977   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
3484f23329a2Sdanielk1977   **
3485f23329a2Sdanielk1977   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
3486a78c22c4Sdrh   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
3487f23329a2Sdanielk1977   ** OFFSET clauses and joins them to the left-hand-side of the original
3488f23329a2Sdanielk1977   ** using UNION ALL operators. In this case N is the number of simple
3489f23329a2Sdanielk1977   ** select statements in the compound sub-query.
3490a78c22c4Sdrh   **
3491a78c22c4Sdrh   ** Example:
3492a78c22c4Sdrh   **
3493a78c22c4Sdrh   **     SELECT a+1 FROM (
3494a78c22c4Sdrh   **        SELECT x FROM tab
3495a78c22c4Sdrh   **        UNION ALL
3496a78c22c4Sdrh   **        SELECT y FROM tab
3497a78c22c4Sdrh   **        UNION ALL
3498a78c22c4Sdrh   **        SELECT abs(z*2) FROM tab2
3499a78c22c4Sdrh   **     ) WHERE a!=5 ORDER BY 1
3500a78c22c4Sdrh   **
3501a78c22c4Sdrh   ** Transformed into:
3502a78c22c4Sdrh   **
3503a78c22c4Sdrh   **     SELECT x+1 FROM tab WHERE x+1!=5
3504a78c22c4Sdrh   **     UNION ALL
3505a78c22c4Sdrh   **     SELECT y+1 FROM tab WHERE y+1!=5
3506a78c22c4Sdrh   **     UNION ALL
3507a78c22c4Sdrh   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
3508a78c22c4Sdrh   **     ORDER BY 1
3509a78c22c4Sdrh   **
3510a78c22c4Sdrh   ** We call this the "compound-subquery flattening".
3511f23329a2Sdanielk1977   */
3512f23329a2Sdanielk1977   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
3513f23329a2Sdanielk1977     Select *pNew;
3514f23329a2Sdanielk1977     ExprList *pOrderBy = p->pOrderBy;
35154b86ef1dSdanielk1977     Expr *pLimit = p->pLimit;
3516547180baSdrh     Expr *pOffset = p->pOffset;
3517f23329a2Sdanielk1977     Select *pPrior = p->pPrior;
3518f23329a2Sdanielk1977     p->pOrderBy = 0;
3519f23329a2Sdanielk1977     p->pSrc = 0;
3520f23329a2Sdanielk1977     p->pPrior = 0;
35214b86ef1dSdanielk1977     p->pLimit = 0;
3522547180baSdrh     p->pOffset = 0;
35236ab3a2ecSdanielk1977     pNew = sqlite3SelectDup(db, p, 0);
3524eb9b884cSdrh     sqlite3SelectSetName(pNew, pSub->zSelName);
3525547180baSdrh     p->pOffset = pOffset;
35264b86ef1dSdanielk1977     p->pLimit = pLimit;
3527a78c22c4Sdrh     p->pOrderBy = pOrderBy;
3528a78c22c4Sdrh     p->pSrc = pSrc;
3529a78c22c4Sdrh     p->op = TK_ALL;
3530a78c22c4Sdrh     if( pNew==0 ){
3531d227a291Sdrh       p->pPrior = pPrior;
3532a78c22c4Sdrh     }else{
3533a78c22c4Sdrh       pNew->pPrior = pPrior;
3534d227a291Sdrh       if( pPrior ) pPrior->pNext = pNew;
3535d227a291Sdrh       pNew->pNext = p;
3536a78c22c4Sdrh       p->pPrior = pNew;
3537eb9b884cSdrh       SELECTTRACE(2,pParse,p,
3538eb9b884cSdrh          ("compound-subquery flattener creates %s.%p as peer\n",
3539eb9b884cSdrh          pNew->zSelName, pNew));
3540d227a291Sdrh     }
3541a78c22c4Sdrh     if( db->mallocFailed ) return 1;
3542a78c22c4Sdrh   }
3543f23329a2Sdanielk1977 
35447d10d5a6Sdrh   /* Begin flattening the iFrom-th entry of the FROM clause
35457d10d5a6Sdrh   ** in the outer query.
3546832508b7Sdrh   */
3547f23329a2Sdanielk1977   pSub = pSub1 = pSubitem->pSelect;
3548c31c2eb8Sdrh 
3549a78c22c4Sdrh   /* Delete the transient table structure associated with the
3550a78c22c4Sdrh   ** subquery
3551a78c22c4Sdrh   */
3552a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zDatabase);
3553a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zName);
3554a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zAlias);
3555a78c22c4Sdrh   pSubitem->zDatabase = 0;
3556a78c22c4Sdrh   pSubitem->zName = 0;
3557a78c22c4Sdrh   pSubitem->zAlias = 0;
3558a78c22c4Sdrh   pSubitem->pSelect = 0;
3559a78c22c4Sdrh 
3560a78c22c4Sdrh   /* Defer deleting the Table object associated with the
3561a78c22c4Sdrh   ** subquery until code generation is
3562a78c22c4Sdrh   ** complete, since there may still exist Expr.pTab entries that
3563a78c22c4Sdrh   ** refer to the subquery even after flattening.  Ticket #3346.
3564ccfcbceaSdrh   **
3565ccfcbceaSdrh   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
3566a78c22c4Sdrh   */
3567ccfcbceaSdrh   if( ALWAYS(pSubitem->pTab!=0) ){
3568a78c22c4Sdrh     Table *pTabToDel = pSubitem->pTab;
3569a78c22c4Sdrh     if( pTabToDel->nRef==1 ){
357065a7cd16Sdan       Parse *pToplevel = sqlite3ParseToplevel(pParse);
357165a7cd16Sdan       pTabToDel->pNextZombie = pToplevel->pZombieTab;
357265a7cd16Sdan       pToplevel->pZombieTab = pTabToDel;
3573a78c22c4Sdrh     }else{
3574a78c22c4Sdrh       pTabToDel->nRef--;
3575a78c22c4Sdrh     }
3576a78c22c4Sdrh     pSubitem->pTab = 0;
3577a78c22c4Sdrh   }
3578a78c22c4Sdrh 
3579a78c22c4Sdrh   /* The following loop runs once for each term in a compound-subquery
3580a78c22c4Sdrh   ** flattening (as described above).  If we are doing a different kind
3581a78c22c4Sdrh   ** of flattening - a flattening other than a compound-subquery flattening -
3582a78c22c4Sdrh   ** then this loop only runs once.
3583a78c22c4Sdrh   **
3584a78c22c4Sdrh   ** This loop moves all of the FROM elements of the subquery into the
3585c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
3586c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
3587c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
3588c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
3589c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
3590c31c2eb8Sdrh   ** elements we are now copying in.
3591c31c2eb8Sdrh   */
3592a78c22c4Sdrh   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
3593a78c22c4Sdrh     int nSubSrc;
3594ea678832Sdrh     u8 jointype = 0;
3595a78c22c4Sdrh     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
3596a78c22c4Sdrh     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
3597a78c22c4Sdrh     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
3598588a9a1aSdrh 
3599a78c22c4Sdrh     if( pSrc ){
3600a78c22c4Sdrh       assert( pParent==p );  /* First time through the loop */
36018a48b9c0Sdrh       jointype = pSubitem->fg.jointype;
3602588a9a1aSdrh     }else{
3603a78c22c4Sdrh       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
3604a78c22c4Sdrh       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
3605cfa063b3Sdrh       if( pSrc==0 ){
3606a78c22c4Sdrh         assert( db->mallocFailed );
3607a78c22c4Sdrh         break;
3608cfa063b3Sdrh       }
3609c31c2eb8Sdrh     }
3610a78c22c4Sdrh 
3611a78c22c4Sdrh     /* The subquery uses a single slot of the FROM clause of the outer
3612a78c22c4Sdrh     ** query.  If the subquery has more than one element in its FROM clause,
3613a78c22c4Sdrh     ** then expand the outer query to make space for it to hold all elements
3614a78c22c4Sdrh     ** of the subquery.
3615a78c22c4Sdrh     **
3616a78c22c4Sdrh     ** Example:
3617a78c22c4Sdrh     **
3618a78c22c4Sdrh     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
3619a78c22c4Sdrh     **
3620a78c22c4Sdrh     ** The outer query has 3 slots in its FROM clause.  One slot of the
3621a78c22c4Sdrh     ** outer query (the middle slot) is used by the subquery.  The next
3622d12b6363Sdrh     ** block of code will expand the outer query FROM clause to 4 slots.
3623d12b6363Sdrh     ** The middle slot is expanded to two slots in order to make space
3624d12b6363Sdrh     ** for the two elements in the FROM clause of the subquery.
3625a78c22c4Sdrh     */
3626a78c22c4Sdrh     if( nSubSrc>1 ){
3627a78c22c4Sdrh       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
3628a78c22c4Sdrh       if( db->mallocFailed ){
3629a78c22c4Sdrh         break;
3630c31c2eb8Sdrh       }
3631c31c2eb8Sdrh     }
3632a78c22c4Sdrh 
3633a78c22c4Sdrh     /* Transfer the FROM clause terms from the subquery into the
3634a78c22c4Sdrh     ** outer query.
3635a78c22c4Sdrh     */
3636c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
3637c3a8402aSdrh       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
363820292310Sdrh       assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
3639c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
3640c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
3641c31c2eb8Sdrh     }
36428a48b9c0Sdrh     pSrc->a[iFrom].fg.jointype = jointype;
3643c31c2eb8Sdrh 
3644c31c2eb8Sdrh     /* Now begin substituting subquery result set expressions for
3645c31c2eb8Sdrh     ** references to the iParent in the outer query.
3646c31c2eb8Sdrh     **
3647c31c2eb8Sdrh     ** Example:
3648c31c2eb8Sdrh     **
3649c31c2eb8Sdrh     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
3650c31c2eb8Sdrh     **   \                     \_____________ subquery __________/          /
3651c31c2eb8Sdrh     **    \_____________________ outer query ______________________________/
3652c31c2eb8Sdrh     **
3653c31c2eb8Sdrh     ** We look at every expression in the outer query and every place we see
3654c31c2eb8Sdrh     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
3655c31c2eb8Sdrh     */
3656f23329a2Sdanielk1977     pList = pParent->pEList;
3657832508b7Sdrh     for(i=0; i<pList->nExpr; i++){
3658ccfcbceaSdrh       if( pList->a[i].zName==0 ){
365942fbf321Sdrh         char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
366042fbf321Sdrh         sqlite3Dequote(zName);
366142fbf321Sdrh         pList->a[i].zName = zName;
3662832508b7Sdrh       }
3663ccfcbceaSdrh     }
3664174b6195Sdrh     if( pSub->pOrderBy ){
36657c0a4720Sdan       /* At this point, any non-zero iOrderByCol values indicate that the
36667c0a4720Sdan       ** ORDER BY column expression is identical to the iOrderByCol'th
36677c0a4720Sdan       ** expression returned by SELECT statement pSub. Since these values
36687c0a4720Sdan       ** do not necessarily correspond to columns in SELECT statement pParent,
36697c0a4720Sdan       ** zero them before transfering the ORDER BY clause.
36707c0a4720Sdan       **
36717c0a4720Sdan       ** Not doing this may cause an error if a subsequent call to this
36727c0a4720Sdan       ** function attempts to flatten a compound sub-query into pParent
36737c0a4720Sdan       ** (the only way this can happen is if the compound sub-query is
36747c0a4720Sdan       ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
36757c0a4720Sdan       ExprList *pOrderBy = pSub->pOrderBy;
36767c0a4720Sdan       for(i=0; i<pOrderBy->nExpr; i++){
36777c0a4720Sdan         pOrderBy->a[i].u.x.iOrderByCol = 0;
36787c0a4720Sdan       }
3679f23329a2Sdanielk1977       assert( pParent->pOrderBy==0 );
36807c0a4720Sdan       assert( pSub->pPrior==0 );
36817c0a4720Sdan       pParent->pOrderBy = pOrderBy;
3682174b6195Sdrh       pSub->pOrderBy = 0;
3683174b6195Sdrh     }
36846ab3a2ecSdanielk1977     pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
3685832508b7Sdrh     if( subqueryIsAgg ){
3686f23329a2Sdanielk1977       assert( pParent->pHaving==0 );
3687f23329a2Sdanielk1977       pParent->pHaving = pParent->pWhere;
3688f23329a2Sdanielk1977       pParent->pWhere = pWhere;
3689f23329a2Sdanielk1977       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
36906ab3a2ecSdanielk1977                                   sqlite3ExprDup(db, pSub->pHaving, 0));
3691f23329a2Sdanielk1977       assert( pParent->pGroupBy==0 );
36926ab3a2ecSdanielk1977       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
3693832508b7Sdrh     }else{
3694f23329a2Sdanielk1977       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
3695832508b7Sdrh     }
3696d12b6363Sdrh     substSelect(db, pParent, iParent, pSub->pEList, 0);
3697c31c2eb8Sdrh 
3698c31c2eb8Sdrh     /* The flattened query is distinct if either the inner or the
3699c31c2eb8Sdrh     ** outer query is distinct.
3700c31c2eb8Sdrh     */
37017d10d5a6Sdrh     pParent->selFlags |= pSub->selFlags & SF_Distinct;
37028c74a8caSdrh 
3703a58fdfb1Sdanielk1977     /*
3704a58fdfb1Sdanielk1977     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
3705ac83963aSdrh     **
3706ac83963aSdrh     ** One is tempted to try to add a and b to combine the limits.  But this
3707ac83963aSdrh     ** does not work if either limit is negative.
3708a58fdfb1Sdanielk1977     */
3709a2dc3b1aSdanielk1977     if( pSub->pLimit ){
3710f23329a2Sdanielk1977       pParent->pLimit = pSub->pLimit;
3711a2dc3b1aSdanielk1977       pSub->pLimit = 0;
3712df199a25Sdrh     }
3713f23329a2Sdanielk1977   }
37148c74a8caSdrh 
3715c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
3716c31c2eb8Sdrh   ** success.
3717c31c2eb8Sdrh   */
3718633e6d57Sdrh   sqlite3SelectDelete(db, pSub1);
3719f23329a2Sdanielk1977 
3720c90713d3Sdrh #if SELECTTRACE_ENABLED
3721c90713d3Sdrh   if( sqlite3SelectTrace & 0x100 ){
3722bc8edba1Sdrh     SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
3723c90713d3Sdrh     sqlite3TreeViewSelect(0, p, 0);
3724c90713d3Sdrh   }
3725c90713d3Sdrh #endif
3726c90713d3Sdrh 
3727832508b7Sdrh   return 1;
37281350b030Sdrh }
37293514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
37301350b030Sdrh 
373169b72d5aSdrh 
373269b72d5aSdrh 
373369b72d5aSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
373469b72d5aSdrh /*
373569b72d5aSdrh ** Make copies of relevant WHERE clause terms of the outer query into
373669b72d5aSdrh ** the WHERE clause of subquery.  Example:
373769b72d5aSdrh **
373869b72d5aSdrh **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
373969b72d5aSdrh **
374069b72d5aSdrh ** Transformed into:
374169b72d5aSdrh **
374269b72d5aSdrh **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
374369b72d5aSdrh **     WHERE x=5 AND y=10;
374469b72d5aSdrh **
374569b72d5aSdrh ** The hope is that the terms added to the inner query will make it more
374669b72d5aSdrh ** efficient.
374769b72d5aSdrh **
374869b72d5aSdrh ** Do not attempt this optimization if:
374969b72d5aSdrh **
375069b72d5aSdrh **   (1) The inner query is an aggregate.  (In that case, we'd really want
375169b72d5aSdrh **       to copy the outer WHERE-clause terms onto the HAVING clause of the
375269b72d5aSdrh **       inner query.  But they probably won't help there so do not bother.)
375369b72d5aSdrh **
375469b72d5aSdrh **   (2) The inner query is the recursive part of a common table expression.
375569b72d5aSdrh **
375669b72d5aSdrh **   (3) The inner query has a LIMIT clause (since the changes to the WHERE
375769b72d5aSdrh **       close would change the meaning of the LIMIT).
375869b72d5aSdrh **
375969b72d5aSdrh **   (4) The inner query is the right operand of a LEFT JOIN.  (The caller
376069b72d5aSdrh **       enforces this restriction since this routine does not have enough
376169b72d5aSdrh **       information to know.)
376269b72d5aSdrh **
376338978dd4Sdrh **   (5) The WHERE clause expression originates in the ON or USING clause
376438978dd4Sdrh **       of a LEFT JOIN.
376538978dd4Sdrh **
376669b72d5aSdrh ** Return 0 if no changes are made and non-zero if one or more WHERE clause
376769b72d5aSdrh ** terms are duplicated into the subquery.
376869b72d5aSdrh */
376969b72d5aSdrh static int pushDownWhereTerms(
377069b72d5aSdrh   sqlite3 *db,          /* The database connection (for malloc()) */
377169b72d5aSdrh   Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
377269b72d5aSdrh   Expr *pWhere,         /* The WHERE clause of the outer query */
377369b72d5aSdrh   int iCursor           /* Cursor number of the subquery */
377469b72d5aSdrh ){
377569b72d5aSdrh   Expr *pNew;
377669b72d5aSdrh   int nChng = 0;
377769b72d5aSdrh   if( pWhere==0 ) return 0;
377869b72d5aSdrh   if( (pSubq->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
377969b72d5aSdrh      return 0; /* restrictions (1) and (2) */
378069b72d5aSdrh   }
378169b72d5aSdrh   if( pSubq->pLimit!=0 ){
378269b72d5aSdrh      return 0; /* restriction (3) */
378369b72d5aSdrh   }
378469b72d5aSdrh   while( pWhere->op==TK_AND ){
378569b72d5aSdrh     nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
378669b72d5aSdrh     pWhere = pWhere->pLeft;
378769b72d5aSdrh   }
378838978dd4Sdrh   if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
378969b72d5aSdrh   if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
379069b72d5aSdrh     nChng++;
379169b72d5aSdrh     while( pSubq ){
379269b72d5aSdrh       pNew = sqlite3ExprDup(db, pWhere, 0);
379369b72d5aSdrh       pNew = substExpr(db, pNew, iCursor, pSubq->pEList);
379469b72d5aSdrh       pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew);
379569b72d5aSdrh       pSubq = pSubq->pPrior;
379669b72d5aSdrh     }
379769b72d5aSdrh   }
379869b72d5aSdrh   return nChng;
379969b72d5aSdrh }
380069b72d5aSdrh #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
380169b72d5aSdrh 
38021350b030Sdrh /*
38034ac391fcSdan ** Based on the contents of the AggInfo structure indicated by the first
38044ac391fcSdan ** argument, this function checks if the following are true:
3805a9d1ccb9Sdanielk1977 **
38064ac391fcSdan **    * the query contains just a single aggregate function,
38074ac391fcSdan **    * the aggregate function is either min() or max(), and
38084ac391fcSdan **    * the argument to the aggregate function is a column value.
3809738bdcfbSdanielk1977 **
38104ac391fcSdan ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
38114ac391fcSdan ** is returned as appropriate. Also, *ppMinMax is set to point to the
38124ac391fcSdan ** list of arguments passed to the aggregate before returning.
38134ac391fcSdan **
38144ac391fcSdan ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
38154ac391fcSdan ** WHERE_ORDERBY_NORMAL is returned.
3816a9d1ccb9Sdanielk1977 */
38174ac391fcSdan static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
38184ac391fcSdan   int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
3819a9d1ccb9Sdanielk1977 
38204ac391fcSdan   *ppMinMax = 0;
38214ac391fcSdan   if( pAggInfo->nFunc==1 ){
38224ac391fcSdan     Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
38234ac391fcSdan     ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
38244ac391fcSdan 
38254ac391fcSdan     assert( pExpr->op==TK_AGG_FUNCTION );
38264ac391fcSdan     if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
38274ac391fcSdan       const char *zFunc = pExpr->u.zToken;
38284ac391fcSdan       if( sqlite3StrICmp(zFunc, "min")==0 ){
38294ac391fcSdan         eRet = WHERE_ORDERBY_MIN;
38304ac391fcSdan         *ppMinMax = pEList;
38314ac391fcSdan       }else if( sqlite3StrICmp(zFunc, "max")==0 ){
38324ac391fcSdan         eRet = WHERE_ORDERBY_MAX;
38334ac391fcSdan         *ppMinMax = pEList;
3834a9d1ccb9Sdanielk1977       }
38354ac391fcSdan     }
38364ac391fcSdan   }
38374ac391fcSdan 
38384ac391fcSdan   assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
38394ac391fcSdan   return eRet;
3840a9d1ccb9Sdanielk1977 }
3841a9d1ccb9Sdanielk1977 
3842a9d1ccb9Sdanielk1977 /*
3843a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query.
384460ec914cSpeter.d.reid ** The second argument is the associated aggregate-info object. This
3845a5533162Sdanielk1977 ** function tests if the SELECT is of the form:
3846a5533162Sdanielk1977 **
3847a5533162Sdanielk1977 **   SELECT count(*) FROM <tbl>
3848a5533162Sdanielk1977 **
3849a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query
3850a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing
3851a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned.
3852a5533162Sdanielk1977 */
3853a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
3854a5533162Sdanielk1977   Table *pTab;
3855a5533162Sdanielk1977   Expr *pExpr;
3856a5533162Sdanielk1977 
3857a5533162Sdanielk1977   assert( !p->pGroupBy );
3858a5533162Sdanielk1977 
38597a895a80Sdanielk1977   if( p->pWhere || p->pEList->nExpr!=1
3860a5533162Sdanielk1977    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
3861a5533162Sdanielk1977   ){
3862a5533162Sdanielk1977     return 0;
3863a5533162Sdanielk1977   }
3864a5533162Sdanielk1977   pTab = p->pSrc->a[0].pTab;
3865a5533162Sdanielk1977   pExpr = p->pEList->a[0].pExpr;
386602f33725Sdanielk1977   assert( pTab && !pTab->pSelect && pExpr );
386702f33725Sdanielk1977 
386802f33725Sdanielk1977   if( IsVirtual(pTab) ) return 0;
3869a5533162Sdanielk1977   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
3870fb0a6081Sdrh   if( NEVER(pAggInfo->nFunc==0) ) return 0;
3871d36e1041Sdrh   if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
3872a5533162Sdanielk1977   if( pExpr->flags&EP_Distinct ) return 0;
3873a5533162Sdanielk1977 
3874a5533162Sdanielk1977   return pTab;
3875a5533162Sdanielk1977 }
3876a5533162Sdanielk1977 
3877a5533162Sdanielk1977 /*
3878b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an
3879b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there
3880b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return
3881b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
3882b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK.
3883b1c685b0Sdanielk1977 */
3884b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
38858a48b9c0Sdrh   if( pFrom->pTab && pFrom->fg.isIndexedBy ){
3886b1c685b0Sdanielk1977     Table *pTab = pFrom->pTab;
38878a48b9c0Sdrh     char *zIndexedBy = pFrom->u1.zIndexedBy;
3888b1c685b0Sdanielk1977     Index *pIdx;
3889b1c685b0Sdanielk1977     for(pIdx=pTab->pIndex;
3890d62fbb50Sdrh         pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
3891b1c685b0Sdanielk1977         pIdx=pIdx->pNext
3892b1c685b0Sdanielk1977     );
3893b1c685b0Sdanielk1977     if( !pIdx ){
3894d62fbb50Sdrh       sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
38951db95106Sdan       pParse->checkSchema = 1;
3896b1c685b0Sdanielk1977       return SQLITE_ERROR;
3897b1c685b0Sdanielk1977     }
38988a48b9c0Sdrh     pFrom->pIBIndex = pIdx;
3899b1c685b0Sdanielk1977   }
3900b1c685b0Sdanielk1977   return SQLITE_OK;
3901b1c685b0Sdanielk1977 }
3902c01b7306Sdrh /*
3903c01b7306Sdrh ** Detect compound SELECT statements that use an ORDER BY clause with
3904c01b7306Sdrh ** an alternative collating sequence.
3905c01b7306Sdrh **
3906c01b7306Sdrh **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
3907c01b7306Sdrh **
3908c01b7306Sdrh ** These are rewritten as a subquery:
3909c01b7306Sdrh **
3910c01b7306Sdrh **    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
3911c01b7306Sdrh **     ORDER BY ... COLLATE ...
3912c01b7306Sdrh **
3913c01b7306Sdrh ** This transformation is necessary because the multiSelectOrderBy() routine
3914c01b7306Sdrh ** above that generates the code for a compound SELECT with an ORDER BY clause
3915c01b7306Sdrh ** uses a merge algorithm that requires the same collating sequence on the
3916c01b7306Sdrh ** result columns as on the ORDER BY clause.  See ticket
3917c01b7306Sdrh ** http://www.sqlite.org/src/info/6709574d2a
3918c01b7306Sdrh **
3919c01b7306Sdrh ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
3920c01b7306Sdrh ** The UNION ALL operator works fine with multiSelectOrderBy() even when
3921c01b7306Sdrh ** there are COLLATE terms in the ORDER BY.
3922c01b7306Sdrh */
3923c01b7306Sdrh static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
3924c01b7306Sdrh   int i;
3925c01b7306Sdrh   Select *pNew;
3926c01b7306Sdrh   Select *pX;
3927c01b7306Sdrh   sqlite3 *db;
3928c01b7306Sdrh   struct ExprList_item *a;
3929c01b7306Sdrh   SrcList *pNewSrc;
3930c01b7306Sdrh   Parse *pParse;
3931c01b7306Sdrh   Token dummy;
3932c01b7306Sdrh 
3933c01b7306Sdrh   if( p->pPrior==0 ) return WRC_Continue;
3934c01b7306Sdrh   if( p->pOrderBy==0 ) return WRC_Continue;
3935c01b7306Sdrh   for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
3936c01b7306Sdrh   if( pX==0 ) return WRC_Continue;
3937c01b7306Sdrh   a = p->pOrderBy->a;
3938c01b7306Sdrh   for(i=p->pOrderBy->nExpr-1; i>=0; i--){
3939c01b7306Sdrh     if( a[i].pExpr->flags & EP_Collate ) break;
3940c01b7306Sdrh   }
3941c01b7306Sdrh   if( i<0 ) return WRC_Continue;
3942c01b7306Sdrh 
3943c01b7306Sdrh   /* If we reach this point, that means the transformation is required. */
3944c01b7306Sdrh 
3945c01b7306Sdrh   pParse = pWalker->pParse;
3946c01b7306Sdrh   db = pParse->db;
3947c01b7306Sdrh   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
3948c01b7306Sdrh   if( pNew==0 ) return WRC_Abort;
3949c01b7306Sdrh   memset(&dummy, 0, sizeof(dummy));
3950c01b7306Sdrh   pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
3951c01b7306Sdrh   if( pNewSrc==0 ) return WRC_Abort;
3952c01b7306Sdrh   *pNew = *p;
3953c01b7306Sdrh   p->pSrc = pNewSrc;
39541a1d3cd2Sdrh   p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
3955c01b7306Sdrh   p->op = TK_SELECT;
3956c01b7306Sdrh   p->pWhere = 0;
3957c01b7306Sdrh   pNew->pGroupBy = 0;
3958c01b7306Sdrh   pNew->pHaving = 0;
3959c01b7306Sdrh   pNew->pOrderBy = 0;
3960c01b7306Sdrh   p->pPrior = 0;
39618af9ad95Sdrh   p->pNext = 0;
3962f932f714Sdrh   p->pWith = 0;
39638af9ad95Sdrh   p->selFlags &= ~SF_Compound;
3964b33c50f2Sdan   assert( (p->selFlags & SF_Converted)==0 );
3965b33c50f2Sdan   p->selFlags |= SF_Converted;
3966a6e3a8c9Sdrh   assert( pNew->pPrior!=0 );
3967a6e3a8c9Sdrh   pNew->pPrior->pNext = pNew;
3968c01b7306Sdrh   pNew->pLimit = 0;
3969c01b7306Sdrh   pNew->pOffset = 0;
3970c01b7306Sdrh   return WRC_Continue;
3971c01b7306Sdrh }
3972b1c685b0Sdanielk1977 
397320292310Sdrh /*
397420292310Sdrh ** Check to see if the FROM clause term pFrom has table-valued function
397520292310Sdrh ** arguments.  If it does, leave an error message in pParse and return
397620292310Sdrh ** non-zero, since pFrom is not allowed to be a table-valued function.
397720292310Sdrh */
397820292310Sdrh static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
397920292310Sdrh   if( pFrom->fg.isTabFunc ){
398020292310Sdrh     sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
398120292310Sdrh     return 1;
398220292310Sdrh   }
398320292310Sdrh   return 0;
398420292310Sdrh }
398520292310Sdrh 
3986eede6a53Sdan #ifndef SQLITE_OMIT_CTE
3987eede6a53Sdan /*
3988eede6a53Sdan ** Argument pWith (which may be NULL) points to a linked list of nested
3989eede6a53Sdan ** WITH contexts, from inner to outermost. If the table identified by
3990eede6a53Sdan ** FROM clause element pItem is really a common-table-expression (CTE)
3991eede6a53Sdan ** then return a pointer to the CTE definition for that table. Otherwise
3992eede6a53Sdan ** return NULL.
399398f45e53Sdan **
399498f45e53Sdan ** If a non-NULL value is returned, set *ppContext to point to the With
399598f45e53Sdan ** object that the returned CTE belongs to.
399660c1a2f0Sdrh */
399798f45e53Sdan static struct Cte *searchWith(
39982476a6f2Sdrh   With *pWith,                    /* Current innermost WITH clause */
399998f45e53Sdan   struct SrcList_item *pItem,     /* FROM clause element to resolve */
400098f45e53Sdan   With **ppContext                /* OUT: WITH clause return value belongs to */
400198f45e53Sdan ){
40027b19f252Sdrh   const char *zName;
40037b19f252Sdrh   if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
4004eede6a53Sdan     With *p;
4005eede6a53Sdan     for(p=pWith; p; p=p->pOuter){
40064e9119d9Sdan       int i;
4007eede6a53Sdan       for(i=0; i<p->nCte; i++){
4008eede6a53Sdan         if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
400998f45e53Sdan           *ppContext = p;
4010eede6a53Sdan           return &p->a[i];
40114e9119d9Sdan         }
40124e9119d9Sdan       }
40134e9119d9Sdan     }
40144e9119d9Sdan   }
40154e9119d9Sdan   return 0;
40164e9119d9Sdan }
40174e9119d9Sdan 
4018c49832c2Sdrh /* The code generator maintains a stack of active WITH clauses
4019c49832c2Sdrh ** with the inner-most WITH clause being at the top of the stack.
4020c49832c2Sdrh **
4021b290f117Sdan ** This routine pushes the WITH clause passed as the second argument
4022b290f117Sdan ** onto the top of the stack. If argument bFree is true, then this
4023b290f117Sdan ** WITH clause will never be popped from the stack. In this case it
4024b290f117Sdan ** should be freed along with the Parse object. In other cases, when
4025b290f117Sdan ** bFree==0, the With object will be freed along with the SELECT
4026b290f117Sdan ** statement with which it is associated.
4027c49832c2Sdrh */
4028b290f117Sdan void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
40296e772266Sdrh   assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
40304e9119d9Sdan   if( pWith ){
40312476a6f2Sdrh     assert( pParse->pWith!=pWith );
40324e9119d9Sdan     pWith->pOuter = pParse->pWith;
40334e9119d9Sdan     pParse->pWith = pWith;
40346e772266Sdrh     if( bFree ) pParse->pWithToFree = pWith;
40354e9119d9Sdan   }
40364e9119d9Sdan }
40374e9119d9Sdan 
4038eede6a53Sdan /*
4039eede6a53Sdan ** This function checks if argument pFrom refers to a CTE declared by
4040eede6a53Sdan ** a WITH clause on the stack currently maintained by the parser. And,
4041eede6a53Sdan ** if currently processing a CTE expression, if it is a recursive
4042eede6a53Sdan ** reference to the current CTE.
4043eede6a53Sdan **
4044eede6a53Sdan ** If pFrom falls into either of the two categories above, pFrom->pTab
4045eede6a53Sdan ** and other fields are populated accordingly. The caller should check
4046eede6a53Sdan ** (pFrom->pTab!=0) to determine whether or not a successful match
4047eede6a53Sdan ** was found.
4048eede6a53Sdan **
4049eede6a53Sdan ** Whether or not a match is found, SQLITE_OK is returned if no error
4050eede6a53Sdan ** occurs. If an error does occur, an error message is stored in the
4051eede6a53Sdan ** parser and some error code other than SQLITE_OK returned.
4052eede6a53Sdan */
40538ce7184bSdan static int withExpand(
40548ce7184bSdan   Walker *pWalker,
4055eede6a53Sdan   struct SrcList_item *pFrom
40568ce7184bSdan ){
40578ce7184bSdan   Parse *pParse = pWalker->pParse;
40588ce7184bSdan   sqlite3 *db = pParse->db;
405998f45e53Sdan   struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
406098f45e53Sdan   With *pWith;                    /* WITH clause that pCte belongs to */
40618ce7184bSdan 
40628ce7184bSdan   assert( pFrom->pTab==0 );
40638ce7184bSdan 
406498f45e53Sdan   pCte = searchWith(pParse->pWith, pFrom, &pWith);
4065eae73fbfSdan   if( pCte ){
406698f45e53Sdan     Table *pTab;
40678ce7184bSdan     ExprList *pEList;
40688ce7184bSdan     Select *pSel;
406960e7068dSdan     Select *pLeft;                /* Left-most SELECT statement */
4070f2655fe8Sdan     int bMayRecursive;            /* True if compound joined by UNION [ALL] */
407198f45e53Sdan     With *pSavedWith;             /* Initial value of pParse->pWith */
4072f2655fe8Sdan 
40730576bc59Sdrh     /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
4074f2655fe8Sdan     ** recursive reference to CTE pCte. Leave an error in pParse and return
40750576bc59Sdrh     ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
4076f2655fe8Sdan     ** In this case, proceed.  */
40770576bc59Sdrh     if( pCte->zCteErr ){
40780576bc59Sdrh       sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
407998f45e53Sdan       return SQLITE_ERROR;
4080f2655fe8Sdan     }
408120292310Sdrh     if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
40828ce7184bSdan 
4083c25e2ebcSdrh     assert( pFrom->pTab==0 );
40848ce7184bSdan     pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
40858ce7184bSdan     if( pTab==0 ) return WRC_Abort;
40868ce7184bSdan     pTab->nRef = 1;
40872d4dc5fcSdan     pTab->zName = sqlite3DbStrDup(db, pCte->zName);
40888ce7184bSdan     pTab->iPKey = -1;
4089cfc9df76Sdan     pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
4090fccda8a1Sdrh     pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
40918ce7184bSdan     pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
40928ce7184bSdan     if( db->mallocFailed ) return SQLITE_NOMEM;
40938ce7184bSdan     assert( pFrom->pSelect );
40948ce7184bSdan 
4095eae73fbfSdan     /* Check if this is a recursive CTE. */
40968ce7184bSdan     pSel = pFrom->pSelect;
4097f2655fe8Sdan     bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
4098f2655fe8Sdan     if( bMayRecursive ){
4099eae73fbfSdan       int i;
4100eae73fbfSdan       SrcList *pSrc = pFrom->pSelect->pSrc;
4101eae73fbfSdan       for(i=0; i<pSrc->nSrc; i++){
4102eae73fbfSdan         struct SrcList_item *pItem = &pSrc->a[i];
4103eae73fbfSdan         if( pItem->zDatabase==0
4104eae73fbfSdan          && pItem->zName!=0
4105eae73fbfSdan          && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
4106eae73fbfSdan           ){
4107eae73fbfSdan           pItem->pTab = pTab;
41088a48b9c0Sdrh           pItem->fg.isRecursive = 1;
4109eae73fbfSdan           pTab->nRef++;
4110eae73fbfSdan           pSel->selFlags |= SF_Recursive;
41118ce7184bSdan         }
4112eae73fbfSdan       }
4113eae73fbfSdan     }
4114eae73fbfSdan 
4115eae73fbfSdan     /* Only one recursive reference is permitted. */
4116eae73fbfSdan     if( pTab->nRef>2 ){
4117eae73fbfSdan       sqlite3ErrorMsg(
4118727a99f1Sdrh           pParse, "multiple references to recursive table: %s", pCte->zName
4119eae73fbfSdan       );
412098f45e53Sdan       return SQLITE_ERROR;
4121eae73fbfSdan     }
4122eae73fbfSdan     assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
4123eae73fbfSdan 
41240576bc59Sdrh     pCte->zCteErr = "circular reference: %s";
412598f45e53Sdan     pSavedWith = pParse->pWith;
412698f45e53Sdan     pParse->pWith = pWith;
4127f2655fe8Sdan     sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
41286e772266Sdrh     pParse->pWith = pWith;
41298ce7184bSdan 
41308ce7184bSdan     for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
41318ce7184bSdan     pEList = pLeft->pEList;
413260e7068dSdan     if( pCte->pCols ){
41338f9d0b2bSdrh       if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
4134727a99f1Sdrh         sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
413560e7068dSdan             pCte->zName, pEList->nExpr, pCte->pCols->nExpr
413660e7068dSdan         );
413798f45e53Sdan         pParse->pWith = pSavedWith;
413898f45e53Sdan         return SQLITE_ERROR;
41398ce7184bSdan       }
414060e7068dSdan       pEList = pCte->pCols;
414160e7068dSdan     }
41428ce7184bSdan 
41438981b904Sdrh     sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
4144f2655fe8Sdan     if( bMayRecursive ){
4145f2655fe8Sdan       if( pSel->selFlags & SF_Recursive ){
41460576bc59Sdrh         pCte->zCteErr = "multiple recursive references: %s";
4147f2655fe8Sdan       }else{
41480576bc59Sdrh         pCte->zCteErr = "recursive reference in a subquery: %s";
4149f2655fe8Sdan       }
4150f2655fe8Sdan       sqlite3WalkSelect(pWalker, pSel);
4151f2655fe8Sdan     }
41520576bc59Sdrh     pCte->zCteErr = 0;
415398f45e53Sdan     pParse->pWith = pSavedWith;
41548ce7184bSdan   }
41558ce7184bSdan 
41568ce7184bSdan   return SQLITE_OK;
41578ce7184bSdan }
4158eede6a53Sdan #endif
41594e9119d9Sdan 
4160b290f117Sdan #ifndef SQLITE_OMIT_CTE
416171856944Sdan /*
416271856944Sdan ** If the SELECT passed as the second argument has an associated WITH
416371856944Sdan ** clause, pop it from the stack stored as part of the Parse object.
416471856944Sdan **
416571856944Sdan ** This function is used as the xSelectCallback2() callback by
416671856944Sdan ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
416771856944Sdan ** names and other FROM clause elements.
416871856944Sdan */
4169b290f117Sdan static void selectPopWith(Walker *pWalker, Select *p){
4170b290f117Sdan   Parse *pParse = pWalker->pParse;
4171d227a291Sdrh   With *pWith = findRightmost(p)->pWith;
4172d227a291Sdrh   if( pWith!=0 ){
4173d227a291Sdrh     assert( pParse->pWith==pWith );
4174d227a291Sdrh     pParse->pWith = pWith->pOuter;
4175b290f117Sdan   }
4176b290f117Sdan }
4177b290f117Sdan #else
4178b290f117Sdan #define selectPopWith 0
4179b290f117Sdan #endif
4180b290f117Sdan 
4181b1c685b0Sdanielk1977 /*
41827d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement.
41837d10d5a6Sdrh ** "Expanding" means to do the following:
41847d10d5a6Sdrh **
41857d10d5a6Sdrh **    (1)  Make sure VDBE cursor numbers have been assigned to every
41867d10d5a6Sdrh **         element of the FROM clause.
41877d10d5a6Sdrh **
41887d10d5a6Sdrh **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
41897d10d5a6Sdrh **         defines FROM clause.  When views appear in the FROM clause,
41907d10d5a6Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
41917d10d5a6Sdrh **         that implements the view.  A copy is made of the view's SELECT
41927d10d5a6Sdrh **         statement so that we can freely modify or delete that statement
419360ec914cSpeter.d.reid **         without worrying about messing up the persistent representation
41947d10d5a6Sdrh **         of the view.
41957d10d5a6Sdrh **
419660ec914cSpeter.d.reid **    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
41977d10d5a6Sdrh **         on joins and the ON and USING clause of joins.
41987d10d5a6Sdrh **
41997d10d5a6Sdrh **    (4)  Scan the list of columns in the result set (pEList) looking
42007d10d5a6Sdrh **         for instances of the "*" operator or the TABLE.* operator.
42017d10d5a6Sdrh **         If found, expand each "*" to be every column in every table
42027d10d5a6Sdrh **         and TABLE.* to be every column in TABLE.
42037d10d5a6Sdrh **
4204b3bce662Sdanielk1977 */
42057d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){
42067d10d5a6Sdrh   Parse *pParse = pWalker->pParse;
42077d10d5a6Sdrh   int i, j, k;
42087d10d5a6Sdrh   SrcList *pTabList;
42097d10d5a6Sdrh   ExprList *pEList;
42107d10d5a6Sdrh   struct SrcList_item *pFrom;
42117d10d5a6Sdrh   sqlite3 *db = pParse->db;
42123e3f1a5bSdrh   Expr *pE, *pRight, *pExpr;
4213785097daSdrh   u16 selFlags = p->selFlags;
42147d10d5a6Sdrh 
4215785097daSdrh   p->selFlags |= SF_Expanded;
42167d10d5a6Sdrh   if( db->mallocFailed  ){
42177d10d5a6Sdrh     return WRC_Abort;
42187d10d5a6Sdrh   }
4219785097daSdrh   if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
42207d10d5a6Sdrh     return WRC_Prune;
42217d10d5a6Sdrh   }
42227d10d5a6Sdrh   pTabList = p->pSrc;
42237d10d5a6Sdrh   pEList = p->pEList;
42243afd2b4dSdrh   if( pWalker->xSelectCallback2==selectPopWith ){
4225d227a291Sdrh     sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
42263afd2b4dSdrh   }
42277d10d5a6Sdrh 
42287d10d5a6Sdrh   /* Make sure cursor numbers have been assigned to all entries in
42297d10d5a6Sdrh   ** the FROM clause of the SELECT statement.
42307d10d5a6Sdrh   */
42317d10d5a6Sdrh   sqlite3SrcListAssignCursors(pParse, pTabList);
42327d10d5a6Sdrh 
42337d10d5a6Sdrh   /* Look up every table named in the FROM clause of the select.  If
42347d10d5a6Sdrh   ** an entry of the FROM clause is a subquery instead of a table or view,
42357d10d5a6Sdrh   ** then create a transient table structure to describe the subquery.
42367d10d5a6Sdrh   */
42377d10d5a6Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
42387d10d5a6Sdrh     Table *pTab;
4239e2b7d7a0Sdrh     assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
42408a48b9c0Sdrh     if( pFrom->fg.isRecursive ) continue;
4241e2b7d7a0Sdrh     assert( pFrom->pTab==0 );
42424e9119d9Sdan #ifndef SQLITE_OMIT_CTE
4243eede6a53Sdan     if( withExpand(pWalker, pFrom) ) return WRC_Abort;
4244eede6a53Sdan     if( pFrom->pTab ) {} else
42454e9119d9Sdan #endif
42467d10d5a6Sdrh     if( pFrom->zName==0 ){
42477d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
42487d10d5a6Sdrh       Select *pSel = pFrom->pSelect;
42497d10d5a6Sdrh       /* A sub-query in the FROM clause of a SELECT */
42507d10d5a6Sdrh       assert( pSel!=0 );
42517d10d5a6Sdrh       assert( pFrom->pTab==0 );
42522b8c5a00Sdrh       if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
42537d10d5a6Sdrh       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
42547d10d5a6Sdrh       if( pTab==0 ) return WRC_Abort;
42557d10d5a6Sdrh       pTab->nRef = 1;
4256186ad8ccSdrh       pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
42577d10d5a6Sdrh       while( pSel->pPrior ){ pSel = pSel->pPrior; }
42588981b904Sdrh       sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
42597d10d5a6Sdrh       pTab->iPKey = -1;
4260cfc9df76Sdan       pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
42617d10d5a6Sdrh       pTab->tabFlags |= TF_Ephemeral;
42627d10d5a6Sdrh #endif
42637d10d5a6Sdrh     }else{
42647d10d5a6Sdrh       /* An ordinary table or view name in the FROM clause */
42657d10d5a6Sdrh       assert( pFrom->pTab==0 );
426641fb5cd1Sdan       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
42677d10d5a6Sdrh       if( pTab==0 ) return WRC_Abort;
4268d2a56238Sdrh       if( pTab->nRef==0xffff ){
4269d2a56238Sdrh         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
4270d2a56238Sdrh            pTab->zName);
4271d2a56238Sdrh         pFrom->pTab = 0;
4272d2a56238Sdrh         return WRC_Abort;
4273d2a56238Sdrh       }
42747d10d5a6Sdrh       pTab->nRef++;
427520292310Sdrh       if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
427620292310Sdrh         return WRC_Abort;
427720292310Sdrh       }
42787d10d5a6Sdrh #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
427920292310Sdrh       if( IsVirtual(pTab) || pTab->pSelect ){
4280bfad7be7Sdrh         i16 nCol;
42817d10d5a6Sdrh         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
428243152cf8Sdrh         assert( pFrom->pSelect==0 );
42836ab3a2ecSdanielk1977         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
4284eb9b884cSdrh         sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
4285bfad7be7Sdrh         nCol = pTab->nCol;
4286bfad7be7Sdrh         pTab->nCol = -1;
42877d10d5a6Sdrh         sqlite3WalkSelect(pWalker, pFrom->pSelect);
4288bfad7be7Sdrh         pTab->nCol = nCol;
42897d10d5a6Sdrh       }
42907d10d5a6Sdrh #endif
42917d10d5a6Sdrh     }
429285574e31Sdanielk1977 
429385574e31Sdanielk1977     /* Locate the index named by the INDEXED BY clause, if any. */
4294b1c685b0Sdanielk1977     if( sqlite3IndexedByLookup(pParse, pFrom) ){
429585574e31Sdanielk1977       return WRC_Abort;
429685574e31Sdanielk1977     }
42977d10d5a6Sdrh   }
42987d10d5a6Sdrh 
42997d10d5a6Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
43007d10d5a6Sdrh   */
43017d10d5a6Sdrh   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
43027d10d5a6Sdrh     return WRC_Abort;
43037d10d5a6Sdrh   }
43047d10d5a6Sdrh 
43057d10d5a6Sdrh   /* For every "*" that occurs in the column list, insert the names of
43067d10d5a6Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
43077d10d5a6Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
43081a1d3cd2Sdrh   ** with the TK_ASTERISK operator for each "*" that it found in the column
43091a1d3cd2Sdrh   ** list.  The following code just has to locate the TK_ASTERISK
43101a1d3cd2Sdrh   ** expressions and expand each one to the list of all columns in
43111a1d3cd2Sdrh   ** all tables.
43127d10d5a6Sdrh   **
43137d10d5a6Sdrh   ** The first loop just checks to see if there are any "*" operators
43147d10d5a6Sdrh   ** that need expanding.
43157d10d5a6Sdrh   */
43167d10d5a6Sdrh   for(k=0; k<pEList->nExpr; k++){
43173e3f1a5bSdrh     pE = pEList->a[k].pExpr;
43181a1d3cd2Sdrh     if( pE->op==TK_ASTERISK ) break;
431943152cf8Sdrh     assert( pE->op!=TK_DOT || pE->pRight!=0 );
432043152cf8Sdrh     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
43211a1d3cd2Sdrh     if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
43227d10d5a6Sdrh   }
43237d10d5a6Sdrh   if( k<pEList->nExpr ){
43247d10d5a6Sdrh     /*
43257d10d5a6Sdrh     ** If we get here it means the result set contains one or more "*"
43267d10d5a6Sdrh     ** operators that need to be expanded.  Loop through each expression
43277d10d5a6Sdrh     ** in the result set and expand them one by one.
43287d10d5a6Sdrh     */
43297d10d5a6Sdrh     struct ExprList_item *a = pEList->a;
43307d10d5a6Sdrh     ExprList *pNew = 0;
43317d10d5a6Sdrh     int flags = pParse->db->flags;
43327d10d5a6Sdrh     int longNames = (flags & SQLITE_FullColNames)!=0
433338b384a0Sdrh                       && (flags & SQLITE_ShortColNames)==0;
433438b384a0Sdrh 
43357d10d5a6Sdrh     for(k=0; k<pEList->nExpr; k++){
43363e3f1a5bSdrh       pE = a[k].pExpr;
43373e3f1a5bSdrh       pRight = pE->pRight;
43383e3f1a5bSdrh       assert( pE->op!=TK_DOT || pRight!=0 );
43391a1d3cd2Sdrh       if( pE->op!=TK_ASTERISK
43401a1d3cd2Sdrh        && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
43411a1d3cd2Sdrh       ){
43427d10d5a6Sdrh         /* This particular expression does not need to be expanded.
43437d10d5a6Sdrh         */
4344b7916a78Sdrh         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
43457d10d5a6Sdrh         if( pNew ){
43467d10d5a6Sdrh           pNew->a[pNew->nExpr-1].zName = a[k].zName;
4347b7916a78Sdrh           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
4348b7916a78Sdrh           a[k].zName = 0;
4349b7916a78Sdrh           a[k].zSpan = 0;
43507d10d5a6Sdrh         }
43517d10d5a6Sdrh         a[k].pExpr = 0;
43527d10d5a6Sdrh       }else{
43537d10d5a6Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
43547d10d5a6Sdrh         ** expanded. */
43557d10d5a6Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
43563e3f1a5bSdrh         char *zTName = 0;       /* text of name of TABLE */
435743152cf8Sdrh         if( pE->op==TK_DOT ){
435843152cf8Sdrh           assert( pE->pLeft!=0 );
435933e619fcSdrh           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
436033e619fcSdrh           zTName = pE->pLeft->u.zToken;
43617d10d5a6Sdrh         }
43627d10d5a6Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
43637d10d5a6Sdrh           Table *pTab = pFrom->pTab;
43643e3f1a5bSdrh           Select *pSub = pFrom->pSelect;
43657d10d5a6Sdrh           char *zTabName = pFrom->zAlias;
43663e3f1a5bSdrh           const char *zSchemaName = 0;
4367c75e09c7Sdrh           int iDb;
436843152cf8Sdrh           if( zTabName==0 ){
43697d10d5a6Sdrh             zTabName = pTab->zName;
43707d10d5a6Sdrh           }
43717d10d5a6Sdrh           if( db->mallocFailed ) break;
43723e3f1a5bSdrh           if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
43733e3f1a5bSdrh             pSub = 0;
43747d10d5a6Sdrh             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
43757d10d5a6Sdrh               continue;
43767d10d5a6Sdrh             }
43773e3f1a5bSdrh             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
4378c75e09c7Sdrh             zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
43793e3f1a5bSdrh           }
43807d10d5a6Sdrh           for(j=0; j<pTab->nCol; j++){
43817d10d5a6Sdrh             char *zName = pTab->aCol[j].zName;
4382b7916a78Sdrh             char *zColname;  /* The computed column name */
4383b7916a78Sdrh             char *zToFree;   /* Malloced string that needs to be freed */
4384b7916a78Sdrh             Token sColname;  /* Computed column name as a token */
43857d10d5a6Sdrh 
4386c75e09c7Sdrh             assert( zName );
43873e3f1a5bSdrh             if( zTName && pSub
43883e3f1a5bSdrh              && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
43893e3f1a5bSdrh             ){
43903e3f1a5bSdrh               continue;
43913e3f1a5bSdrh             }
43923e3f1a5bSdrh 
439380090f92Sdrh             /* If a column is marked as 'hidden', omit it from the expanded
439480090f92Sdrh             ** result-set list unless the SELECT has the SF_IncludeHidden
439580090f92Sdrh             ** bit set.
43967d10d5a6Sdrh             */
439780090f92Sdrh             if( (p->selFlags & SF_IncludeHidden)==0
439880090f92Sdrh              && IsHiddenColumn(&pTab->aCol[j])
439980090f92Sdrh             ){
44007d10d5a6Sdrh               continue;
44017d10d5a6Sdrh             }
44023e3f1a5bSdrh             tableSeen = 1;
44037d10d5a6Sdrh 
4404da55c48aSdrh             if( i>0 && zTName==0 ){
44058a48b9c0Sdrh               if( (pFrom->fg.jointype & JT_NATURAL)!=0
44062179b434Sdrh                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
44072179b434Sdrh               ){
44087d10d5a6Sdrh                 /* In a NATURAL join, omit the join columns from the
44092179b434Sdrh                 ** table to the right of the join */
44107d10d5a6Sdrh                 continue;
44117d10d5a6Sdrh               }
44122179b434Sdrh               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
44137d10d5a6Sdrh                 /* In a join with a USING clause, omit columns in the
44147d10d5a6Sdrh                 ** using clause from the table on the right. */
44157d10d5a6Sdrh                 continue;
44167d10d5a6Sdrh               }
44177d10d5a6Sdrh             }
4418b7916a78Sdrh             pRight = sqlite3Expr(db, TK_ID, zName);
4419b7916a78Sdrh             zColname = zName;
4420b7916a78Sdrh             zToFree = 0;
44217d10d5a6Sdrh             if( longNames || pTabList->nSrc>1 ){
4422b7916a78Sdrh               Expr *pLeft;
4423b7916a78Sdrh               pLeft = sqlite3Expr(db, TK_ID, zTabName);
44247d10d5a6Sdrh               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
442538b384a0Sdrh               if( zSchemaName ){
4426c75e09c7Sdrh                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
4427c75e09c7Sdrh                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
4428c75e09c7Sdrh               }
4429b7916a78Sdrh               if( longNames ){
4430b7916a78Sdrh                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
4431b7916a78Sdrh                 zToFree = zColname;
4432b7916a78Sdrh               }
44337d10d5a6Sdrh             }else{
44347d10d5a6Sdrh               pExpr = pRight;
44357d10d5a6Sdrh             }
4436b7916a78Sdrh             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
4437b7916a78Sdrh             sColname.z = zColname;
4438b7916a78Sdrh             sColname.n = sqlite3Strlen30(zColname);
4439b7916a78Sdrh             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
44408f25d18bSdrh             if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
44413e3f1a5bSdrh               struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
44423e3f1a5bSdrh               if( pSub ){
44433e3f1a5bSdrh                 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
4444c75e09c7Sdrh                 testcase( pX->zSpan==0 );
44453e3f1a5bSdrh               }else{
44463e3f1a5bSdrh                 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
44473e3f1a5bSdrh                                            zSchemaName, zTabName, zColname);
4448c75e09c7Sdrh                 testcase( pX->zSpan==0 );
44493e3f1a5bSdrh               }
44503e3f1a5bSdrh               pX->bSpanIsTab = 1;
44518f25d18bSdrh             }
4452b7916a78Sdrh             sqlite3DbFree(db, zToFree);
44537d10d5a6Sdrh           }
44547d10d5a6Sdrh         }
44557d10d5a6Sdrh         if( !tableSeen ){
44567d10d5a6Sdrh           if( zTName ){
44577d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
44587d10d5a6Sdrh           }else{
44597d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no tables specified");
44607d10d5a6Sdrh           }
44617d10d5a6Sdrh         }
44627d10d5a6Sdrh       }
44637d10d5a6Sdrh     }
44647d10d5a6Sdrh     sqlite3ExprListDelete(db, pEList);
44657d10d5a6Sdrh     p->pEList = pNew;
44667d10d5a6Sdrh   }
44677d10d5a6Sdrh #if SQLITE_MAX_COLUMN
44687d10d5a6Sdrh   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
44697d10d5a6Sdrh     sqlite3ErrorMsg(pParse, "too many columns in result set");
44708836cbbcSdan     return WRC_Abort;
44717d10d5a6Sdrh   }
44727d10d5a6Sdrh #endif
44737d10d5a6Sdrh   return WRC_Continue;
44747d10d5a6Sdrh }
44757d10d5a6Sdrh 
44767d10d5a6Sdrh /*
44777d10d5a6Sdrh ** No-op routine for the parse-tree walker.
44787d10d5a6Sdrh **
44797d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees
44807d10d5a6Sdrh ** are walked without any actions being taken at each node.  Presumably,
44817d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then
44827d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every
44837d10d5a6Sdrh ** subquery in the parser tree.
44847d10d5a6Sdrh */
44855b88bc4bSdrh int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
448662c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
44877d10d5a6Sdrh   return WRC_Continue;
44887d10d5a6Sdrh }
44897d10d5a6Sdrh 
44907d10d5a6Sdrh /*
44917d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries.
44927d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT
44937d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above.
44947d10d5a6Sdrh **
44957d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a
44967d10d5a6Sdrh ** SELECT statement.  The SELECT statement must be expanded before
44977d10d5a6Sdrh ** name resolution is performed.
44987d10d5a6Sdrh **
44997d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse.
45007d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr
45017d10d5a6Sdrh ** and/or pParse->db->mallocFailed.
45027d10d5a6Sdrh */
45037d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
45047d10d5a6Sdrh   Walker w;
4505aa87f9a6Sdrh   memset(&w, 0, sizeof(w));
45065b88bc4bSdrh   w.xExprCallback = sqlite3ExprWalkNoop;
45077d10d5a6Sdrh   w.pParse = pParse;
4508d58d3278Sdrh   if( pParse->hasCompound ){
4509d58d3278Sdrh     w.xSelectCallback = convertCompoundSelectToSubquery;
45107d10d5a6Sdrh     sqlite3WalkSelect(&w, pSelect);
4511d58d3278Sdrh   }
4512c01b7306Sdrh   w.xSelectCallback = selectExpander;
4513772460fdSdrh   if( (pSelect->selFlags & SF_MultiValue)==0 ){
4514b290f117Sdan     w.xSelectCallback2 = selectPopWith;
45153afd2b4dSdrh   }
4516c01b7306Sdrh   sqlite3WalkSelect(&w, pSelect);
45177d10d5a6Sdrh }
45187d10d5a6Sdrh 
45197d10d5a6Sdrh 
45207d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
45217d10d5a6Sdrh /*
45227d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
45237d10d5a6Sdrh ** interface.
45247d10d5a6Sdrh **
45257d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl
45267d10d5a6Sdrh ** information to the Table structure that represents the result set
45277d10d5a6Sdrh ** of that subquery.
45287d10d5a6Sdrh **
45297d10d5a6Sdrh ** The Table structure that represents the result set was constructed
45307d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted
45317d10d5a6Sdrh ** at that point because identifiers had not yet been resolved.  This
45327d10d5a6Sdrh ** routine is called after identifier resolution.
45337d10d5a6Sdrh */
4534b290f117Sdan static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
45357d10d5a6Sdrh   Parse *pParse;
45367d10d5a6Sdrh   int i;
45377d10d5a6Sdrh   SrcList *pTabList;
45387d10d5a6Sdrh   struct SrcList_item *pFrom;
45397d10d5a6Sdrh 
45409d8b3072Sdrh   assert( p->selFlags & SF_Resolved );
4541e2b7d7a0Sdrh   assert( (p->selFlags & SF_HasTypeInfo)==0 );
45427d10d5a6Sdrh   p->selFlags |= SF_HasTypeInfo;
45437d10d5a6Sdrh   pParse = pWalker->pParse;
45447d10d5a6Sdrh   pTabList = p->pSrc;
45457d10d5a6Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
45467d10d5a6Sdrh     Table *pTab = pFrom->pTab;
4547e2b7d7a0Sdrh     assert( pTab!=0 );
4548e2b7d7a0Sdrh     if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
45497d10d5a6Sdrh       /* A sub-query in the FROM clause of a SELECT */
45507d10d5a6Sdrh       Select *pSel = pFrom->pSelect;
45518ce7184bSdan       if( pSel ){
45527d10d5a6Sdrh         while( pSel->pPrior ) pSel = pSel->pPrior;
4553186ad8ccSdrh         selectAddColumnTypeAndCollation(pParse, pTab, pSel);
45547d10d5a6Sdrh       }
45557d10d5a6Sdrh     }
45565a29d9cbSdrh   }
45578ce7184bSdan }
45587d10d5a6Sdrh #endif
45597d10d5a6Sdrh 
45607d10d5a6Sdrh 
45617d10d5a6Sdrh /*
45627d10d5a6Sdrh ** This routine adds datatype and collating sequence information to
45637d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a
45647d10d5a6Sdrh ** SELECT statement.
45657d10d5a6Sdrh **
45667d10d5a6Sdrh ** Use this routine after name resolution.
45677d10d5a6Sdrh */
45687d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
45697d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
45707d10d5a6Sdrh   Walker w;
4571aa87f9a6Sdrh   memset(&w, 0, sizeof(w));
4572b290f117Sdan   w.xSelectCallback2 = selectAddSubqueryTypeInfo;
45735b88bc4bSdrh   w.xExprCallback = sqlite3ExprWalkNoop;
45747d10d5a6Sdrh   w.pParse = pParse;
45757d10d5a6Sdrh   sqlite3WalkSelect(&w, pSelect);
45767d10d5a6Sdrh #endif
45777d10d5a6Sdrh }
45787d10d5a6Sdrh 
45797d10d5a6Sdrh 
45807d10d5a6Sdrh /*
4581030796dfSdrh ** This routine sets up a SELECT statement for processing.  The
45827d10d5a6Sdrh ** following is accomplished:
45837d10d5a6Sdrh **
45847d10d5a6Sdrh **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
45857d10d5a6Sdrh **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
45867d10d5a6Sdrh **     *  ON and USING clauses are shifted into WHERE statements
45877d10d5a6Sdrh **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
45887d10d5a6Sdrh **     *  Identifiers in expression are matched to tables.
45897d10d5a6Sdrh **
45907d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT.
45917d10d5a6Sdrh */
45927d10d5a6Sdrh void sqlite3SelectPrep(
4593b3bce662Sdanielk1977   Parse *pParse,         /* The parser context */
4594b3bce662Sdanielk1977   Select *p,             /* The SELECT statement being coded. */
45957d10d5a6Sdrh   NameContext *pOuterNC  /* Name context for container */
4596b3bce662Sdanielk1977 ){
45977d10d5a6Sdrh   sqlite3 *db;
459843152cf8Sdrh   if( NEVER(p==0) ) return;
45997d10d5a6Sdrh   db = pParse->db;
4600785097daSdrh   if( db->mallocFailed ) return;
46017d10d5a6Sdrh   if( p->selFlags & SF_HasTypeInfo ) return;
46027d10d5a6Sdrh   sqlite3SelectExpand(pParse, p);
46037d10d5a6Sdrh   if( pParse->nErr || db->mallocFailed ) return;
46047d10d5a6Sdrh   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
46057d10d5a6Sdrh   if( pParse->nErr || db->mallocFailed ) return;
46067d10d5a6Sdrh   sqlite3SelectAddTypeInfo(pParse, p);
4607f6bbe022Sdrh }
4608b3bce662Sdanielk1977 
4609b3bce662Sdanielk1977 /*
461013449892Sdrh ** Reset the aggregate accumulator.
461113449892Sdrh **
461213449892Sdrh ** The aggregate accumulator is a set of memory cells that hold
461313449892Sdrh ** intermediate results while calculating an aggregate.  This
4614030796dfSdrh ** routine generates code that stores NULLs in all of those memory
4615030796dfSdrh ** cells.
4616b3bce662Sdanielk1977 */
461713449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
461813449892Sdrh   Vdbe *v = pParse->pVdbe;
461913449892Sdrh   int i;
4620c99130fdSdrh   struct AggInfo_func *pFunc;
46217e61d18eSdrh   int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
46227e61d18eSdrh   if( nReg==0 ) return;
46237e61d18eSdrh #ifdef SQLITE_DEBUG
46247e61d18eSdrh   /* Verify that all AggInfo registers are within the range specified by
46257e61d18eSdrh   ** AggInfo.mnReg..AggInfo.mxReg */
46267e61d18eSdrh   assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
462713449892Sdrh   for(i=0; i<pAggInfo->nColumn; i++){
46287e61d18eSdrh     assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
46297e61d18eSdrh          && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
463013449892Sdrh   }
46317e61d18eSdrh   for(i=0; i<pAggInfo->nFunc; i++){
46327e61d18eSdrh     assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
46337e61d18eSdrh          && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
46347e61d18eSdrh   }
46357e61d18eSdrh #endif
46367e61d18eSdrh   sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
4637c99130fdSdrh   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
4638c99130fdSdrh     if( pFunc->iDistinct>=0 ){
4639c99130fdSdrh       Expr *pE = pFunc->pExpr;
46406ab3a2ecSdanielk1977       assert( !ExprHasProperty(pE, EP_xIsSelect) );
46416ab3a2ecSdanielk1977       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
46420daa002cSdrh         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
46430daa002cSdrh            "argument");
4644c99130fdSdrh         pFunc->iDistinct = -1;
4645c99130fdSdrh       }else{
4646079a3072Sdrh         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
464766a5167bSdrh         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
46482ec2fb22Sdrh                           (char*)pKeyInfo, P4_KEYINFO);
4649c99130fdSdrh       }
4650c99130fdSdrh     }
465113449892Sdrh   }
4652b3bce662Sdanielk1977 }
4653b3bce662Sdanielk1977 
4654b3bce662Sdanielk1977 /*
465513449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function
465613449892Sdrh ** in the AggInfo structure.
4657b3bce662Sdanielk1977 */
465813449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
465913449892Sdrh   Vdbe *v = pParse->pVdbe;
466013449892Sdrh   int i;
466113449892Sdrh   struct AggInfo_func *pF;
466213449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
46636ab3a2ecSdanielk1977     ExprList *pList = pF->pExpr->x.pList;
46646ab3a2ecSdanielk1977     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
466566a5167bSdrh     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
466666a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
4667b3bce662Sdanielk1977   }
466813449892Sdrh }
466913449892Sdrh 
467013449892Sdrh /*
467113449892Sdrh ** Update the accumulator memory cells for an aggregate based on
467213449892Sdrh ** the current cursor position.
467313449892Sdrh */
467413449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
467513449892Sdrh   Vdbe *v = pParse->pVdbe;
467613449892Sdrh   int i;
46777a95789cSdrh   int regHit = 0;
46787a95789cSdrh   int addrHitTest = 0;
467913449892Sdrh   struct AggInfo_func *pF;
468013449892Sdrh   struct AggInfo_col *pC;
468113449892Sdrh 
468213449892Sdrh   pAggInfo->directMode = 1;
468313449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
468413449892Sdrh     int nArg;
4685c99130fdSdrh     int addrNext = 0;
468698757157Sdrh     int regAgg;
46876ab3a2ecSdanielk1977     ExprList *pList = pF->pExpr->x.pList;
46886ab3a2ecSdanielk1977     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
468913449892Sdrh     if( pList ){
469013449892Sdrh       nArg = pList->nExpr;
4691892d3179Sdrh       regAgg = sqlite3GetTempRange(pParse, nArg);
46925579d59fSdrh       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
469313449892Sdrh     }else{
469413449892Sdrh       nArg = 0;
469598757157Sdrh       regAgg = 0;
469613449892Sdrh     }
4697c99130fdSdrh     if( pF->iDistinct>=0 ){
4698c99130fdSdrh       addrNext = sqlite3VdbeMakeLabel(v);
46997c052da5Sdrh       testcase( nArg==0 );  /* Error condition */
47007c052da5Sdrh       testcase( nArg>1 );   /* Also an error */
47012dcef11bSdrh       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
4702c99130fdSdrh     }
4703d36e1041Sdrh     if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
470413449892Sdrh       CollSeq *pColl = 0;
470513449892Sdrh       struct ExprList_item *pItem;
470613449892Sdrh       int j;
4707e82f5d04Sdrh       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
470843617e9aSdrh       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
470913449892Sdrh         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
471013449892Sdrh       }
471113449892Sdrh       if( !pColl ){
471213449892Sdrh         pColl = pParse->db->pDfltColl;
471313449892Sdrh       }
47147a95789cSdrh       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
47157a95789cSdrh       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
471613449892Sdrh     }
47179c7c913cSdrh     sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem,
471866a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
4719ea678832Sdrh     sqlite3VdbeChangeP5(v, (u8)nArg);
4720da250ea5Sdrh     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
4721f49f3523Sdrh     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
4722c99130fdSdrh     if( addrNext ){
4723c99130fdSdrh       sqlite3VdbeResolveLabel(v, addrNext);
4724ceea3321Sdrh       sqlite3ExprCacheClear(pParse);
4725c99130fdSdrh     }
472613449892Sdrh   }
472767a6a40cSdan 
472867a6a40cSdan   /* Before populating the accumulator registers, clear the column cache.
472967a6a40cSdan   ** Otherwise, if any of the required column values are already present
473067a6a40cSdan   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
473167a6a40cSdan   ** to pC->iMem. But by the time the value is used, the original register
473267a6a40cSdan   ** may have been used, invalidating the underlying buffer holding the
473367a6a40cSdan   ** text or blob value. See ticket [883034dcb5].
473467a6a40cSdan   **
473567a6a40cSdan   ** Another solution would be to change the OP_SCopy used to copy cached
473667a6a40cSdan   ** values to an OP_Copy.
473767a6a40cSdan   */
47387a95789cSdrh   if( regHit ){
4739688852abSdrh     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
47407a95789cSdrh   }
474167a6a40cSdan   sqlite3ExprCacheClear(pParse);
474213449892Sdrh   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
4743389a1adbSdrh     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
474413449892Sdrh   }
474513449892Sdrh   pAggInfo->directMode = 0;
4746ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
47477a95789cSdrh   if( addrHitTest ){
47487a95789cSdrh     sqlite3VdbeJumpHere(v, addrHitTest);
47497a95789cSdrh   }
475013449892Sdrh }
475113449892Sdrh 
4752b3bce662Sdanielk1977 /*
4753ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple
4754ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab").
4755ef7075deSdan */
4756ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN
4757ef7075deSdan static void explainSimpleCount(
4758ef7075deSdan   Parse *pParse,                  /* Parse context */
4759ef7075deSdan   Table *pTab,                    /* Table being queried */
4760ef7075deSdan   Index *pIdx                     /* Index used to optimize scan, or NULL */
4761ef7075deSdan ){
4762ef7075deSdan   if( pParse->explain==2 ){
476348dd1d8eSdrh     int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
47648a4380d7Sdrh     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
4765ef7075deSdan         pTab->zName,
4766e96f2df3Sdan         bCover ? " USING COVERING INDEX " : "",
4767e96f2df3Sdan         bCover ? pIdx->zName : ""
4768ef7075deSdan     );
4769ef7075deSdan     sqlite3VdbeAddOp4(
4770ef7075deSdan         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
4771ef7075deSdan     );
4772ef7075deSdan   }
4773ef7075deSdan }
4774ef7075deSdan #else
4775ef7075deSdan # define explainSimpleCount(a,b,c)
4776ef7075deSdan #endif
4777ef7075deSdan 
4778ef7075deSdan /*
47797d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument.
47809bb61fe7Sdrh **
4781340309fdSdrh ** The results are returned according to the SelectDest structure.
4782340309fdSdrh ** See comments in sqliteInt.h for further information.
4783e78e8284Sdrh **
47849bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
47859bb61fe7Sdrh ** encountered, then an appropriate error message is left in
47869bb61fe7Sdrh ** pParse->zErrMsg.
47879bb61fe7Sdrh **
47889bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
47899bb61fe7Sdrh ** calling function needs to do that.
47909bb61fe7Sdrh */
47914adee20fSdanielk1977 int sqlite3Select(
4792cce7d176Sdrh   Parse *pParse,         /* The parser context */
47939bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
47947d10d5a6Sdrh   SelectDest *pDest      /* What to do with the query results */
4795cce7d176Sdrh ){
479613449892Sdrh   int i, j;              /* Loop counters */
479713449892Sdrh   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
479813449892Sdrh   Vdbe *v;               /* The virtual machine under construction */
4799b3bce662Sdanielk1977   int isAgg;             /* True for select lists like "count(*)" */
4800c29cbb0bSmistachkin   ExprList *pEList = 0;  /* List of columns to extract. */
4801ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
48029bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
48032282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
48042282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
48051d83f052Sdrh   int rc = 1;            /* Value to return from this function */
4806e8e4af76Sdrh   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
4807079a3072Sdrh   SortCtx sSort;         /* Info on how to code the ORDER BY clause */
480813449892Sdrh   AggInfo sAggInfo;      /* Information used by aggregate queries */
4809ec7429aeSdrh   int iEnd;              /* Address of the end of the query */
481017435752Sdrh   sqlite3 *db;           /* The database connection */
48119bb61fe7Sdrh 
48122ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN
48132ce22453Sdan   int iRestoreSelectId = pParse->iSelectId;
48142ce22453Sdan   pParse->iSelectId = pParse->iNextSelectId++;
48152ce22453Sdan #endif
48162ce22453Sdan 
481717435752Sdrh   db = pParse->db;
481817435752Sdrh   if( p==0 || db->mallocFailed || pParse->nErr ){
48196f7adc8aSdrh     return 1;
48206f7adc8aSdrh   }
48214adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
482213449892Sdrh   memset(&sAggInfo, 0, sizeof(sAggInfo));
4823eb9b884cSdrh #if SELECTTRACE_ENABLED
4824eb9b884cSdrh   pParse->nSelectIndent++;
4825c90713d3Sdrh   SELECTTRACE(1,pParse,p, ("begin processing:\n"));
4826c90713d3Sdrh   if( sqlite3SelectTrace & 0x100 ){
4827c90713d3Sdrh     sqlite3TreeViewSelect(0, p, 0);
4828c90713d3Sdrh   }
4829eb9b884cSdrh #endif
4830daffd0e5Sdrh 
48318e1ee88cSdrh   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
48328e1ee88cSdrh   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
48339afccba2Sdan   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
48349afccba2Sdan   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
48356c8c8ce0Sdanielk1977   if( IgnorableOrderby(pDest) ){
48369ed1dfa8Sdanielk1977     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
48379afccba2Sdan            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
48388e1ee88cSdrh            pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
48398e1ee88cSdrh            pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
4840ccfcbceaSdrh     /* If ORDER BY makes no difference in the output then neither does
4841ccfcbceaSdrh     ** DISTINCT so it can be removed too. */
4842ccfcbceaSdrh     sqlite3ExprListDelete(db, p->pOrderBy);
4843ccfcbceaSdrh     p->pOrderBy = 0;
48447d10d5a6Sdrh     p->selFlags &= ~SF_Distinct;
48459a99334dSdrh   }
48467d10d5a6Sdrh   sqlite3SelectPrep(pParse, p, 0);
4847079a3072Sdrh   memset(&sSort, 0, sizeof(sSort));
4848079a3072Sdrh   sSort.pOrderBy = p->pOrderBy;
4849b27b7f5dSdrh   pTabList = p->pSrc;
4850956f4319Sdanielk1977   if( pParse->nErr || db->mallocFailed ){
48519a99334dSdrh     goto select_end;
48529a99334dSdrh   }
4853adc57f68Sdrh   assert( p->pEList!=0 );
48547d10d5a6Sdrh   isAgg = (p->selFlags & SF_Aggregate)!=0;
485517645f5eSdrh #if SELECTTRACE_ENABLED
485617645f5eSdrh   if( sqlite3SelectTrace & 0x100 ){
485717645f5eSdrh     SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
485817645f5eSdrh     sqlite3TreeViewSelect(0, p, 0);
485917645f5eSdrh   }
486017645f5eSdrh #endif
4861cce7d176Sdrh 
4862d820cb1bSdrh 
486374b617b2Sdan   /* If writing to memory or generating a set
486474b617b2Sdan   ** only a single column may be output.
486574b617b2Sdan   */
486674b617b2Sdan #ifndef SQLITE_OMIT_SUBQUERY
4867adc57f68Sdrh   if( checkForMultiColumnSelectError(pParse, pDest, p->pEList->nExpr) ){
486874b617b2Sdan     goto select_end;
486974b617b2Sdan   }
487074b617b2Sdan #endif
487174b617b2Sdan 
4872adc57f68Sdrh   /* Try to flatten subqueries in the FROM clause up into the main query
4873d820cb1bSdrh   */
487451522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4875f23329a2Sdanielk1977   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
487613449892Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
4877daf79acbSdanielk1977     Select *pSub = pItem->pSelect;
4878f23329a2Sdanielk1977     int isAggSub;
48792679f14fSdrh     Table *pTab = pItem->pTab;
48804490c40bSdrh     if( pSub==0 ) continue;
48812679f14fSdrh 
48822679f14fSdrh     /* Catch mismatch in the declared columns of a view and the number of
48832679f14fSdrh     ** columns in the SELECT on the RHS */
48842679f14fSdrh     if( pTab->nCol!=pSub->pEList->nExpr ){
48852679f14fSdrh       sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
48862679f14fSdrh                       pTab->nCol, pTab->zName, pSub->pEList->nExpr);
48872679f14fSdrh       goto select_end;
48882679f14fSdrh     }
48892679f14fSdrh 
48904490c40bSdrh     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
48914490c40bSdrh     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
48924490c40bSdrh       /* This subquery can be absorbed into its parent. */
48934490c40bSdrh       if( isAggSub ){
48944490c40bSdrh         isAgg = 1;
48954490c40bSdrh         p->selFlags |= SF_Aggregate;
48964490c40bSdrh       }
48974490c40bSdrh       i = -1;
48984490c40bSdrh     }
48994490c40bSdrh     pTabList = p->pSrc;
49004490c40bSdrh     if( db->mallocFailed ) goto select_end;
49014490c40bSdrh     if( !IgnorableOrderby(pDest) ){
49024490c40bSdrh       sSort.pOrderBy = p->pOrderBy;
49034490c40bSdrh     }
49044490c40bSdrh   }
49054490c40bSdrh #endif
49064490c40bSdrh 
4907adc57f68Sdrh   /* Get a pointer the VDBE under construction, allocating a new VDBE if one
4908adc57f68Sdrh   ** does not already exist */
4909adc57f68Sdrh   v = sqlite3GetVdbe(pParse);
4910adc57f68Sdrh   if( v==0 ) goto select_end;
49114490c40bSdrh 
49124490c40bSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
49134490c40bSdrh   /* Handle compound SELECT statements using the separate multiSelect()
49144490c40bSdrh   ** procedure.
49154490c40bSdrh   */
49164490c40bSdrh   if( p->pPrior ){
49174490c40bSdrh     rc = multiSelect(pParse, p, pDest);
49184490c40bSdrh     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
49194490c40bSdrh #if SELECTTRACE_ENABLED
49204490c40bSdrh     SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
49214490c40bSdrh     pParse->nSelectIndent--;
49224490c40bSdrh #endif
49234490c40bSdrh     return rc;
49244490c40bSdrh   }
49254490c40bSdrh #endif
49264490c40bSdrh 
49276e17529eSdrh   /* Generate code for all sub-queries in the FROM clause
49286e17529eSdrh   */
49296e17529eSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
49304490c40bSdrh   for(i=0; i<pTabList->nSrc; i++){
4931ad3cab52Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
49325cf590c1Sdrh     SelectDest dest;
4933c31c2eb8Sdrh     Select *pSub = pItem->pSelect;
49345b6a9ed4Sdrh     if( pSub==0 ) continue;
493521172c4cSdrh 
493621172c4cSdrh     /* Sometimes the code for a subquery will be generated more than
493721172c4cSdrh     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
493821172c4cSdrh     ** for example.  In that case, do not regenerate the code to manifest
493921172c4cSdrh     ** a view or the co-routine to implement a view.  The first instance
494021172c4cSdrh     ** is sufficient, though the subroutine to manifest the view does need
494121172c4cSdrh     ** to be invoked again. */
49425b6a9ed4Sdrh     if( pItem->addrFillSub ){
49438a48b9c0Sdrh       if( pItem->fg.viaCoroutine==0 ){
49445b6a9ed4Sdrh         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
494521172c4cSdrh       }
49465b6a9ed4Sdrh       continue;
49475b6a9ed4Sdrh     }
4948daf79acbSdanielk1977 
4949fc976065Sdanielk1977     /* Increment Parse.nHeight by the height of the largest expression
4950f7b5496eSdrh     ** tree referred to by this, the parent select. The child select
4951fc976065Sdanielk1977     ** may contain expression trees of at most
4952fc976065Sdanielk1977     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
4953fc976065Sdanielk1977     ** more conservative than necessary, but much easier than enforcing
4954fc976065Sdanielk1977     ** an exact limit.
4955fc976065Sdanielk1977     */
4956fc976065Sdanielk1977     pParse->nHeight += sqlite3SelectExprHeight(p);
4957daf79acbSdanielk1977 
4958adc57f68Sdrh     /* Make copies of constant WHERE-clause terms in the outer query down
4959adc57f68Sdrh     ** inside the subquery.  This can help the subquery to run more efficiently.
4960adc57f68Sdrh     */
49618a48b9c0Sdrh     if( (pItem->fg.jointype & JT_OUTER)==0
496269b72d5aSdrh      && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor)
496369b72d5aSdrh     ){
496469b72d5aSdrh #if SELECTTRACE_ENABLED
496569b72d5aSdrh       if( sqlite3SelectTrace & 0x100 ){
4966bc8edba1Sdrh         SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
496769b72d5aSdrh         sqlite3TreeViewSelect(0, p, 0);
4968daf79acbSdanielk1977       }
496969b72d5aSdrh #endif
497069b72d5aSdrh     }
4971adc57f68Sdrh 
4972adc57f68Sdrh     /* Generate code to implement the subquery
4973adc57f68Sdrh     */
497469b72d5aSdrh     if( pTabList->nSrc==1
49757cea7f95Sdrh      && (p->selFlags & SF_All)==0
4976a5759677Sdrh      && OptimizationEnabled(db, SQLITE_SubqCoroutine)
4977a5759677Sdrh     ){
497821172c4cSdrh       /* Implement a co-routine that will return a single row of the result
497921172c4cSdrh       ** set on each invocation.
498021172c4cSdrh       */
4981725de29aSdrh       int addrTop = sqlite3VdbeCurrentAddr(v)+1;
498221172c4cSdrh       pItem->regReturn = ++pParse->nMem;
4983725de29aSdrh       sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
4984725de29aSdrh       VdbeComment((v, "%s", pItem->pTab->zName));
498521172c4cSdrh       pItem->addrFillSub = addrTop;
498621172c4cSdrh       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
498721172c4cSdrh       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
498821172c4cSdrh       sqlite3Select(pParse, pSub, &dest);
4989cfc9df76Sdan       pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
49908a48b9c0Sdrh       pItem->fg.viaCoroutine = 1;
49915f612295Sdrh       pItem->regResult = dest.iSdst;
499281cf13ecSdrh       sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
499321172c4cSdrh       sqlite3VdbeJumpHere(v, addrTop-1);
499421172c4cSdrh       sqlite3ClearTempRegCache(pParse);
4995daf79acbSdanielk1977     }else{
49965b6a9ed4Sdrh       /* Generate a subroutine that will fill an ephemeral table with
49975b6a9ed4Sdrh       ** the content of this subquery.  pItem->addrFillSub will point
49985b6a9ed4Sdrh       ** to the address of the generated subroutine.  pItem->regReturn
49995b6a9ed4Sdrh       ** is a register allocated to hold the subroutine return address
50005b6a9ed4Sdrh       */
50017157e8eaSdrh       int topAddr;
500248f2d3b1Sdrh       int onceAddr = 0;
50037157e8eaSdrh       int retAddr;
50045b6a9ed4Sdrh       assert( pItem->addrFillSub==0 );
50055b6a9ed4Sdrh       pItem->regReturn = ++pParse->nMem;
50067157e8eaSdrh       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
50077157e8eaSdrh       pItem->addrFillSub = topAddr+1;
50088a48b9c0Sdrh       if( pItem->fg.isCorrelated==0 ){
5009ed17167eSdrh         /* If the subquery is not correlated and if we are not inside of
50105b6a9ed4Sdrh         ** a trigger, then we only need to compute the value of the subquery
50115b6a9ed4Sdrh         ** once. */
50127d176105Sdrh         onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
5013725de29aSdrh         VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
5014725de29aSdrh       }else{
5015725de29aSdrh         VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
50165b6a9ed4Sdrh       }
50171013c932Sdrh       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
5018ce7e189dSdan       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
50197d10d5a6Sdrh       sqlite3Select(pParse, pSub, &dest);
5020cfc9df76Sdan       pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
502148f2d3b1Sdrh       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
50227157e8eaSdrh       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
50237157e8eaSdrh       VdbeComment((v, "end %s", pItem->pTab->zName));
50247157e8eaSdrh       sqlite3VdbeChangeP1(v, topAddr, retAddr);
5025cdc69557Sdrh       sqlite3ClearTempRegCache(pParse);
5026daf79acbSdanielk1977     }
5027adc57f68Sdrh     if( db->mallocFailed ) goto select_end;
5028fc976065Sdanielk1977     pParse->nHeight -= sqlite3SelectExprHeight(p);
5029acd4c695Sdrh   }
5030daf79acbSdanielk1977 #endif
5031adc57f68Sdrh 
503238b4149cSdrh   /* Various elements of the SELECT copied into local variables for
503338b4149cSdrh   ** convenience */
5034adc57f68Sdrh   pEList = p->pEList;
5035daf79acbSdanielk1977   pWhere = p->pWhere;
5036832508b7Sdrh   pGroupBy = p->pGroupBy;
5037832508b7Sdrh   pHaving = p->pHaving;
5038e8e4af76Sdrh   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
5039832508b7Sdrh 
5040bc8edba1Sdrh #if SELECTTRACE_ENABLED
5041bc8edba1Sdrh   if( sqlite3SelectTrace & 0x400 ){
5042bc8edba1Sdrh     SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
5043bc8edba1Sdrh     sqlite3TreeViewSelect(0, p, 0);
5044f23329a2Sdanielk1977   }
5045f23329a2Sdanielk1977 #endif
5046f23329a2Sdanielk1977 
504750118cdfSdan   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
504850118cdfSdan   ** if the select-list is the same as the ORDER BY list, then this query
504950118cdfSdan   ** can be rewritten as a GROUP BY. In other words, this:
505050118cdfSdan   **
505150118cdfSdan   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
505250118cdfSdan   **
505350118cdfSdan   ** is transformed to:
505450118cdfSdan   **
5055dea7d70dSdrh   **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
505650118cdfSdan   **
505750118cdfSdan   ** The second form is preferred as a single index (or temp-table) may be
505850118cdfSdan   ** used for both the ORDER BY and DISTINCT processing. As originally
505950118cdfSdan   ** written the query must use a temp-table for at least one of the ORDER
506050118cdfSdan   ** BY and DISTINCT, and an index or separate temp-table for the other.
506150118cdfSdan   */
506250118cdfSdan   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
5063adc57f68Sdrh    && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
506450118cdfSdan   ){
506550118cdfSdan     p->selFlags &= ~SF_Distinct;
5066adc57f68Sdrh     pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
5067e8e4af76Sdrh     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
5068e8e4af76Sdrh     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
5069e8e4af76Sdrh     ** original setting of the SF_Distinct flag, not the current setting */
5070e8e4af76Sdrh     assert( sDistinct.isTnct );
507150118cdfSdan   }
507250118cdfSdan 
5073adc57f68Sdrh   /* If there is an ORDER BY clause, then create an ephemeral index to
5074adc57f68Sdrh   ** do the sorting.  But this sorting ephemeral index might end up
5075adc57f68Sdrh   ** being unused if the data can be extracted in pre-sorted order.
5076adc57f68Sdrh   ** If that is the case, then the OP_OpenEphemeral instruction will be
5077adc57f68Sdrh   ** changed to an OP_Noop once we figure out that the sorting index is
5078adc57f68Sdrh   ** not needed.  The sSort.addrSortIndex variable is used to facilitate
5079adc57f68Sdrh   ** that change.
50807cedc8d4Sdanielk1977   */
5081079a3072Sdrh   if( sSort.pOrderBy ){
50820342b1f5Sdrh     KeyInfo *pKeyInfo;
50833f39bcf5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
5084079a3072Sdrh     sSort.iECursor = pParse->nTab++;
5085079a3072Sdrh     sSort.addrSortIndex =
508666a5167bSdrh       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
5087f45f2326Sdrh           sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
5088f45f2326Sdrh           (char*)pKeyInfo, P4_KEYINFO
5089f45f2326Sdrh       );
50909d2985c7Sdrh   }else{
5091079a3072Sdrh     sSort.addrSortIndex = -1;
50927cedc8d4Sdanielk1977   }
50937cedc8d4Sdanielk1977 
50942d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
50952d0794e3Sdrh   */
50966c8c8ce0Sdanielk1977   if( pDest->eDest==SRT_EphemTab ){
50972b596da8Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
50982d0794e3Sdrh   }
50992d0794e3Sdrh 
5100f42bacc2Sdrh   /* Set the limiter.
5101f42bacc2Sdrh   */
5102f42bacc2Sdrh   iEnd = sqlite3VdbeMakeLabel(v);
5103c63367efSdrh   p->nSelectRow = LARGEST_INT64;
5104f42bacc2Sdrh   computeLimitRegisters(pParse, p, iEnd);
5105079a3072Sdrh   if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
51060ff287fbSdrh     sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
5107079a3072Sdrh     sSort.sortFlags |= SORTFLAG_UseSorter;
5108c6aff30cSdrh   }
5109f42bacc2Sdrh 
5110adc57f68Sdrh   /* Open an ephemeral index to use for the distinct set.
5111cce7d176Sdrh   */
51122ce22453Sdan   if( p->selFlags & SF_Distinct ){
5113e8e4af76Sdrh     sDistinct.tabTnct = pParse->nTab++;
5114e8e4af76Sdrh     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
5115e8e4af76Sdrh                              sDistinct.tabTnct, 0, 0,
5116079a3072Sdrh                              (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
51172ec2fb22Sdrh                              P4_KEYINFO);
5118d4187c71Sdrh     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
5119e8e4af76Sdrh     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
5120832508b7Sdrh   }else{
5121e8e4af76Sdrh     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
5122efb7251dSdrh   }
5123832508b7Sdrh 
512413449892Sdrh   if( !isAgg && pGroupBy==0 ){
5125e8e4af76Sdrh     /* No aggregate functions and no GROUP BY clause */
51266457a353Sdrh     u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
512738cc40c2Sdan 
512838cc40c2Sdan     /* Begin the database scan. */
5129079a3072Sdrh     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
5130079a3072Sdrh                                p->pEList, wctrlFlags, 0);
51311d83f052Sdrh     if( pWInfo==0 ) goto select_end;
51326f32848dSdrh     if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
51336f32848dSdrh       p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
51346f32848dSdrh     }
51356457a353Sdrh     if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
51366f32848dSdrh       sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
51376f32848dSdrh     }
5138079a3072Sdrh     if( sSort.pOrderBy ){
5139079a3072Sdrh       sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
5140079a3072Sdrh       if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
5141079a3072Sdrh         sSort.pOrderBy = 0;
5142079a3072Sdrh       }
5143079a3072Sdrh     }
5144cce7d176Sdrh 
5145b9bb7c18Sdrh     /* If sorting index that was created by a prior OP_OpenEphemeral
5146b9bb7c18Sdrh     ** instruction ended up not being needed, then change the OP_OpenEphemeral
51479d2985c7Sdrh     ** into an OP_Noop.
51489d2985c7Sdrh     */
5149079a3072Sdrh     if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
5150079a3072Sdrh       sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
51519d2985c7Sdrh     }
51529d2985c7Sdrh 
515338cc40c2Sdan     /* Use the standard inner loop. */
5154079a3072Sdrh     selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
51556f32848dSdrh                     sqlite3WhereContinueLabel(pWInfo),
51566f32848dSdrh                     sqlite3WhereBreakLabel(pWInfo));
51572282792aSdrh 
5158cce7d176Sdrh     /* End the database scan loop.
5159cce7d176Sdrh     */
51604adee20fSdanielk1977     sqlite3WhereEnd(pWInfo);
516113449892Sdrh   }else{
5162e8e4af76Sdrh     /* This case when there exist aggregate functions or a GROUP BY clause
5163e8e4af76Sdrh     ** or both */
516413449892Sdrh     NameContext sNC;    /* Name context for processing aggregate information */
516513449892Sdrh     int iAMem;          /* First Mem address for storing current GROUP BY */
516613449892Sdrh     int iBMem;          /* First Mem address for previous GROUP BY */
516713449892Sdrh     int iUseFlag;       /* Mem address holding flag indicating that at least
516813449892Sdrh                         ** one row of the input to the aggregator has been
516913449892Sdrh                         ** processed */
517013449892Sdrh     int iAbortFlag;     /* Mem address which causes query abort if positive */
517113449892Sdrh     int groupBySort;    /* Rows come from source in GROUP BY order */
5172d176611bSdrh     int addrEnd;        /* End of processing for this SELECT */
51731c9d835dSdrh     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
51741c9d835dSdrh     int sortOut = 0;    /* Output register from the sorter */
5175374cd78cSdan     int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
5176d176611bSdrh 
5177d176611bSdrh     /* Remove any and all aliases between the result set and the
5178d176611bSdrh     ** GROUP BY clause.
5179d176611bSdrh     */
5180d176611bSdrh     if( pGroupBy ){
5181dc5ea5c7Sdrh       int k;                        /* Loop counter */
5182d176611bSdrh       struct ExprList_item *pItem;  /* For looping over expression in a list */
5183d176611bSdrh 
5184dc5ea5c7Sdrh       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
5185c2acc4e4Sdrh         pItem->u.x.iAlias = 0;
5186d176611bSdrh       }
5187dc5ea5c7Sdrh       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
5188c2acc4e4Sdrh         pItem->u.x.iAlias = 0;
5189d176611bSdrh       }
5190c63367efSdrh       if( p->nSelectRow>100 ) p->nSelectRow = 100;
519195aa47b1Sdrh     }else{
5192c63367efSdrh       p->nSelectRow = 1;
5193d176611bSdrh     }
5194cce7d176Sdrh 
5195374cd78cSdan     /* If there is both a GROUP BY and an ORDER BY clause and they are
5196374cd78cSdan     ** identical, then it may be possible to disable the ORDER BY clause
5197374cd78cSdan     ** on the grounds that the GROUP BY will cause elements to come out
5198adc57f68Sdrh     ** in the correct order. It also may not - the GROUP BY might use a
5199374cd78cSdan     ** database index that causes rows to be grouped together as required
5200374cd78cSdan     ** but not actually sorted. Either way, record the fact that the
5201374cd78cSdan     ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
5202374cd78cSdan     ** variable.  */
5203374cd78cSdan     if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
5204374cd78cSdan       orderByGrp = 1;
5205374cd78cSdan     }
520613449892Sdrh 
5207d176611bSdrh     /* Create a label to jump to when we want to abort the query */
520813449892Sdrh     addrEnd = sqlite3VdbeMakeLabel(v);
520913449892Sdrh 
521013449892Sdrh     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
521113449892Sdrh     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
521213449892Sdrh     ** SELECT statement.
52132282792aSdrh     */
521413449892Sdrh     memset(&sNC, 0, sizeof(sNC));
521513449892Sdrh     sNC.pParse = pParse;
521613449892Sdrh     sNC.pSrcList = pTabList;
521713449892Sdrh     sNC.pAggInfo = &sAggInfo;
52187e61d18eSdrh     sAggInfo.mnReg = pParse->nMem+1;
5219dd23c6bfSdan     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
52209d2985c7Sdrh     sAggInfo.pGroupBy = pGroupBy;
5221d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pEList);
5222079a3072Sdrh     sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
5223d2b3e23bSdrh     if( pHaving ){
5224d2b3e23bSdrh       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
522513449892Sdrh     }
522613449892Sdrh     sAggInfo.nAccumulator = sAggInfo.nColumn;
522713449892Sdrh     for(i=0; i<sAggInfo.nFunc; i++){
52286ab3a2ecSdanielk1977       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
52293a8c4be7Sdrh       sNC.ncFlags |= NC_InAggFunc;
52306ab3a2ecSdanielk1977       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
52313a8c4be7Sdrh       sNC.ncFlags &= ~NC_InAggFunc;
523213449892Sdrh     }
52337e61d18eSdrh     sAggInfo.mxReg = pParse->nMem;
523417435752Sdrh     if( db->mallocFailed ) goto select_end;
523513449892Sdrh 
523613449892Sdrh     /* Processing for aggregates with GROUP BY is very different and
52373c4809a2Sdanielk1977     ** much more complex than aggregates without a GROUP BY.
523813449892Sdrh     */
523913449892Sdrh     if( pGroupBy ){
524013449892Sdrh       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
5241728e0f91Sdrh       int addr1;          /* A-vs-B comparision jump */
5242d176611bSdrh       int addrOutputRow;  /* Start of subroutine that outputs a result row */
5243d176611bSdrh       int regOutputRow;   /* Return address register for output subroutine */
5244d176611bSdrh       int addrSetAbort;   /* Set the abort flag and return */
5245d176611bSdrh       int addrTopOfLoop;  /* Top of the input loop */
5246d176611bSdrh       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
5247d176611bSdrh       int addrReset;      /* Subroutine for resetting the accumulator */
5248d176611bSdrh       int regReset;       /* Return address register for reset subroutine */
524913449892Sdrh 
525013449892Sdrh       /* If there is a GROUP BY clause we might need a sorting index to
525113449892Sdrh       ** implement it.  Allocate that sorting index now.  If it turns out
52521c9d835dSdrh       ** that we do not need it after all, the OP_SorterOpen instruction
525313449892Sdrh       ** will be converted into a Noop.
525413449892Sdrh       */
525513449892Sdrh       sAggInfo.sortingIdx = pParse->nTab++;
52563f39bcf5Sdrh       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
52571c9d835dSdrh       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
5258cd3e8f7cSdanielk1977           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
52592ec2fb22Sdrh           0, (char*)pKeyInfo, P4_KEYINFO);
526013449892Sdrh 
526113449892Sdrh       /* Initialize memory locations used by GROUP BY aggregate processing
526213449892Sdrh       */
52630a07c107Sdrh       iUseFlag = ++pParse->nMem;
52640a07c107Sdrh       iAbortFlag = ++pParse->nMem;
5265d176611bSdrh       regOutputRow = ++pParse->nMem;
5266d176611bSdrh       addrOutputRow = sqlite3VdbeMakeLabel(v);
5267d176611bSdrh       regReset = ++pParse->nMem;
5268d176611bSdrh       addrReset = sqlite3VdbeMakeLabel(v);
52690a07c107Sdrh       iAMem = pParse->nMem + 1;
527013449892Sdrh       pParse->nMem += pGroupBy->nExpr;
52710a07c107Sdrh       iBMem = pParse->nMem + 1;
527213449892Sdrh       pParse->nMem += pGroupBy->nExpr;
52734c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
5274d4e70ebdSdrh       VdbeComment((v, "clear abort flag"));
52754c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
5276d4e70ebdSdrh       VdbeComment((v, "indicate accumulator empty"));
5277b8475df8Sdrh       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
5278e313382eSdrh 
527913449892Sdrh       /* Begin a loop that will extract all source rows in GROUP BY order.
528013449892Sdrh       ** This might involve two separate loops with an OP_Sort in between, or
528113449892Sdrh       ** it might be a single loop that uses an index to extract information
528213449892Sdrh       ** in the right order to begin with.
528313449892Sdrh       */
52842eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
528593ec45d5Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
5286374cd78cSdan           WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
5287374cd78cSdan       );
52885360ad34Sdrh       if( pWInfo==0 ) goto select_end;
5289ddba0c22Sdrh       if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
529013449892Sdrh         /* The optimizer is able to deliver rows in group by order so
5291b9bb7c18Sdrh         ** we do not have to sort.  The OP_OpenEphemeral table will be
529213449892Sdrh         ** cancelled later because we still need to use the pKeyInfo
529313449892Sdrh         */
529413449892Sdrh         groupBySort = 0;
529513449892Sdrh       }else{
529613449892Sdrh         /* Rows are coming out in undetermined order.  We have to push
529713449892Sdrh         ** each row into a sorting index, terminate the first loop,
529813449892Sdrh         ** then loop over the sorting index in order to get the output
529913449892Sdrh         ** in sorted order
530013449892Sdrh         */
5301892d3179Sdrh         int regBase;
5302892d3179Sdrh         int regRecord;
5303892d3179Sdrh         int nCol;
5304892d3179Sdrh         int nGroupBy;
5305892d3179Sdrh 
53062ce22453Sdan         explainTempTable(pParse,
5307e8e4af76Sdrh             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
5308e8e4af76Sdrh                     "DISTINCT" : "GROUP BY");
53092ce22453Sdan 
531013449892Sdrh         groupBySort = 1;
5311892d3179Sdrh         nGroupBy = pGroupBy->nExpr;
5312dd23c6bfSdan         nCol = nGroupBy;
5313dd23c6bfSdan         j = nGroupBy;
531413449892Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
5315892d3179Sdrh           if( sAggInfo.aCol[i].iSorterColumn>=j ){
5316892d3179Sdrh             nCol++;
531713449892Sdrh             j++;
531813449892Sdrh           }
5319892d3179Sdrh         }
5320892d3179Sdrh         regBase = sqlite3GetTempRange(pParse, nCol);
5321ceea3321Sdrh         sqlite3ExprCacheClear(pParse);
53225579d59fSdrh         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
5323dd23c6bfSdan         j = nGroupBy;
5324892d3179Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
5325892d3179Sdrh           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
5326892d3179Sdrh           if( pCol->iSorterColumn>=j ){
5327e55cbd72Sdrh             int r1 = j + regBase;
5328ce78bc6eSdrh             sqlite3ExprCodeGetColumnToReg(pParse,
5329ce78bc6eSdrh                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
53306a012f04Sdrh             j++;
5331892d3179Sdrh           }
5332892d3179Sdrh         }
5333892d3179Sdrh         regRecord = sqlite3GetTempReg(pParse);
53341db639ceSdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
53351c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
5336892d3179Sdrh         sqlite3ReleaseTempReg(pParse, regRecord);
5337892d3179Sdrh         sqlite3ReleaseTempRange(pParse, regBase, nCol);
533813449892Sdrh         sqlite3WhereEnd(pWInfo);
53395134d135Sdan         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
53401c9d835dSdrh         sortOut = sqlite3GetTempReg(pParse);
53411c9d835dSdrh         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
53421c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
5343688852abSdrh         VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
534413449892Sdrh         sAggInfo.useSortingIdx = 1;
5345ceea3321Sdrh         sqlite3ExprCacheClear(pParse);
5346374cd78cSdan 
5347374cd78cSdan       }
5348374cd78cSdan 
5349374cd78cSdan       /* If the index or temporary table used by the GROUP BY sort
5350374cd78cSdan       ** will naturally deliver rows in the order required by the ORDER BY
5351374cd78cSdan       ** clause, cancel the ephemeral table open coded earlier.
5352374cd78cSdan       **
5353374cd78cSdan       ** This is an optimization - the correct answer should result regardless.
5354374cd78cSdan       ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
5355374cd78cSdan       ** disable this optimization for testing purposes.  */
5356374cd78cSdan       if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
5357374cd78cSdan        && (groupBySort || sqlite3WhereIsSorted(pWInfo))
5358374cd78cSdan       ){
5359374cd78cSdan         sSort.pOrderBy = 0;
5360374cd78cSdan         sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
536113449892Sdrh       }
536213449892Sdrh 
536313449892Sdrh       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
536413449892Sdrh       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
536513449892Sdrh       ** Then compare the current GROUP BY terms against the GROUP BY terms
536613449892Sdrh       ** from the previous row currently stored in a0, a1, a2...
536713449892Sdrh       */
536813449892Sdrh       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
5369ceea3321Sdrh       sqlite3ExprCacheClear(pParse);
53701c9d835dSdrh       if( groupBySort ){
537138b4149cSdrh         sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
537238b4149cSdrh                           sortOut, sortPTab);
53731c9d835dSdrh       }
537413449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
537513449892Sdrh         if( groupBySort ){
53761c9d835dSdrh           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
537713449892Sdrh         }else{
537813449892Sdrh           sAggInfo.directMode = 1;
53792dcef11bSdrh           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
538013449892Sdrh         }
538113449892Sdrh       }
538216ee60ffSdrh       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
53832ec2fb22Sdrh                           (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
5384728e0f91Sdrh       addr1 = sqlite3VdbeCurrentAddr(v);
5385728e0f91Sdrh       sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
538613449892Sdrh 
538713449892Sdrh       /* Generate code that runs whenever the GROUP BY changes.
5388e00ee6ebSdrh       ** Changes in the GROUP BY are detected by the previous code
538913449892Sdrh       ** block.  If there were no changes, this block is skipped.
539013449892Sdrh       **
539113449892Sdrh       ** This code copies current group by terms in b0,b1,b2,...
539213449892Sdrh       ** over to a0,a1,a2.  It then calls the output subroutine
539313449892Sdrh       ** and resets the aggregate accumulator registers in preparation
539413449892Sdrh       ** for the next GROUP BY batch.
539513449892Sdrh       */
5396b21e7c70Sdrh       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
53972eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
5398d4e70ebdSdrh       VdbeComment((v, "output one row"));
5399688852abSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
5400d4e70ebdSdrh       VdbeComment((v, "check abort flag"));
54012eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
5402d4e70ebdSdrh       VdbeComment((v, "reset accumulator"));
540313449892Sdrh 
540413449892Sdrh       /* Update the aggregate accumulators based on the content of
540513449892Sdrh       ** the current row
540613449892Sdrh       */
5407728e0f91Sdrh       sqlite3VdbeJumpHere(v, addr1);
540813449892Sdrh       updateAccumulator(pParse, &sAggInfo);
54094c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
5410d4e70ebdSdrh       VdbeComment((v, "indicate data in accumulator"));
541113449892Sdrh 
541213449892Sdrh       /* End of the loop
541313449892Sdrh       */
541413449892Sdrh       if( groupBySort ){
54151c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
5416688852abSdrh         VdbeCoverage(v);
541713449892Sdrh       }else{
541813449892Sdrh         sqlite3WhereEnd(pWInfo);
541948f2d3b1Sdrh         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
542013449892Sdrh       }
542113449892Sdrh 
542213449892Sdrh       /* Output the final row of result
542313449892Sdrh       */
54242eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
5425d4e70ebdSdrh       VdbeComment((v, "output final row"));
542613449892Sdrh 
5427d176611bSdrh       /* Jump over the subroutines
5428d176611bSdrh       */
5429076e85f5Sdrh       sqlite3VdbeGoto(v, addrEnd);
5430d176611bSdrh 
5431d176611bSdrh       /* Generate a subroutine that outputs a single row of the result
5432d176611bSdrh       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
5433d176611bSdrh       ** is less than or equal to zero, the subroutine is a no-op.  If
5434d176611bSdrh       ** the processing calls for the query to abort, this subroutine
5435d176611bSdrh       ** increments the iAbortFlag memory location before returning in
5436d176611bSdrh       ** order to signal the caller to abort.
5437d176611bSdrh       */
5438d176611bSdrh       addrSetAbort = sqlite3VdbeCurrentAddr(v);
5439d176611bSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
5440d176611bSdrh       VdbeComment((v, "set abort flag"));
5441d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5442d176611bSdrh       sqlite3VdbeResolveLabel(v, addrOutputRow);
5443d176611bSdrh       addrOutputRow = sqlite3VdbeCurrentAddr(v);
5444d176611bSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
544538b4149cSdrh       VdbeCoverage(v);
5446d176611bSdrh       VdbeComment((v, "Groupby result generator entry point"));
5447d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5448d176611bSdrh       finalizeAggFunctions(pParse, &sAggInfo);
5449d176611bSdrh       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
5450079a3072Sdrh       selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
5451e8e4af76Sdrh                       &sDistinct, pDest,
5452d176611bSdrh                       addrOutputRow+1, addrSetAbort);
5453d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5454d176611bSdrh       VdbeComment((v, "end groupby result generator"));
5455d176611bSdrh 
5456d176611bSdrh       /* Generate a subroutine that will reset the group-by accumulator
5457d176611bSdrh       */
5458d176611bSdrh       sqlite3VdbeResolveLabel(v, addrReset);
5459d176611bSdrh       resetAccumulator(pParse, &sAggInfo);
5460d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regReset);
5461d176611bSdrh 
546243152cf8Sdrh     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
546313449892Sdrh     else {
5464dba0137eSdanielk1977       ExprList *pDel = 0;
5465a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT
5466a5533162Sdanielk1977       Table *pTab;
5467a5533162Sdanielk1977       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
5468a5533162Sdanielk1977         /* If isSimpleCount() returns a pointer to a Table structure, then
5469a5533162Sdanielk1977         ** the SQL statement is of the form:
5470a5533162Sdanielk1977         **
5471a5533162Sdanielk1977         **   SELECT count(*) FROM <tbl>
5472a5533162Sdanielk1977         **
5473a5533162Sdanielk1977         ** where the Table structure returned represents table <tbl>.
5474a5533162Sdanielk1977         **
5475a5533162Sdanielk1977         ** This statement is so common that it is optimized specially. The
5476a5533162Sdanielk1977         ** OP_Count instruction is executed either on the intkey table that
5477a5533162Sdanielk1977         ** contains the data for table <tbl> or on one of its indexes. It
5478a5533162Sdanielk1977         ** is better to execute the op on an index, as indexes are almost
5479a5533162Sdanielk1977         ** always spread across less pages than their corresponding tables.
5480a5533162Sdanielk1977         */
5481a5533162Sdanielk1977         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
5482a5533162Sdanielk1977         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
5483a5533162Sdanielk1977         Index *pIdx;                         /* Iterator variable */
5484a5533162Sdanielk1977         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
5485a5533162Sdanielk1977         Index *pBest = 0;                    /* Best index found so far */
5486a5533162Sdanielk1977         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
5487a9d1ccb9Sdanielk1977 
5488a5533162Sdanielk1977         sqlite3CodeVerifySchema(pParse, iDb);
5489a5533162Sdanielk1977         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
5490a5533162Sdanielk1977 
5491d9e3cad2Sdrh         /* Search for the index that has the lowest scan cost.
5492a5533162Sdanielk1977         **
54933e9548b3Sdrh         ** (2011-04-15) Do not do a full scan of an unordered index.
54943e9548b3Sdrh         **
5495abcc1941Sdrh         ** (2013-10-03) Do not count the entries in a partial index.
54965f33f375Sdrh         **
5497a5533162Sdanielk1977         ** In practice the KeyInfo structure will not be used. It is only
5498a5533162Sdanielk1977         ** passed to keep OP_OpenRead happy.
5499a5533162Sdanielk1977         */
55005c7917e4Sdrh         if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
5501a5533162Sdanielk1977         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
5502d9e3cad2Sdrh           if( pIdx->bUnordered==0
5503e13e9f54Sdrh            && pIdx->szIdxRow<pTab->szTabRow
5504d3037a41Sdrh            && pIdx->pPartIdxWhere==0
5505e13e9f54Sdrh            && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
5506d9e3cad2Sdrh           ){
5507a5533162Sdanielk1977             pBest = pIdx;
5508a5533162Sdanielk1977           }
5509a5533162Sdanielk1977         }
5510d9e3cad2Sdrh         if( pBest ){
5511a5533162Sdanielk1977           iRoot = pBest->tnum;
55122ec2fb22Sdrh           pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
5513a5533162Sdanielk1977         }
5514a5533162Sdanielk1977 
5515a5533162Sdanielk1977         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
5516261c02d9Sdrh         sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
5517a5533162Sdanielk1977         if( pKeyInfo ){
55182ec2fb22Sdrh           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
5519a5533162Sdanielk1977         }
5520a5533162Sdanielk1977         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
5521a5533162Sdanielk1977         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
5522ef7075deSdan         explainSimpleCount(pParse, pTab, pBest);
5523a5533162Sdanielk1977       }else
5524a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */
5525a5533162Sdanielk1977       {
5526738bdcfbSdanielk1977         /* Check if the query is of one of the following forms:
5527738bdcfbSdanielk1977         **
5528738bdcfbSdanielk1977         **   SELECT min(x) FROM ...
5529738bdcfbSdanielk1977         **   SELECT max(x) FROM ...
5530738bdcfbSdanielk1977         **
5531738bdcfbSdanielk1977         ** If it is, then ask the code in where.c to attempt to sort results
5532738bdcfbSdanielk1977         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
5533738bdcfbSdanielk1977         ** If where.c is able to produce results sorted in this order, then
5534738bdcfbSdanielk1977         ** add vdbe code to break out of the processing loop after the
5535738bdcfbSdanielk1977         ** first iteration (since the first iteration of the loop is
5536738bdcfbSdanielk1977         ** guaranteed to operate on the row with the minimum or maximum
5537738bdcfbSdanielk1977         ** value of x, the only row required).
5538738bdcfbSdanielk1977         **
5539738bdcfbSdanielk1977         ** A special flag must be passed to sqlite3WhereBegin() to slightly
554048864df9Smistachkin         ** modify behavior as follows:
5541738bdcfbSdanielk1977         **
5542738bdcfbSdanielk1977         **   + If the query is a "SELECT min(x)", then the loop coded by
5543738bdcfbSdanielk1977         **     where.c should not iterate over any values with a NULL value
5544738bdcfbSdanielk1977         **     for x.
5545738bdcfbSdanielk1977         **
5546738bdcfbSdanielk1977         **   + The optimizer code in where.c (the thing that decides which
5547738bdcfbSdanielk1977         **     index or indices to use) should place a different priority on
5548738bdcfbSdanielk1977         **     satisfying the 'ORDER BY' clause than it does in other cases.
5549738bdcfbSdanielk1977         **     Refer to code and comments in where.c for details.
5550738bdcfbSdanielk1977         */
5551a5533162Sdanielk1977         ExprList *pMinMax = 0;
55524ac391fcSdan         u8 flag = WHERE_ORDERBY_NORMAL;
55534ac391fcSdan 
55544ac391fcSdan         assert( p->pGroupBy==0 );
55554ac391fcSdan         assert( flag==0 );
55564ac391fcSdan         if( p->pHaving==0 ){
55574ac391fcSdan           flag = minMaxQuery(&sAggInfo, &pMinMax);
55584ac391fcSdan         }
55594ac391fcSdan         assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
55604ac391fcSdan 
5561a9d1ccb9Sdanielk1977         if( flag ){
55624ac391fcSdan           pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
55636ab3a2ecSdanielk1977           pDel = pMinMax;
55640e359b30Sdrh           if( pMinMax && !db->mallocFailed ){
5565ea678832Sdrh             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
5566a9d1ccb9Sdanielk1977             pMinMax->a[0].pExpr->op = TK_COLUMN;
5567a9d1ccb9Sdanielk1977           }
55681013c932Sdrh         }
5569a9d1ccb9Sdanielk1977 
557013449892Sdrh         /* This case runs if the aggregate has no GROUP BY clause.  The
557113449892Sdrh         ** processing is much simpler since there is only a single row
557213449892Sdrh         ** of output.
557313449892Sdrh         */
557413449892Sdrh         resetAccumulator(pParse, &sAggInfo);
557546ec5b63Sdrh         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
5576dba0137eSdanielk1977         if( pWInfo==0 ){
5577633e6d57Sdrh           sqlite3ExprListDelete(db, pDel);
5578dba0137eSdanielk1977           goto select_end;
5579dba0137eSdanielk1977         }
558013449892Sdrh         updateAccumulator(pParse, &sAggInfo);
558146c35f9bSdrh         assert( pMinMax==0 || pMinMax->nExpr==1 );
5582ddba0c22Sdrh         if( sqlite3WhereIsOrdered(pWInfo)>0 ){
5583076e85f5Sdrh           sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
5584a5533162Sdanielk1977           VdbeComment((v, "%s() by index",
5585a5533162Sdanielk1977                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
5586a9d1ccb9Sdanielk1977         }
558713449892Sdrh         sqlite3WhereEnd(pWInfo);
558813449892Sdrh         finalizeAggFunctions(pParse, &sAggInfo);
55897a895a80Sdanielk1977       }
55907a895a80Sdanielk1977 
5591079a3072Sdrh       sSort.pOrderBy = 0;
559235573356Sdrh       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
5593079a3072Sdrh       selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
5594a9671a22Sdrh                       pDest, addrEnd, addrEnd);
5595633e6d57Sdrh       sqlite3ExprListDelete(db, pDel);
559613449892Sdrh     }
559713449892Sdrh     sqlite3VdbeResolveLabel(v, addrEnd);
559813449892Sdrh 
559913449892Sdrh   } /* endif aggregate query */
56002282792aSdrh 
5601e8e4af76Sdrh   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
56022ce22453Sdan     explainTempTable(pParse, "DISTINCT");
56032ce22453Sdan   }
56042ce22453Sdan 
5605cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
5606cce7d176Sdrh   ** and send them to the callback one by one.
5607cce7d176Sdrh   */
5608079a3072Sdrh   if( sSort.pOrderBy ){
560938b4149cSdrh     explainTempTable(pParse,
561038b4149cSdrh                      sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
5611079a3072Sdrh     generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
5612cce7d176Sdrh   }
56136a535340Sdrh 
5614ec7429aeSdrh   /* Jump here to skip this query
5615ec7429aeSdrh   */
5616ec7429aeSdrh   sqlite3VdbeResolveLabel(v, iEnd);
5617ec7429aeSdrh 
56185b1c07e7Sdan   /* The SELECT has been coded. If there is an error in the Parse structure,
56195b1c07e7Sdan   ** set the return code to 1. Otherwise 0. */
56205b1c07e7Sdan   rc = (pParse->nErr>0);
56211d83f052Sdrh 
56221d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
56231d83f052Sdrh   ** successful coding of the SELECT.
56241d83f052Sdrh   */
56251d83f052Sdrh select_end:
562617c0bc0cSdan   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
5627955de52cSdanielk1977 
56287d10d5a6Sdrh   /* Identify column names if results of the SELECT are to be output.
5629955de52cSdanielk1977   */
56307d10d5a6Sdrh   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
5631955de52cSdanielk1977     generateColumnNames(pParse, pTabList, pEList);
5632955de52cSdanielk1977   }
5633955de52cSdanielk1977 
5634633e6d57Sdrh   sqlite3DbFree(db, sAggInfo.aCol);
5635633e6d57Sdrh   sqlite3DbFree(db, sAggInfo.aFunc);
5636eb9b884cSdrh #if SELECTTRACE_ENABLED
5637eb9b884cSdrh   SELECTTRACE(1,pParse,p,("end processing\n"));
5638eb9b884cSdrh   pParse->nSelectIndent--;
5639eb9b884cSdrh #endif
56401d83f052Sdrh   return rc;
5641cce7d176Sdrh }
5642