xref: /sqlite-3.40.0/src/select.c (revision a536df4e)
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 */
57a04a8be2Sdrh   int labelDone;        /* Jump here when done, ex: LIMIT reached */
58079a3072Sdrh   u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
59*a536df4eSdrh   u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */
60079a3072Sdrh };
61079a3072Sdrh #define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
62cce7d176Sdrh 
63cce7d176Sdrh /*
64b87fbed5Sdrh ** Delete all the content of a Select structure.  Deallocate the structure
65b87fbed5Sdrh ** itself only if bFree is true.
66eda639e1Sdrh */
67b87fbed5Sdrh static void clearSelect(sqlite3 *db, Select *p, int bFree){
68b87fbed5Sdrh   while( p ){
69b87fbed5Sdrh     Select *pPrior = p->pPrior;
70633e6d57Sdrh     sqlite3ExprListDelete(db, p->pEList);
71633e6d57Sdrh     sqlite3SrcListDelete(db, p->pSrc);
72633e6d57Sdrh     sqlite3ExprDelete(db, p->pWhere);
73633e6d57Sdrh     sqlite3ExprListDelete(db, p->pGroupBy);
74633e6d57Sdrh     sqlite3ExprDelete(db, p->pHaving);
75633e6d57Sdrh     sqlite3ExprListDelete(db, p->pOrderBy);
76633e6d57Sdrh     sqlite3ExprDelete(db, p->pLimit);
77633e6d57Sdrh     sqlite3ExprDelete(db, p->pOffset);
78f3c57ff5Sdrh     if( p->pWith ) sqlite3WithDelete(db, p->pWith);
79b87fbed5Sdrh     if( bFree ) sqlite3DbFree(db, p);
80b87fbed5Sdrh     p = pPrior;
81b87fbed5Sdrh     bFree = 1;
82b87fbed5Sdrh   }
83eda639e1Sdrh }
84eda639e1Sdrh 
851013c932Sdrh /*
861013c932Sdrh ** Initialize a SelectDest structure.
871013c932Sdrh */
881013c932Sdrh void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
89ea678832Sdrh   pDest->eDest = (u8)eDest;
902b596da8Sdrh   pDest->iSDParm = iParm;
912b596da8Sdrh   pDest->affSdst = 0;
922b596da8Sdrh   pDest->iSdst = 0;
932b596da8Sdrh   pDest->nSdst = 0;
941013c932Sdrh }
951013c932Sdrh 
96eda639e1Sdrh 
97eda639e1Sdrh /*
989bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that
999bb61fe7Sdrh ** structure.
100cce7d176Sdrh */
1014adee20fSdanielk1977 Select *sqlite3SelectNew(
10217435752Sdrh   Parse *pParse,        /* Parsing context */
103daffd0e5Sdrh   ExprList *pEList,     /* which columns to include in the result */
104ad3cab52Sdrh   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
105daffd0e5Sdrh   Expr *pWhere,         /* the WHERE clause */
106daffd0e5Sdrh   ExprList *pGroupBy,   /* the GROUP BY clause */
107daffd0e5Sdrh   Expr *pHaving,        /* the HAVING clause */
108daffd0e5Sdrh   ExprList *pOrderBy,   /* the ORDER BY clause */
109c3489bbfSdrh   u32 selFlags,         /* Flag parameters, such as SF_Distinct */
110a2dc3b1aSdanielk1977   Expr *pLimit,         /* LIMIT value.  NULL means not used */
111a2dc3b1aSdanielk1977   Expr *pOffset         /* OFFSET value.  NULL means no offset */
1129bb61fe7Sdrh ){
1139bb61fe7Sdrh   Select *pNew;
114eda639e1Sdrh   Select standin;
11517435752Sdrh   sqlite3 *db = pParse->db;
116575fad65Sdrh   pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
117daffd0e5Sdrh   if( pNew==0 ){
118338ec3e1Sdrh     assert( db->mallocFailed );
119eda639e1Sdrh     pNew = &standin;
120eda639e1Sdrh   }
121b733d037Sdrh   if( pEList==0 ){
1221a1d3cd2Sdrh     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ASTERISK,0));
123b733d037Sdrh   }
1249bb61fe7Sdrh   pNew->pEList = pEList;
125ca3862dcSdrh   pNew->op = TK_SELECT;
126ca3862dcSdrh   pNew->selFlags = selFlags;
127ca3862dcSdrh   pNew->iLimit = 0;
128ca3862dcSdrh   pNew->iOffset = 0;
1299ca33fa4Sdrh #if SELECTTRACE_ENABLED
1309ca33fa4Sdrh   pNew->zSelName[0] = 0;
1319ca33fa4Sdrh #endif
132ca3862dcSdrh   pNew->addrOpenEphm[0] = -1;
133ca3862dcSdrh   pNew->addrOpenEphm[1] = -1;
134ca3862dcSdrh   pNew->nSelectRow = 0;
1357b113babSdrh   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
1369bb61fe7Sdrh   pNew->pSrc = pSrc;
1379bb61fe7Sdrh   pNew->pWhere = pWhere;
1389bb61fe7Sdrh   pNew->pGroupBy = pGroupBy;
1399bb61fe7Sdrh   pNew->pHaving = pHaving;
1409bb61fe7Sdrh   pNew->pOrderBy = pOrderBy;
141ca3862dcSdrh   pNew->pPrior = 0;
142ca3862dcSdrh   pNew->pNext = 0;
143a2dc3b1aSdanielk1977   pNew->pLimit = pLimit;
144a2dc3b1aSdanielk1977   pNew->pOffset = pOffset;
145ca3862dcSdrh   pNew->pWith = 0;
146b8289a8bSdrh   assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
1470a846f96Sdrh   if( db->mallocFailed ) {
148b87fbed5Sdrh     clearSelect(db, pNew, pNew!=&standin);
149eda639e1Sdrh     pNew = 0;
150a464c234Sdrh   }else{
151a464c234Sdrh     assert( pNew->pSrc!=0 || pParse->nErr>0 );
152daffd0e5Sdrh   }
153338ec3e1Sdrh   assert( pNew!=&standin );
1549bb61fe7Sdrh   return pNew;
1559bb61fe7Sdrh }
1569bb61fe7Sdrh 
157eb9b884cSdrh #if SELECTTRACE_ENABLED
158eb9b884cSdrh /*
159eb9b884cSdrh ** Set the name of a Select object
160eb9b884cSdrh */
161eb9b884cSdrh void sqlite3SelectSetName(Select *p, const char *zName){
162eb9b884cSdrh   if( p && zName ){
163eb9b884cSdrh     sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
164eb9b884cSdrh   }
165eb9b884cSdrh }
166eb9b884cSdrh #endif
167eb9b884cSdrh 
168eb9b884cSdrh 
1699bb61fe7Sdrh /*
170eda639e1Sdrh ** Delete the given Select structure and all of its substructures.
171eda639e1Sdrh */
172633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){
173f3c57ff5Sdrh   if( p ) clearSelect(db, p, 1);
174eda639e1Sdrh }
175eda639e1Sdrh 
176eda639e1Sdrh /*
177d227a291Sdrh ** Return a pointer to the right-most SELECT statement in a compound.
178d227a291Sdrh */
179d227a291Sdrh static Select *findRightmost(Select *p){
180d227a291Sdrh   while( p->pNext ) p = p->pNext;
181d227a291Sdrh   return p;
1829bb61fe7Sdrh }
1839bb61fe7Sdrh 
1849bb61fe7Sdrh /*
185f7b5496eSdrh ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
18601f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
18701f3f253Sdrh ** in terms of the following bit values:
18801f3f253Sdrh **
18901f3f253Sdrh **     JT_INNER
1903dec223cSdrh **     JT_CROSS
19101f3f253Sdrh **     JT_OUTER
19201f3f253Sdrh **     JT_NATURAL
19301f3f253Sdrh **     JT_LEFT
19401f3f253Sdrh **     JT_RIGHT
19501f3f253Sdrh **
19601f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
19701f3f253Sdrh **
19801f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
19901f3f253Sdrh ** a join type, but put an error in the pParse structure.
20001f3f253Sdrh */
2014adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
20201f3f253Sdrh   int jointype = 0;
20301f3f253Sdrh   Token *apAll[3];
20401f3f253Sdrh   Token *p;
205373cc2ddSdrh                              /*   0123456789 123456789 123456789 123 */
206373cc2ddSdrh   static const char zKeyText[] = "naturaleftouterightfullinnercross";
2075719628aSdrh   static const struct {
208373cc2ddSdrh     u8 i;        /* Beginning of keyword text in zKeyText[] */
209373cc2ddSdrh     u8 nChar;    /* Length of the keyword in characters */
210373cc2ddSdrh     u8 code;     /* Join type mask */
211373cc2ddSdrh   } aKeyword[] = {
212373cc2ddSdrh     /* natural */ { 0,  7, JT_NATURAL                },
213373cc2ddSdrh     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
214373cc2ddSdrh     /* outer   */ { 10, 5, JT_OUTER                  },
215373cc2ddSdrh     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
216373cc2ddSdrh     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
217373cc2ddSdrh     /* inner   */ { 23, 5, JT_INNER                  },
218373cc2ddSdrh     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
21901f3f253Sdrh   };
22001f3f253Sdrh   int i, j;
22101f3f253Sdrh   apAll[0] = pA;
22201f3f253Sdrh   apAll[1] = pB;
22301f3f253Sdrh   apAll[2] = pC;
224195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
22501f3f253Sdrh     p = apAll[i];
226373cc2ddSdrh     for(j=0; j<ArraySize(aKeyword); j++){
227373cc2ddSdrh       if( p->n==aKeyword[j].nChar
228373cc2ddSdrh           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
229373cc2ddSdrh         jointype |= aKeyword[j].code;
23001f3f253Sdrh         break;
23101f3f253Sdrh       }
23201f3f253Sdrh     }
233373cc2ddSdrh     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
234373cc2ddSdrh     if( j>=ArraySize(aKeyword) ){
23501f3f253Sdrh       jointype |= JT_ERROR;
23601f3f253Sdrh       break;
23701f3f253Sdrh     }
23801f3f253Sdrh   }
239ad2d8307Sdrh   if(
240ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
241195e6967Sdrh      (jointype & JT_ERROR)!=0
242ad2d8307Sdrh   ){
243a9671a22Sdrh     const char *zSp = " ";
244a9671a22Sdrh     assert( pB!=0 );
245a9671a22Sdrh     if( pC==0 ){ zSp++; }
246ae29ffbeSdrh     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
247a9671a22Sdrh        "%T %T%s%T", pA, pB, zSp, pC);
24801f3f253Sdrh     jointype = JT_INNER;
249373cc2ddSdrh   }else if( (jointype & JT_OUTER)!=0
250373cc2ddSdrh          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
2514adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
252da93d238Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported");
253195e6967Sdrh     jointype = JT_INNER;
25401f3f253Sdrh   }
25501f3f253Sdrh   return jointype;
25601f3f253Sdrh }
25701f3f253Sdrh 
25801f3f253Sdrh /*
259ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
260ad2d8307Sdrh ** is not contained in the table.
261ad2d8307Sdrh */
262ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
263ad2d8307Sdrh   int i;
264ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
2654adee20fSdanielk1977     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
266ad2d8307Sdrh   }
267ad2d8307Sdrh   return -1;
268ad2d8307Sdrh }
269ad2d8307Sdrh 
270ad2d8307Sdrh /*
2712179b434Sdrh ** Search the first N tables in pSrc, from left to right, looking for a
2722179b434Sdrh ** table that has a column named zCol.
2732179b434Sdrh **
2742179b434Sdrh ** When found, set *piTab and *piCol to the table index and column index
2752179b434Sdrh ** of the matching column and return TRUE.
2762179b434Sdrh **
2772179b434Sdrh ** If not found, return FALSE.
2782179b434Sdrh */
2792179b434Sdrh static int tableAndColumnIndex(
2802179b434Sdrh   SrcList *pSrc,       /* Array of tables to search */
2812179b434Sdrh   int N,               /* Number of tables in pSrc->a[] to search */
2822179b434Sdrh   const char *zCol,    /* Name of the column we are looking for */
2832179b434Sdrh   int *piTab,          /* Write index of pSrc->a[] here */
2842179b434Sdrh   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
2852179b434Sdrh ){
2862179b434Sdrh   int i;               /* For looping over tables in pSrc */
2872179b434Sdrh   int iCol;            /* Index of column matching zCol */
2882179b434Sdrh 
2892179b434Sdrh   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
2902179b434Sdrh   for(i=0; i<N; i++){
2912179b434Sdrh     iCol = columnIndex(pSrc->a[i].pTab, zCol);
2922179b434Sdrh     if( iCol>=0 ){
2932179b434Sdrh       if( piTab ){
2942179b434Sdrh         *piTab = i;
2952179b434Sdrh         *piCol = iCol;
2962179b434Sdrh       }
2972179b434Sdrh       return 1;
2982179b434Sdrh     }
2992179b434Sdrh   }
3002179b434Sdrh   return 0;
3012179b434Sdrh }
3022179b434Sdrh 
3032179b434Sdrh /*
304f7b0b0adSdan ** This function is used to add terms implied by JOIN syntax to the
305f7b0b0adSdan ** WHERE clause expression of a SELECT statement. The new term, which
306f7b0b0adSdan ** is ANDed with the existing WHERE clause, is of the form:
307f7b0b0adSdan **
308f7b0b0adSdan **    (tab1.col1 = tab2.col2)
309f7b0b0adSdan **
310f7b0b0adSdan ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
311f7b0b0adSdan ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
312f7b0b0adSdan ** column iColRight of tab2.
313ad2d8307Sdrh */
314ad2d8307Sdrh static void addWhereTerm(
31517435752Sdrh   Parse *pParse,                  /* Parsing context */
316f7b0b0adSdan   SrcList *pSrc,                  /* List of tables in FROM clause */
3172179b434Sdrh   int iLeft,                      /* Index of first table to join in pSrc */
318f7b0b0adSdan   int iColLeft,                   /* Index of column in first table */
3192179b434Sdrh   int iRight,                     /* Index of second table in pSrc */
320f7b0b0adSdan   int iColRight,                  /* Index of column in second table */
321f7b0b0adSdan   int isOuterJoin,                /* True if this is an OUTER join */
322f7b0b0adSdan   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
323ad2d8307Sdrh ){
324f7b0b0adSdan   sqlite3 *db = pParse->db;
325f7b0b0adSdan   Expr *pE1;
326f7b0b0adSdan   Expr *pE2;
327f7b0b0adSdan   Expr *pEq;
328ad2d8307Sdrh 
3292179b434Sdrh   assert( iLeft<iRight );
3302179b434Sdrh   assert( pSrc->nSrc>iRight );
3312179b434Sdrh   assert( pSrc->a[iLeft].pTab );
3322179b434Sdrh   assert( pSrc->a[iRight].pTab );
333f7b0b0adSdan 
3342179b434Sdrh   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
3352179b434Sdrh   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
336f7b0b0adSdan 
337f7b0b0adSdan   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
338f7b0b0adSdan   if( pEq && isOuterJoin ){
339f7b0b0adSdan     ExprSetProperty(pEq, EP_FromJoin);
340c5cd1249Sdrh     assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
341ebb6a65dSdrh     ExprSetVVAProperty(pEq, EP_NoReduce);
342f7b0b0adSdan     pEq->iRightJoinTable = (i16)pE2->iTable;
343030530deSdrh   }
344f7b0b0adSdan   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
345ad2d8307Sdrh }
346ad2d8307Sdrh 
347ad2d8307Sdrh /*
3481f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
34922d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the
35022d6a53aSdrh ** expression.
3511cc093c2Sdrh **
352e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
3531cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
3541f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
3551f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
3561f16230bSdrh ** WHERE clause during join processing but we need to remember that they
3571f16230bSdrh ** originated in the ON or USING clause.
35822d6a53aSdrh **
35922d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the
36022d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not
36122d6a53aSdrh ** explicitly mentioned in the expression.  That information is needed
36222d6a53aSdrh ** for cases like this:
36322d6a53aSdrh **
36422d6a53aSdrh **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
36522d6a53aSdrh **
36622d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5
36722d6a53aSdrh ** term until after the t2 loop of the join.  In that way, a
36822d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
36922d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately
37022d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in
37122d6a53aSdrh ** the output, which is incorrect.
3721cc093c2Sdrh */
37322d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){
3741cc093c2Sdrh   while( p ){
3751f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
376c5cd1249Sdrh     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
377ebb6a65dSdrh     ExprSetVVAProperty(p, EP_NoReduce);
378cf697396Sshane     p->iRightJoinTable = (i16)iTable;
379606f2344Sdrh     if( p->op==TK_FUNCTION && p->x.pList ){
380606f2344Sdrh       int i;
381606f2344Sdrh       for(i=0; i<p->x.pList->nExpr; i++){
382606f2344Sdrh         setJoinExpr(p->x.pList->a[i].pExpr, iTable);
383606f2344Sdrh       }
384606f2344Sdrh     }
38522d6a53aSdrh     setJoinExpr(p->pLeft, iTable);
3861cc093c2Sdrh     p = p->pRight;
3871cc093c2Sdrh   }
3881cc093c2Sdrh }
3891cc093c2Sdrh 
3901cc093c2Sdrh /*
391ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
392ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
393ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
394ad2d8307Sdrh **
39591bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure.
39691bb0eedSdrh ** The left most table is the first entry in Select.pSrc.  The right-most
39791bb0eedSdrh ** table is the last entry.  The join operator is held in the entry to
39891bb0eedSdrh ** the left.  Thus entry 0 contains the join operator for the join between
39991bb0eedSdrh ** entries 0 and 1.  Any ON or USING clauses associated with the join are
40091bb0eedSdrh ** also attached to the left entry.
40191bb0eedSdrh **
402ad2d8307Sdrh ** This routine returns the number of errors encountered.
403ad2d8307Sdrh */
404ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
40591bb0eedSdrh   SrcList *pSrc;                  /* All tables in the FROM clause */
40691bb0eedSdrh   int i, j;                       /* Loop counters */
40791bb0eedSdrh   struct SrcList_item *pLeft;     /* Left table being joined */
40891bb0eedSdrh   struct SrcList_item *pRight;    /* Right table being joined */
409ad2d8307Sdrh 
41091bb0eedSdrh   pSrc = p->pSrc;
41191bb0eedSdrh   pLeft = &pSrc->a[0];
41291bb0eedSdrh   pRight = &pLeft[1];
41391bb0eedSdrh   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
41491bb0eedSdrh     Table *pLeftTab = pLeft->pTab;
41591bb0eedSdrh     Table *pRightTab = pRight->pTab;
416ad27e761Sdrh     int isOuter;
41791bb0eedSdrh 
4181c767f0dSdrh     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
4198a48b9c0Sdrh     isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
420ad2d8307Sdrh 
421ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
422ad2d8307Sdrh     ** every column that the two tables have in common.
423ad2d8307Sdrh     */
4248a48b9c0Sdrh     if( pRight->fg.jointype & JT_NATURAL ){
42561dfc31dSdrh       if( pRight->pOn || pRight->pUsing ){
4264adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
427ad2d8307Sdrh            "an ON or USING clause", 0);
428ad2d8307Sdrh         return 1;
429ad2d8307Sdrh       }
4302179b434Sdrh       for(j=0; j<pRightTab->nCol; j++){
4312179b434Sdrh         char *zName;   /* Name of column in the right table */
4322179b434Sdrh         int iLeft;     /* Matching left table */
4332179b434Sdrh         int iLeftCol;  /* Matching column in the left table */
4342179b434Sdrh 
4352179b434Sdrh         zName = pRightTab->aCol[j].zName;
4362179b434Sdrh         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
4372179b434Sdrh           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
4382179b434Sdrh                        isOuter, &p->pWhere);
439ad2d8307Sdrh         }
440ad2d8307Sdrh       }
441ad2d8307Sdrh     }
442ad2d8307Sdrh 
443ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
444ad2d8307Sdrh     */
44561dfc31dSdrh     if( pRight->pOn && pRight->pUsing ){
4464adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
447da93d238Sdrh         "clauses in the same join");
448ad2d8307Sdrh       return 1;
449ad2d8307Sdrh     }
450ad2d8307Sdrh 
451ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
45291bb0eedSdrh     ** an AND operator.
453ad2d8307Sdrh     */
45461dfc31dSdrh     if( pRight->pOn ){
455ad27e761Sdrh       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
45617435752Sdrh       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
45761dfc31dSdrh       pRight->pOn = 0;
458ad2d8307Sdrh     }
459ad2d8307Sdrh 
460ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
461ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
462ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
463ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
464ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
465ad2d8307Sdrh     ** not contained in both tables to be joined.
466ad2d8307Sdrh     */
46761dfc31dSdrh     if( pRight->pUsing ){
46861dfc31dSdrh       IdList *pList = pRight->pUsing;
469ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
4702179b434Sdrh         char *zName;     /* Name of the term in the USING clause */
4712179b434Sdrh         int iLeft;       /* Table on the left with matching column name */
4722179b434Sdrh         int iLeftCol;    /* Column number of matching column on the left */
4732179b434Sdrh         int iRightCol;   /* Column number of matching column on the right */
4742179b434Sdrh 
4752179b434Sdrh         zName = pList->a[j].zName;
4762179b434Sdrh         iRightCol = columnIndex(pRightTab, zName);
4772179b434Sdrh         if( iRightCol<0
4782179b434Sdrh          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
4792179b434Sdrh         ){
4804adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
48191bb0eedSdrh             "not present in both tables", zName);
482ad2d8307Sdrh           return 1;
483ad2d8307Sdrh         }
4842179b434Sdrh         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
4852179b434Sdrh                      isOuter, &p->pWhere);
486ad2d8307Sdrh       }
487ad2d8307Sdrh     }
488ad2d8307Sdrh   }
489ad2d8307Sdrh   return 0;
490ad2d8307Sdrh }
491ad2d8307Sdrh 
492079a3072Sdrh /* Forward reference */
493079a3072Sdrh static KeyInfo *keyInfoFromExprList(
494079a3072Sdrh   Parse *pParse,       /* Parsing context */
495079a3072Sdrh   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
496079a3072Sdrh   int iStart,          /* Begin with this column of pList */
497079a3072Sdrh   int nExtra           /* Add this many extra columns to the end */
498079a3072Sdrh );
499079a3072Sdrh 
500ad2d8307Sdrh /*
501f45f2326Sdrh ** Generate code that will push the record in registers regData
502f45f2326Sdrh ** through regData+nData-1 onto the sorter.
503c926afbcSdrh */
504d59ba6ceSdrh static void pushOntoSorter(
505d59ba6ceSdrh   Parse *pParse,         /* Parser context */
506079a3072Sdrh   SortCtx *pSort,        /* Information about the ORDER BY clause */
507b7654111Sdrh   Select *pSelect,       /* The whole SELECT statement */
508f45f2326Sdrh   int regData,           /* First register holding data to be sorted */
5095579d59fSdrh   int regOrigData,       /* First register holding data before packing */
510fd0a2f97Sdrh   int nData,             /* Number of elements in the data array */
511fd0a2f97Sdrh   int nPrefixReg         /* No. of reg prior to regData available for use */
512d59ba6ceSdrh ){
513f45f2326Sdrh   Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
51478d58432Sdan   int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
515f45f2326Sdrh   int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
51678d58432Sdan   int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
517fd0a2f97Sdrh   int regBase;                                     /* Regs for sorter record */
518fb0d6e56Sdrh   int regRecord = ++pParse->nMem;                  /* Assembled sorter record */
51978d58432Sdan   int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
520f45f2326Sdrh   int op;                            /* Opcode to add sorter record to sorter */
521a04a8be2Sdrh   int iLimit;                        /* LIMIT counter */
522f45f2326Sdrh 
52378d58432Sdan   assert( bSeq==0 || bSeq==1 );
5245579d59fSdrh   assert( nData==1 || regData==regOrigData );
525fd0a2f97Sdrh   if( nPrefixReg ){
52678d58432Sdan     assert( nPrefixReg==nExpr+bSeq );
52778d58432Sdan     regBase = regData - nExpr - bSeq;
528fd0a2f97Sdrh   }else{
529fb0d6e56Sdrh     regBase = pParse->nMem + 1;
530fb0d6e56Sdrh     pParse->nMem += nBase;
531fd0a2f97Sdrh   }
532a04a8be2Sdrh   assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
533a04a8be2Sdrh   iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
534a04a8be2Sdrh   pSort->labelDone = sqlite3VdbeMakeLabel(v);
5355579d59fSdrh   sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
5365579d59fSdrh                           SQLITE_ECEL_DUP|SQLITE_ECEL_REF);
53778d58432Sdan   if( bSeq ){
538079a3072Sdrh     sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
539fd0a2f97Sdrh   }
54078d58432Sdan   if( nPrefixReg==0 ){
541236241aeSdrh     sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
54278d58432Sdan   }
543f45f2326Sdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
544079a3072Sdrh   if( nOBSat>0 ){
545079a3072Sdrh     int regPrevKey;   /* The first nOBSat columns of the previous row */
546079a3072Sdrh     int addrFirst;    /* Address of the OP_IfNot opcode */
547079a3072Sdrh     int addrJmp;      /* Address of the OP_Jump opcode */
548079a3072Sdrh     VdbeOp *pOp;      /* Opcode that opens the sorter */
549079a3072Sdrh     int nKey;         /* Number of sorting key columns, including OP_Sequence */
550dbfca2b7Sdrh     KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
551079a3072Sdrh 
55226d7e7c6Sdrh     regPrevKey = pParse->nMem+1;
55326d7e7c6Sdrh     pParse->nMem += pSort->nOBSat;
55478d58432Sdan     nKey = nExpr - pSort->nOBSat + bSeq;
55578d58432Sdan     if( bSeq ){
55678d58432Sdan       addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
55778d58432Sdan     }else{
55878d58432Sdan       addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
55978d58432Sdan     }
56078d58432Sdan     VdbeCoverage(v);
56126d7e7c6Sdrh     sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
562079a3072Sdrh     pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
56359b8f2e1Sdrh     if( pParse->db->mallocFailed ) return;
564fb0d6e56Sdrh     pOp->p2 = nKey + nData;
565dbfca2b7Sdrh     pKI = pOp->p4.pKeyInfo;
566dbfca2b7Sdrh     memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
567dbfca2b7Sdrh     sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
568fe201effSdrh     testcase( pKI->nXField>2 );
569fe201effSdrh     pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
570fe201effSdrh                                            pKI->nXField-1);
571079a3072Sdrh     addrJmp = sqlite3VdbeCurrentAddr(v);
572079a3072Sdrh     sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
573079a3072Sdrh     pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
574079a3072Sdrh     pSort->regReturn = ++pParse->nMem;
575079a3072Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
57665ea12cbSdrh     sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
577a04a8be2Sdrh     if( iLimit ){
578a04a8be2Sdrh       sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
579a04a8be2Sdrh       VdbeCoverage(v);
580a04a8be2Sdrh     }
581079a3072Sdrh     sqlite3VdbeJumpHere(v, addrFirst);
582236241aeSdrh     sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
583079a3072Sdrh     sqlite3VdbeJumpHere(v, addrJmp);
584079a3072Sdrh   }
585079a3072Sdrh   if( pSort->sortFlags & SORTFLAG_UseSorter ){
586c6aff30cSdrh     op = OP_SorterInsert;
587c6aff30cSdrh   }else{
588c6aff30cSdrh     op = OP_IdxInsert;
589c6aff30cSdrh   }
590079a3072Sdrh   sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
591a04a8be2Sdrh   if( iLimit ){
59216897072Sdrh     int addr;
593*a536df4eSdrh     int r1 = 0;
594*a536df4eSdrh     /* Fill the sorter until it contains LIMIT+OFFSET entries.  (The iLimit
595*a536df4eSdrh     ** register is initialized with value of LIMIT+OFFSET.)  After the sorter
596*a536df4eSdrh     ** fills up, delete the least entry in the sorter after each insert.
597*a536df4eSdrh     ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */
5988b0cf38aSdrh     addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v);
599079a3072Sdrh     sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
600*a536df4eSdrh     if( pSort->bOrderedInnerLoop ){
601*a536df4eSdrh       r1 = ++pParse->nMem;
602*a536df4eSdrh       sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1);
603*a536df4eSdrh       VdbeComment((v, "seq"));
604*a536df4eSdrh     }
605079a3072Sdrh     sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
606*a536df4eSdrh     if( pSort->bOrderedInnerLoop ){
607*a536df4eSdrh       /* If the inner loop is driven by an index such that values from
608*a536df4eSdrh       ** the same iteration of the inner loop are in sorted order, then
609*a536df4eSdrh       ** immediately jump to the next iteration of an inner loop if the
610*a536df4eSdrh       ** entry from the current iteration does not fit into the top
611*a536df4eSdrh       ** LIMIT+OFFSET entries of the sorter. */
612*a536df4eSdrh       int iBrk = sqlite3VdbeCurrentAddr(v) + 2;
613*a536df4eSdrh       sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1);
614*a536df4eSdrh       VdbeCoverage(v);
615*a536df4eSdrh     }
61616897072Sdrh     sqlite3VdbeJumpHere(v, addr);
617d59ba6ceSdrh   }
618c926afbcSdrh }
619c926afbcSdrh 
620c926afbcSdrh /*
621ec7429aeSdrh ** Add code to implement the OFFSET
622ea48eb2eSdrh */
623ec7429aeSdrh static void codeOffset(
624bab39e13Sdrh   Vdbe *v,          /* Generate code into this VM */
625aa9ce707Sdrh   int iOffset,      /* Register holding the offset counter */
626b7654111Sdrh   int iContinue     /* Jump here to skip the current record */
627ea48eb2eSdrh ){
628a22a75e5Sdrh   if( iOffset>0 ){
6298b0cf38aSdrh     sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
6308b0cf38aSdrh     VdbeComment((v, "OFFSET"));
631ea48eb2eSdrh   }
632ea48eb2eSdrh }
633ea48eb2eSdrh 
634ea48eb2eSdrh /*
63598757157Sdrh ** Add code that will check to make sure the N registers starting at iMem
63698757157Sdrh ** form a distinct entry.  iTab is a sorting index that holds previously
637a2a49dc9Sdrh ** seen combinations of the N values.  A new entry is made in iTab
638a2a49dc9Sdrh ** if the current N values are new.
639a2a49dc9Sdrh **
640a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the
641a2a49dc9Sdrh ** stack if the top N elements are not distinct.
642a2a49dc9Sdrh */
643a2a49dc9Sdrh static void codeDistinct(
6442dcef11bSdrh   Parse *pParse,     /* Parsing and code generating context */
645a2a49dc9Sdrh   int iTab,          /* A sorting index used to test for distinctness */
646a2a49dc9Sdrh   int addrRepeat,    /* Jump to here if not distinct */
647477df4b3Sdrh   int N,             /* Number of elements */
648a2a49dc9Sdrh   int iMem           /* First element */
649a2a49dc9Sdrh ){
6502dcef11bSdrh   Vdbe *v;
6512dcef11bSdrh   int r1;
6522dcef11bSdrh 
6532dcef11bSdrh   v = pParse->pVdbe;
6542dcef11bSdrh   r1 = sqlite3GetTempReg(pParse);
655688852abSdrh   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
6561db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
6572dcef11bSdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
6582dcef11bSdrh   sqlite3ReleaseTempReg(pParse, r1);
659a2a49dc9Sdrh }
660a2a49dc9Sdrh 
661bb7dd683Sdrh #ifndef SQLITE_OMIT_SUBQUERY
662a2a49dc9Sdrh /*
663e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression
664e305f43fSdrh ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
665bb7dd683Sdrh ** column.  We do this in a subroutine because the error used to occur
666bb7dd683Sdrh ** in multiple places.  (The error only occurs in one place now, but we
667bb7dd683Sdrh ** retain the subroutine to minimize code disruption.)
668e305f43fSdrh */
6696c8c8ce0Sdanielk1977 static int checkForMultiColumnSelectError(
6706c8c8ce0Sdanielk1977   Parse *pParse,       /* Parse context. */
6716c8c8ce0Sdanielk1977   SelectDest *pDest,   /* Destination of SELECT results */
6726c8c8ce0Sdanielk1977   int nExpr            /* Number of result columns returned by SELECT */
6736c8c8ce0Sdanielk1977 ){
6746c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
675e305f43fSdrh   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
676e305f43fSdrh     sqlite3ErrorMsg(pParse, "only a single result allowed for "
677e305f43fSdrh        "a SELECT that is part of an expression");
678e305f43fSdrh     return 1;
679e305f43fSdrh   }else{
680e305f43fSdrh     return 0;
681e305f43fSdrh   }
682e305f43fSdrh }
683bb7dd683Sdrh #endif
684c99130fdSdrh 
685c99130fdSdrh /*
6862282792aSdrh ** This routine generates the code for the inside of the inner loop
6872282792aSdrh ** of a SELECT.
68882c3d636Sdrh **
689340309fdSdrh ** If srcTab is negative, then the pEList expressions
690340309fdSdrh ** are evaluated in order to get the data for this row.  If srcTab is
691340309fdSdrh ** zero or more, then data is pulled from srcTab and pEList is used only
692340309fdSdrh ** to get number columns and the datatype for each column.
6932282792aSdrh */
694d2b3e23bSdrh static void selectInnerLoop(
6952282792aSdrh   Parse *pParse,          /* The parser context */
696df199a25Sdrh   Select *p,              /* The complete select statement being coded */
6972282792aSdrh   ExprList *pEList,       /* List of values being extracted */
69882c3d636Sdrh   int srcTab,             /* Pull data from this table */
699079a3072Sdrh   SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
700e8e4af76Sdrh   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
7016c8c8ce0Sdanielk1977   SelectDest *pDest,      /* How to dispose of the results */
7022282792aSdrh   int iContinue,          /* Jump here to continue with next row */
703a9671a22Sdrh   int iBreak              /* Jump here to break out of the inner loop */
7042282792aSdrh ){
7052282792aSdrh   Vdbe *v = pParse->pVdbe;
706d847eaadSdrh   int i;
707ea48eb2eSdrh   int hasDistinct;        /* True if the DISTINCT keyword is present */
708d847eaadSdrh   int regResult;              /* Start of memory holding result set */
709d847eaadSdrh   int eDest = pDest->eDest;   /* How to dispose of results */
7102b596da8Sdrh   int iParm = pDest->iSDParm; /* First argument to disposal method */
711d847eaadSdrh   int nResultCol;             /* Number of result columns */
712fd0a2f97Sdrh   int nPrefixReg = 0;         /* Number of extra registers before regResult */
71338640e15Sdrh 
7141c767f0dSdrh   assert( v );
71538640e15Sdrh   assert( pEList!=0 );
716e8e4af76Sdrh   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
717079a3072Sdrh   if( pSort && pSort->pOrderBy==0 ) pSort = 0;
718079a3072Sdrh   if( pSort==0 && !hasDistinct ){
719a22a75e5Sdrh     assert( iContinue!=0 );
720aa9ce707Sdrh     codeOffset(v, p->iOffset, iContinue);
721df199a25Sdrh   }
722df199a25Sdrh 
723967e8b73Sdrh   /* Pull the requested columns.
7242282792aSdrh   */
725d847eaadSdrh   nResultCol = pEList->nExpr;
72605a86c5cSdrh 
7272b596da8Sdrh   if( pDest->iSdst==0 ){
728fd0a2f97Sdrh     if( pSort ){
72978d58432Sdan       nPrefixReg = pSort->pOrderBy->nExpr;
73078d58432Sdan       if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
731fd0a2f97Sdrh       pParse->nMem += nPrefixReg;
7321013c932Sdrh     }
733a2a49dc9Sdrh     pDest->iSdst = pParse->nMem+1;
734477df4b3Sdrh     pParse->nMem += nResultCol;
73505a86c5cSdrh   }else if( pDest->iSdst+nResultCol > pParse->nMem ){
73605a86c5cSdrh     /* This is an error condition that can result, for example, when a SELECT
73705a86c5cSdrh     ** on the right-hand side of an INSERT contains more result columns than
73805a86c5cSdrh     ** there are columns in the table on the left.  The error will be caught
73905a86c5cSdrh     ** and reported later.  But we need to make sure enough memory is allocated
74005a86c5cSdrh     ** to avoid other spurious errors in the meantime. */
74105a86c5cSdrh     pParse->nMem += nResultCol;
7424c583128Sdrh   }
74305a86c5cSdrh   pDest->nSdst = nResultCol;
7442b596da8Sdrh   regResult = pDest->iSdst;
745340309fdSdrh   if( srcTab>=0 ){
746340309fdSdrh     for(i=0; i<nResultCol; i++){
747d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
748340309fdSdrh       VdbeComment((v, "%s", pEList->a[i].zName));
74982c3d636Sdrh     }
7509ed1dfa8Sdanielk1977   }else if( eDest!=SRT_Exists ){
7519ed1dfa8Sdanielk1977     /* If the destination is an EXISTS(...) expression, the actual
7529ed1dfa8Sdanielk1977     ** values returned by the SELECT are not required.
7539ed1dfa8Sdanielk1977     */
754df553659Sdrh     u8 ecelFlags;
755df553659Sdrh     if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
756df553659Sdrh       ecelFlags = SQLITE_ECEL_DUP;
757df553659Sdrh     }else{
758df553659Sdrh       ecelFlags = 0;
759a2a49dc9Sdrh     }
7605579d59fSdrh     sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags);
761a2a49dc9Sdrh   }
7622282792aSdrh 
763daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
764daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
765daffd0e5Sdrh   ** part of the result.
7662282792aSdrh   */
767ea48eb2eSdrh   if( hasDistinct ){
768e8e4af76Sdrh     switch( pDistinct->eTnctType ){
769e8e4af76Sdrh       case WHERE_DISTINCT_ORDERED: {
770e8e4af76Sdrh         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
771e8e4af76Sdrh         int iJump;              /* Jump destination */
772e8e4af76Sdrh         int regPrev;            /* Previous row content */
773e8e4af76Sdrh 
774e8e4af76Sdrh         /* Allocate space for the previous row */
775e8e4af76Sdrh         regPrev = pParse->nMem+1;
776340309fdSdrh         pParse->nMem += nResultCol;
777e8e4af76Sdrh 
778e8e4af76Sdrh         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
779e8e4af76Sdrh         ** sets the MEM_Cleared bit on the first register of the
780e8e4af76Sdrh         ** previous value.  This will cause the OP_Ne below to always
781e8e4af76Sdrh         ** fail on the first iteration of the loop even if the first
782e8e4af76Sdrh         ** row is all NULLs.
783e8e4af76Sdrh         */
784e8e4af76Sdrh         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
785e8e4af76Sdrh         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
786e8e4af76Sdrh         pOp->opcode = OP_Null;
787e8e4af76Sdrh         pOp->p1 = 1;
788e8e4af76Sdrh         pOp->p2 = regPrev;
789e8e4af76Sdrh 
790340309fdSdrh         iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
791340309fdSdrh         for(i=0; i<nResultCol; i++){
792e8e4af76Sdrh           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
793340309fdSdrh           if( i<nResultCol-1 ){
794e8e4af76Sdrh             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
795688852abSdrh             VdbeCoverage(v);
796e8e4af76Sdrh           }else{
797e8e4af76Sdrh             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
798688852abSdrh             VdbeCoverage(v);
799e8e4af76Sdrh            }
800e8e4af76Sdrh           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
801e8e4af76Sdrh           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
802e8e4af76Sdrh         }
803fcf2a775Sdrh         assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
804340309fdSdrh         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
805e8e4af76Sdrh         break;
806e8e4af76Sdrh       }
807e8e4af76Sdrh 
808e8e4af76Sdrh       case WHERE_DISTINCT_UNIQUE: {
809e8e4af76Sdrh         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
810e8e4af76Sdrh         break;
811e8e4af76Sdrh       }
812e8e4af76Sdrh 
813e8e4af76Sdrh       default: {
814e8e4af76Sdrh         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
81538b4149cSdrh         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
81638b4149cSdrh                      regResult);
817e8e4af76Sdrh         break;
818e8e4af76Sdrh       }
819e8e4af76Sdrh     }
820079a3072Sdrh     if( pSort==0 ){
821aa9ce707Sdrh       codeOffset(v, p->iOffset, iContinue);
822ea48eb2eSdrh     }
8232282792aSdrh   }
82482c3d636Sdrh 
825c926afbcSdrh   switch( eDest ){
82682c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
82782c3d636Sdrh     ** table iParm.
8282282792aSdrh     */
82913449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
830c926afbcSdrh     case SRT_Union: {
8319cbf3425Sdrh       int r1;
8329cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
833340309fdSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
8349cbf3425Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
8359cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
836c926afbcSdrh       break;
837c926afbcSdrh     }
83882c3d636Sdrh 
83982c3d636Sdrh     /* Construct a record from the query result, but instead of
84082c3d636Sdrh     ** saving that record, use it as a key to delete elements from
84182c3d636Sdrh     ** the temporary table iParm.
84282c3d636Sdrh     */
843c926afbcSdrh     case SRT_Except: {
844340309fdSdrh       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
845c926afbcSdrh       break;
846c926afbcSdrh     }
847781def29Sdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
8485338a5f7Sdanielk1977 
8495338a5f7Sdanielk1977     /* Store the result as data using a unique key.
8505338a5f7Sdanielk1977     */
8518e1ee88cSdrh     case SRT_Fifo:
8528e1ee88cSdrh     case SRT_DistFifo:
8535338a5f7Sdanielk1977     case SRT_Table:
854b9bb7c18Sdrh     case SRT_EphemTab: {
855fd0a2f97Sdrh       int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
856373cc2ddSdrh       testcase( eDest==SRT_Table );
857373cc2ddSdrh       testcase( eDest==SRT_EphemTab );
858e2248cfdSdrh       testcase( eDest==SRT_Fifo );
859e2248cfdSdrh       testcase( eDest==SRT_DistFifo );
860fd0a2f97Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
8618ce7184bSdan #ifndef SQLITE_OMIT_CTE
8628e1ee88cSdrh       if( eDest==SRT_DistFifo ){
8638e1ee88cSdrh         /* If the destination is DistFifo, then cursor (iParm+1) is open
8648ce7184bSdan         ** on an ephemeral index. If the current row is already present
8658ce7184bSdan         ** in the index, do not write it to the output. If not, add the
8668ce7184bSdan         ** current row to the index and proceed with writing it to the
8678ce7184bSdan         ** output table as well.  */
8688ce7184bSdan         int addr = sqlite3VdbeCurrentAddr(v) + 4;
86938b4149cSdrh         sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
87038b4149cSdrh         VdbeCoverage(v);
8718ce7184bSdan         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
872079a3072Sdrh         assert( pSort==0 );
8738ce7184bSdan       }
8748ce7184bSdan #endif
875079a3072Sdrh       if( pSort ){
8765579d59fSdrh         pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
8775338a5f7Sdanielk1977       }else{
878b7654111Sdrh         int r2 = sqlite3GetTempReg(pParse);
879b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
880b7654111Sdrh         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
881b7654111Sdrh         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
882b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r2);
8835338a5f7Sdanielk1977       }
884fd0a2f97Sdrh       sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
8855338a5f7Sdanielk1977       break;
8865338a5f7Sdanielk1977     }
8872282792aSdrh 
88893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
8892282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
8902282792aSdrh     ** then there should be a single item on the stack.  Write this
8912282792aSdrh     ** item into the set table with bogus data.
8922282792aSdrh     */
893c926afbcSdrh     case SRT_Set: {
894340309fdSdrh       assert( nResultCol==1 );
895634d81deSdrh       pDest->affSdst =
896634d81deSdrh                   sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
897079a3072Sdrh       if( pSort ){
898de941c60Sdrh         /* At first glance you would think we could optimize out the
899de941c60Sdrh         ** ORDER BY in this case since the order of entries in the set
900de941c60Sdrh         ** does not matter.  But there might be a LIMIT clause, in which
901de941c60Sdrh         ** case the order does matter */
9025579d59fSdrh         pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
903c926afbcSdrh       }else{
904b7654111Sdrh         int r1 = sqlite3GetTempReg(pParse);
905634d81deSdrh         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
906da250ea5Sdrh         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
907b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
908b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r1);
909c926afbcSdrh       }
910c926afbcSdrh       break;
911c926afbcSdrh     }
91282c3d636Sdrh 
913504b6989Sdrh     /* If any row exist in the result set, record that fact and abort.
914ec7429aeSdrh     */
915ec7429aeSdrh     case SRT_Exists: {
9164c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
917ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
918ec7429aeSdrh       break;
919ec7429aeSdrh     }
920ec7429aeSdrh 
9212282792aSdrh     /* If this is a scalar select that is part of an expression, then
9222282792aSdrh     ** store the results in the appropriate memory cell and break out
9232282792aSdrh     ** of the scan loop.
9242282792aSdrh     */
925c926afbcSdrh     case SRT_Mem: {
926340309fdSdrh       assert( nResultCol==1 );
927079a3072Sdrh       if( pSort ){
9285579d59fSdrh         pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
929c926afbcSdrh       }else{
93053932ce8Sdrh         assert( regResult==iParm );
931ec7429aeSdrh         /* The LIMIT clause will jump out of the loop for us */
932c926afbcSdrh       }
933c926afbcSdrh       break;
934c926afbcSdrh     }
93593758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
9362282792aSdrh 
93781cf13ecSdrh     case SRT_Coroutine:       /* Send data to a co-routine */
93881cf13ecSdrh     case SRT_Output: {        /* Return the results */
939373cc2ddSdrh       testcase( eDest==SRT_Coroutine );
940373cc2ddSdrh       testcase( eDest==SRT_Output );
941079a3072Sdrh       if( pSort ){
9425579d59fSdrh         pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol,
9435579d59fSdrh                        nPrefixReg);
944e00ee6ebSdrh       }else if( eDest==SRT_Coroutine ){
9452b596da8Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
946c182d163Sdrh       }else{
947340309fdSdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
948340309fdSdrh         sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
949ac82fcf5Sdrh       }
950142e30dfSdrh       break;
951142e30dfSdrh     }
952142e30dfSdrh 
953fe1c6bb9Sdrh #ifndef SQLITE_OMIT_CTE
954fe1c6bb9Sdrh     /* Write the results into a priority queue that is order according to
955fe1c6bb9Sdrh     ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
956fe1c6bb9Sdrh     ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
957fe1c6bb9Sdrh     ** pSO->nExpr columns, then make sure all keys are unique by adding a
958fe1c6bb9Sdrh     ** final OP_Sequence column.  The last column is the record as a blob.
959fe1c6bb9Sdrh     */
960fe1c6bb9Sdrh     case SRT_DistQueue:
961fe1c6bb9Sdrh     case SRT_Queue: {
962fe1c6bb9Sdrh       int nKey;
963fe1c6bb9Sdrh       int r1, r2, r3;
964fe1c6bb9Sdrh       int addrTest = 0;
965fe1c6bb9Sdrh       ExprList *pSO;
966fe1c6bb9Sdrh       pSO = pDest->pOrderBy;
967fe1c6bb9Sdrh       assert( pSO );
968fe1c6bb9Sdrh       nKey = pSO->nExpr;
969fe1c6bb9Sdrh       r1 = sqlite3GetTempReg(pParse);
970fe1c6bb9Sdrh       r2 = sqlite3GetTempRange(pParse, nKey+2);
971fe1c6bb9Sdrh       r3 = r2+nKey+1;
972fe1c6bb9Sdrh       if( eDest==SRT_DistQueue ){
973fe1c6bb9Sdrh         /* If the destination is DistQueue, then cursor (iParm+1) is open
974fe1c6bb9Sdrh         ** on a second ephemeral index that holds all values every previously
9757e4efaecSdrh         ** added to the queue. */
9767e4efaecSdrh         addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
9777e4efaecSdrh                                         regResult, nResultCol);
978688852abSdrh         VdbeCoverage(v);
9797e4efaecSdrh       }
9807e4efaecSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
9817e4efaecSdrh       if( eDest==SRT_DistQueue ){
982fe1c6bb9Sdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
983cfe24586Sdan         sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
984fe1c6bb9Sdrh       }
985fe1c6bb9Sdrh       for(i=0; i<nKey; i++){
986fe1c6bb9Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy,
987fe1c6bb9Sdrh                           regResult + pSO->a[i].u.x.iOrderByCol - 1,
988fe1c6bb9Sdrh                           r2+i);
989fe1c6bb9Sdrh       }
990fe1c6bb9Sdrh       sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
991fe1c6bb9Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
992fe1c6bb9Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
993fe1c6bb9Sdrh       if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
994fe1c6bb9Sdrh       sqlite3ReleaseTempReg(pParse, r1);
995fe1c6bb9Sdrh       sqlite3ReleaseTempRange(pParse, r2, nKey+2);
996fe1c6bb9Sdrh       break;
997fe1c6bb9Sdrh     }
998fe1c6bb9Sdrh #endif /* SQLITE_OMIT_CTE */
999fe1c6bb9Sdrh 
1000fe1c6bb9Sdrh 
1001fe1c6bb9Sdrh 
10026a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER)
1003d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
1004d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
1005d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
1006d7489c39Sdrh     ** about the actual results of the select.
1007d7489c39Sdrh     */
1008c926afbcSdrh     default: {
1009f46f905aSdrh       assert( eDest==SRT_Discard );
1010c926afbcSdrh       break;
1011c926afbcSdrh     }
101293758c8dSdanielk1977 #endif
1013c926afbcSdrh   }
1014ec7429aeSdrh 
10155e87be87Sdrh   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
10165e87be87Sdrh   ** there is a sorter, in which case the sorter has already limited
10175e87be87Sdrh   ** the output for us.
1018ec7429aeSdrh   */
1019079a3072Sdrh   if( pSort==0 && p->iLimit ){
102016897072Sdrh     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
1021ec7429aeSdrh   }
102282c3d636Sdrh }
102382c3d636Sdrh 
102482c3d636Sdrh /*
1025ad124329Sdrh ** Allocate a KeyInfo object sufficient for an index of N key columns and
1026ad124329Sdrh ** X extra columns.
1027323df790Sdrh */
1028ad124329Sdrh KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
1029c263f7c4Sdrh   int nExtra = (N+X)*(sizeof(CollSeq*)+1);
1030c263f7c4Sdrh   KeyInfo *p = sqlite3Malloc(sizeof(KeyInfo) + nExtra);
1031323df790Sdrh   if( p ){
1032ad124329Sdrh     p->aSortOrder = (u8*)&p->aColl[N+X];
1033323df790Sdrh     p->nField = (u16)N;
1034ad124329Sdrh     p->nXField = (u16)X;
1035323df790Sdrh     p->enc = ENC(db);
1036323df790Sdrh     p->db = db;
10372ec2fb22Sdrh     p->nRef = 1;
1038c263f7c4Sdrh     memset(&p[1], 0, nExtra);
10392ec2fb22Sdrh   }else{
10404a642b60Sdrh     sqlite3OomFault(db);
1041323df790Sdrh   }
1042323df790Sdrh   return p;
1043323df790Sdrh }
1044323df790Sdrh 
1045323df790Sdrh /*
10462ec2fb22Sdrh ** Deallocate a KeyInfo object
10472ec2fb22Sdrh */
10482ec2fb22Sdrh void sqlite3KeyInfoUnref(KeyInfo *p){
10492ec2fb22Sdrh   if( p ){
10502ec2fb22Sdrh     assert( p->nRef>0 );
10512ec2fb22Sdrh     p->nRef--;
1052c6efe12dSmistachkin     if( p->nRef==0 ) sqlite3DbFree(0, p);
10532ec2fb22Sdrh   }
10542ec2fb22Sdrh }
10552ec2fb22Sdrh 
10562ec2fb22Sdrh /*
10572ec2fb22Sdrh ** Make a new pointer to a KeyInfo object
10582ec2fb22Sdrh */
10592ec2fb22Sdrh KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
10602ec2fb22Sdrh   if( p ){
10612ec2fb22Sdrh     assert( p->nRef>0 );
10622ec2fb22Sdrh     p->nRef++;
10632ec2fb22Sdrh   }
10642ec2fb22Sdrh   return p;
10652ec2fb22Sdrh }
10662ec2fb22Sdrh 
10672ec2fb22Sdrh #ifdef SQLITE_DEBUG
10682ec2fb22Sdrh /*
10692ec2fb22Sdrh ** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
10702ec2fb22Sdrh ** can only be changed if this is just a single reference to the object.
10712ec2fb22Sdrh **
10722ec2fb22Sdrh ** This routine is used only inside of assert() statements.
10732ec2fb22Sdrh */
10742ec2fb22Sdrh int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
10752ec2fb22Sdrh #endif /* SQLITE_DEBUG */
10762ec2fb22Sdrh 
10772ec2fb22Sdrh /*
1078dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records
1079dece1a84Sdrh ** the collating sequence for each expression in that expression list.
1080dece1a84Sdrh **
10810342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
10820342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to
10830342b1f5Sdrh ** implement that clause.  If the ExprList is the result set of a SELECT
10840342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual
10850342b1f5Sdrh ** index to implement a DISTINCT test.
10860342b1f5Sdrh **
108760ec914cSpeter.d.reid ** Space to hold the KeyInfo structure is obtained from malloc.  The calling
1088dece1a84Sdrh ** function is responsible for seeing that this structure is eventually
10892ec2fb22Sdrh ** freed.
1090dece1a84Sdrh */
1091079a3072Sdrh static KeyInfo *keyInfoFromExprList(
1092079a3072Sdrh   Parse *pParse,       /* Parsing context */
1093079a3072Sdrh   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
1094079a3072Sdrh   int iStart,          /* Begin with this column of pList */
1095079a3072Sdrh   int nExtra           /* Add this many extra columns to the end */
1096079a3072Sdrh ){
1097dece1a84Sdrh   int nExpr;
1098dece1a84Sdrh   KeyInfo *pInfo;
1099dece1a84Sdrh   struct ExprList_item *pItem;
1100323df790Sdrh   sqlite3 *db = pParse->db;
1101dece1a84Sdrh   int i;
1102dece1a84Sdrh 
1103dece1a84Sdrh   nExpr = pList->nExpr;
11043f39bcf5Sdrh   pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
1105dece1a84Sdrh   if( pInfo ){
11062ec2fb22Sdrh     assert( sqlite3KeyInfoIsWriteable(pInfo) );
11076284db90Sdrh     for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
1108dece1a84Sdrh       CollSeq *pColl;
1109dece1a84Sdrh       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
1110323df790Sdrh       if( !pColl ) pColl = db->pDfltColl;
11116284db90Sdrh       pInfo->aColl[i-iStart] = pColl;
11126284db90Sdrh       pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
1113dece1a84Sdrh     }
1114dece1a84Sdrh   }
1115dece1a84Sdrh   return pInfo;
1116dece1a84Sdrh }
1117dece1a84Sdrh 
11187f61e92cSdan /*
11197f61e92cSdan ** Name of the connection operator, used for error messages.
11207f61e92cSdan */
11217f61e92cSdan static const char *selectOpName(int id){
11227f61e92cSdan   char *z;
11237f61e92cSdan   switch( id ){
11247f61e92cSdan     case TK_ALL:       z = "UNION ALL";   break;
11257f61e92cSdan     case TK_INTERSECT: z = "INTERSECT";   break;
11267f61e92cSdan     case TK_EXCEPT:    z = "EXCEPT";      break;
11277f61e92cSdan     default:           z = "UNION";       break;
11287f61e92cSdan   }
11297f61e92cSdan   return z;
11307f61e92cSdan }
11317f61e92cSdan 
11322ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN
113317c0bc0cSdan /*
113417c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
113517c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
113617c0bc0cSdan ** where the caption is of the form:
113717c0bc0cSdan **
113817c0bc0cSdan **   "USE TEMP B-TREE FOR xxx"
113917c0bc0cSdan **
114017c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
114117c0bc0cSdan ** is determined by the zUsage argument.
114217c0bc0cSdan */
11432ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){
11442ce22453Sdan   if( pParse->explain==2 ){
11452ce22453Sdan     Vdbe *v = pParse->pVdbe;
11462ce22453Sdan     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
11472ce22453Sdan     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
11482ce22453Sdan   }
11492ce22453Sdan }
115017c0bc0cSdan 
115117c0bc0cSdan /*
1152bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro
1153bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
1154bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that
1155bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
1156bb2b4418Sdan ** code with #ifndef directives.
1157bb2b4418Sdan */
1158bb2b4418Sdan # define explainSetInteger(a, b) a = b
1159bb2b4418Sdan 
1160bb2b4418Sdan #else
1161bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */
1162bb2b4418Sdan # define explainTempTable(y,z)
1163bb2b4418Sdan # define explainSetInteger(y,z)
1164bb2b4418Sdan #endif
1165bb2b4418Sdan 
1166bb2b4418Sdan #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
1167bb2b4418Sdan /*
11687f61e92cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
11697f61e92cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
11707f61e92cSdan ** where the caption is of one of the two forms:
11717f61e92cSdan **
11727f61e92cSdan **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
11737f61e92cSdan **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
11747f61e92cSdan **
11757f61e92cSdan ** where iSub1 and iSub2 are the integers passed as the corresponding
11767f61e92cSdan ** function parameters, and op is the text representation of the parameter
11777f61e92cSdan ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
11787f61e92cSdan ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
11797f61e92cSdan ** false, or the second form if it is true.
11807f61e92cSdan */
11817f61e92cSdan static void explainComposite(
11827f61e92cSdan   Parse *pParse,                  /* Parse context */
11837f61e92cSdan   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
11847f61e92cSdan   int iSub1,                      /* Subquery id 1 */
11857f61e92cSdan   int iSub2,                      /* Subquery id 2 */
11867f61e92cSdan   int bUseTmp                     /* True if a temp table was used */
11877f61e92cSdan ){
11887f61e92cSdan   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
11897f61e92cSdan   if( pParse->explain==2 ){
11907f61e92cSdan     Vdbe *v = pParse->pVdbe;
11917f61e92cSdan     char *zMsg = sqlite3MPrintf(
119230969d3fSdan         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
11937f61e92cSdan         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
11947f61e92cSdan     );
11957f61e92cSdan     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
11967f61e92cSdan   }
11977f61e92cSdan }
11982ce22453Sdan #else
119917c0bc0cSdan /* No-op versions of the explainXXX() functions and macros. */
12007f61e92cSdan # define explainComposite(v,w,x,y,z)
12012ce22453Sdan #endif
1202dece1a84Sdrh 
1203dece1a84Sdrh /*
1204d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
1205d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
1206d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
1207d8bc7086Sdrh ** routine generates the code needed to do that.
1208d8bc7086Sdrh */
1209c926afbcSdrh static void generateSortTail(
1210cdd536f0Sdrh   Parse *pParse,    /* Parsing context */
1211c926afbcSdrh   Select *p,        /* The SELECT statement */
1212079a3072Sdrh   SortCtx *pSort,   /* Information on the ORDER BY clause */
1213c926afbcSdrh   int nColumn,      /* Number of columns of data */
12146c8c8ce0Sdanielk1977   SelectDest *pDest /* Write the sorted results here */
1215c926afbcSdrh ){
1216ddba0c22Sdrh   Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
1217a04a8be2Sdrh   int addrBreak = pSort->labelDone;            /* Jump here to exit loop */
1218dc5ea5c7Sdrh   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
1219d8bc7086Sdrh   int addr;
1220079a3072Sdrh   int addrOnce = 0;
12210342b1f5Sdrh   int iTab;
1222079a3072Sdrh   ExprList *pOrderBy = pSort->pOrderBy;
12236c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
12242b596da8Sdrh   int iParm = pDest->iSDParm;
12252d401ab8Sdrh   int regRow;
12262d401ab8Sdrh   int regRowid;
1227079a3072Sdrh   int nKey;
1228f45f2326Sdrh   int iSortTab;                   /* Sorter cursor to read from */
1229f45f2326Sdrh   int nSortData;                  /* Trailing values to read from sorter */
1230f45f2326Sdrh   int i;
123178d58432Sdan   int bSeq;                       /* True if sorter record includes seq. no. */
123270f624c3Sdrh #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
123370f624c3Sdrh   struct ExprList_item *aOutEx = p->pEList->a;
123470f624c3Sdrh #endif
12352d401ab8Sdrh 
1236a04a8be2Sdrh   assert( addrBreak<0 );
1237079a3072Sdrh   if( pSort->labelBkOut ){
1238079a3072Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
1239076e85f5Sdrh     sqlite3VdbeGoto(v, addrBreak);
1240079a3072Sdrh     sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
1241079a3072Sdrh   }
1242079a3072Sdrh   iTab = pSort->iECursor;
12437d10d5a6Sdrh   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
12443e9ca094Sdrh     regRowid = 0;
1245f45f2326Sdrh     regRow = pDest->iSdst;
1246f45f2326Sdrh     nSortData = nColumn;
12473e9ca094Sdrh   }else{
12483e9ca094Sdrh     regRowid = sqlite3GetTempReg(pParse);
1249f45f2326Sdrh     regRow = sqlite3GetTempReg(pParse);
1250f45f2326Sdrh     nSortData = 1;
1251cdd536f0Sdrh   }
1252079a3072Sdrh   nKey = pOrderBy->nExpr - pSort->nOBSat;
1253079a3072Sdrh   if( pSort->sortFlags & SORTFLAG_UseSorter ){
1254c2bb3282Sdrh     int regSortOut = ++pParse->nMem;
1255f45f2326Sdrh     iSortTab = pParse->nTab++;
125683553eefSdrh     if( pSort->labelBkOut ){
125783553eefSdrh       addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
125883553eefSdrh     }
1259f45f2326Sdrh     sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
1260079a3072Sdrh     if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
1261c6aff30cSdrh     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
1262688852abSdrh     VdbeCoverage(v);
1263aa9ce707Sdrh     codeOffset(v, p->iOffset, addrContinue);
12646cf4a7dfSdrh     sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
126578d58432Sdan     bSeq = 0;
1266c6aff30cSdrh   }else{
1267688852abSdrh     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
1268aa9ce707Sdrh     codeOffset(v, p->iOffset, addrContinue);
1269f45f2326Sdrh     iSortTab = iTab;
127078d58432Sdan     bSeq = 1;
1271f45f2326Sdrh   }
1272f45f2326Sdrh   for(i=0; i<nSortData; i++){
127378d58432Sdan     sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
127470f624c3Sdrh     VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
1275c6aff30cSdrh   }
1276c926afbcSdrh   switch( eDest ){
1277b9bb7c18Sdrh     case SRT_EphemTab: {
12782d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
12792d401ab8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
12802d401ab8Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1281c926afbcSdrh       break;
1282c926afbcSdrh     }
128393758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
1284c926afbcSdrh     case SRT_Set: {
1285c926afbcSdrh       assert( nColumn==1 );
1286634d81deSdrh       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
1287634d81deSdrh                         &pDest->affSdst, 1);
1288da250ea5Sdrh       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
1289a7a8e14bSdanielk1977       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
1290c926afbcSdrh       break;
1291c926afbcSdrh     }
1292c926afbcSdrh     case SRT_Mem: {
1293c926afbcSdrh       assert( nColumn==1 );
1294b21e7c70Sdrh       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
1295ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
1296c926afbcSdrh       break;
1297c926afbcSdrh     }
129893758c8dSdanielk1977 #endif
1299373cc2ddSdrh     default: {
1300373cc2ddSdrh       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
13011c767f0dSdrh       testcase( eDest==SRT_Output );
13021c767f0dSdrh       testcase( eDest==SRT_Coroutine );
13037d10d5a6Sdrh       if( eDest==SRT_Output ){
13042b596da8Sdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
13052b596da8Sdrh         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
1306a9671a22Sdrh       }else{
13072b596da8Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1308ce665cf6Sdrh       }
1309ac82fcf5Sdrh       break;
1310ac82fcf5Sdrh     }
1311c926afbcSdrh   }
1312f45f2326Sdrh   if( regRowid ){
13132d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regRow);
13142d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regRowid);
1315f45f2326Sdrh   }
1316ec7429aeSdrh   /* The bottom of the loop
1317ec7429aeSdrh   */
1318dc5ea5c7Sdrh   sqlite3VdbeResolveLabel(v, addrContinue);
1319079a3072Sdrh   if( pSort->sortFlags & SORTFLAG_UseSorter ){
1320688852abSdrh     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
1321c6aff30cSdrh   }else{
1322688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
1323c6aff30cSdrh   }
1324079a3072Sdrh   if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
1325dc5ea5c7Sdrh   sqlite3VdbeResolveLabel(v, addrBreak);
1326d8bc7086Sdrh }
1327d8bc7086Sdrh 
1328d8bc7086Sdrh /*
1329517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
1330517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
1331e78e8284Sdrh **
13325f3e5e74Sdrh ** Also try to estimate the size of the returned value and return that
13335f3e5e74Sdrh ** result in *pEstWidth.
13345f3e5e74Sdrh **
1335955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the
1336955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The
1337955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
1338955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The
1339955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is
1340955de52cSdanielk1977 ** considered a column by this function.
1341e78e8284Sdrh **
1342955de52cSdanielk1977 **   SELECT col FROM tbl;
1343955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl;
1344955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl);
1345955de52cSdanielk1977 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
1346955de52cSdanielk1977 **
1347955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL.
13485f3e5e74Sdrh **
13495f3e5e74Sdrh ** This routine has either 3 or 6 parameters depending on whether or not
13505f3e5e74Sdrh ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
1351fcb78a49Sdrh */
13525f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
13535f3e5e74Sdrh # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
1354b121dd14Sdrh #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
1355b121dd14Sdrh # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
1356b121dd14Sdrh #endif
13575f3e5e74Sdrh static const char *columnTypeImpl(
1358955de52cSdanielk1977   NameContext *pNC,
1359955de52cSdanielk1977   Expr *pExpr,
1360b121dd14Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
13615f3e5e74Sdrh   const char **pzOrigDb,
13625f3e5e74Sdrh   const char **pzOrigTab,
13635f3e5e74Sdrh   const char **pzOrigCol,
1364b121dd14Sdrh #endif
13655f3e5e74Sdrh   u8 *pEstWidth
1366955de52cSdanielk1977 ){
1367955de52cSdanielk1977   char const *zType = 0;
1368517eb646Sdanielk1977   int j;
13695f3e5e74Sdrh   u8 estWidth = 1;
1370b121dd14Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1371b121dd14Sdrh   char const *zOrigDb = 0;
1372b121dd14Sdrh   char const *zOrigTab = 0;
1373b121dd14Sdrh   char const *zOrigCol = 0;
1374b121dd14Sdrh #endif
13755338a5f7Sdanielk1977 
1376f7ce4291Sdrh   assert( pExpr!=0 );
1377f7ce4291Sdrh   assert( pNC->pSrcList!=0 );
137800e279d9Sdanielk1977   switch( pExpr->op ){
137930bcf5dbSdrh     case TK_AGG_COLUMN:
138000e279d9Sdanielk1977     case TK_COLUMN: {
1381955de52cSdanielk1977       /* The expression is a column. Locate the table the column is being
1382955de52cSdanielk1977       ** extracted from in NameContext.pSrcList. This table may be real
1383955de52cSdanielk1977       ** database table or a subquery.
1384955de52cSdanielk1977       */
1385955de52cSdanielk1977       Table *pTab = 0;            /* Table structure column is extracted from */
1386955de52cSdanielk1977       Select *pS = 0;             /* Select the column is extracted from */
1387955de52cSdanielk1977       int iCol = pExpr->iColumn;  /* Index of column in pTab */
1388373cc2ddSdrh       testcase( pExpr->op==TK_AGG_COLUMN );
1389373cc2ddSdrh       testcase( pExpr->op==TK_COLUMN );
139043bc88bbSdan       while( pNC && !pTab ){
1391b3bce662Sdanielk1977         SrcList *pTabList = pNC->pSrcList;
1392b3bce662Sdanielk1977         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
1393b3bce662Sdanielk1977         if( j<pTabList->nSrc ){
13946a3ea0e6Sdrh           pTab = pTabList->a[j].pTab;
1395955de52cSdanielk1977           pS = pTabList->a[j].pSelect;
1396b3bce662Sdanielk1977         }else{
1397b3bce662Sdanielk1977           pNC = pNC->pNext;
1398b3bce662Sdanielk1977         }
1399b3bce662Sdanielk1977       }
1400955de52cSdanielk1977 
140143bc88bbSdan       if( pTab==0 ){
1402417168adSdrh         /* At one time, code such as "SELECT new.x" within a trigger would
1403417168adSdrh         ** cause this condition to run.  Since then, we have restructured how
1404417168adSdrh         ** trigger code is generated and so this condition is no longer
140543bc88bbSdan         ** possible. However, it can still be true for statements like
140643bc88bbSdan         ** the following:
140743bc88bbSdan         **
140843bc88bbSdan         **   CREATE TABLE t1(col INTEGER);
140943bc88bbSdan         **   SELECT (SELECT t1.col) FROM FROM t1;
141043bc88bbSdan         **
141143bc88bbSdan         ** when columnType() is called on the expression "t1.col" in the
141243bc88bbSdan         ** sub-select. In this case, set the column type to NULL, even
141343bc88bbSdan         ** though it should really be "INTEGER".
141443bc88bbSdan         **
141543bc88bbSdan         ** This is not a problem, as the column type of "t1.col" is never
141643bc88bbSdan         ** used. When columnType() is called on the expression
141743bc88bbSdan         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
141843bc88bbSdan         ** branch below.  */
14197e62779aSdrh         break;
14207e62779aSdrh       }
1421955de52cSdanielk1977 
142243bc88bbSdan       assert( pTab && pExpr->pTab==pTab );
1423955de52cSdanielk1977       if( pS ){
1424955de52cSdanielk1977         /* The "table" is actually a sub-select or a view in the FROM clause
1425955de52cSdanielk1977         ** of the SELECT statement. Return the declaration type and origin
1426955de52cSdanielk1977         ** data for the result-set column of the sub-select.
1427955de52cSdanielk1977         */
14287b688edeSdrh         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
1429955de52cSdanielk1977           /* If iCol is less than zero, then the expression requests the
1430955de52cSdanielk1977           ** rowid of the sub-select or view. This expression is legal (see
1431955de52cSdanielk1977           ** test case misc2.2.2) - it always evaluates to NULL.
14322ec18a3cSdrh           **
14332ec18a3cSdrh           ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
14342ec18a3cSdrh           ** caught already by name resolution.
1435955de52cSdanielk1977           */
1436955de52cSdanielk1977           NameContext sNC;
1437955de52cSdanielk1977           Expr *p = pS->pEList->a[iCol].pExpr;
1438955de52cSdanielk1977           sNC.pSrcList = pS->pSrc;
143943bc88bbSdan           sNC.pNext = pNC;
1440955de52cSdanielk1977           sNC.pParse = pNC->pParse;
14415f3e5e74Sdrh           zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
1442955de52cSdanielk1977         }
144393c36bb3Sdrh       }else if( pTab->pSchema ){
1444955de52cSdanielk1977         /* A real table */
1445955de52cSdanielk1977         assert( !pS );
1446fcb78a49Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
1447fcb78a49Sdrh         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
14485f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1449fcb78a49Sdrh         if( iCol<0 ){
1450fcb78a49Sdrh           zType = "INTEGER";
14515f3e5e74Sdrh           zOrigCol = "rowid";
1452fcb78a49Sdrh         }else{
14535f3e5e74Sdrh           zOrigCol = pTab->aCol[iCol].zName;
1454d7564865Sdrh           zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
14555f3e5e74Sdrh           estWidth = pTab->aCol[iCol].szEst;
1456955de52cSdanielk1977         }
14575f3e5e74Sdrh         zOrigTab = pTab->zName;
1458955de52cSdanielk1977         if( pNC->pParse ){
1459955de52cSdanielk1977           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
14605f3e5e74Sdrh           zOrigDb = pNC->pParse->db->aDb[iDb].zName;
1461955de52cSdanielk1977         }
14625f3e5e74Sdrh #else
14635f3e5e74Sdrh         if( iCol<0 ){
14645f3e5e74Sdrh           zType = "INTEGER";
14655f3e5e74Sdrh         }else{
1466d7564865Sdrh           zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
14675f3e5e74Sdrh           estWidth = pTab->aCol[iCol].szEst;
14685f3e5e74Sdrh         }
14695f3e5e74Sdrh #endif
1470fcb78a49Sdrh       }
147100e279d9Sdanielk1977       break;
1472736c22b8Sdrh     }
147393758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
147400e279d9Sdanielk1977     case TK_SELECT: {
1475955de52cSdanielk1977       /* The expression is a sub-select. Return the declaration type and
1476955de52cSdanielk1977       ** origin info for the single column in the result set of the SELECT
1477955de52cSdanielk1977       ** statement.
1478955de52cSdanielk1977       */
1479b3bce662Sdanielk1977       NameContext sNC;
14806ab3a2ecSdanielk1977       Select *pS = pExpr->x.pSelect;
1481955de52cSdanielk1977       Expr *p = pS->pEList->a[0].pExpr;
14826ab3a2ecSdanielk1977       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
1483955de52cSdanielk1977       sNC.pSrcList = pS->pSrc;
1484b3bce662Sdanielk1977       sNC.pNext = pNC;
1485955de52cSdanielk1977       sNC.pParse = pNC->pParse;
14865f3e5e74Sdrh       zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
148700e279d9Sdanielk1977       break;
1488fcb78a49Sdrh     }
148993758c8dSdanielk1977 #endif
149000e279d9Sdanielk1977   }
149100e279d9Sdanielk1977 
14925f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
14935f3e5e74Sdrh   if( pzOrigDb ){
14945f3e5e74Sdrh     assert( pzOrigTab && pzOrigCol );
14955f3e5e74Sdrh     *pzOrigDb = zOrigDb;
14965f3e5e74Sdrh     *pzOrigTab = zOrigTab;
14975f3e5e74Sdrh     *pzOrigCol = zOrigCol;
1498955de52cSdanielk1977   }
14995f3e5e74Sdrh #endif
15005f3e5e74Sdrh   if( pEstWidth ) *pEstWidth = estWidth;
1501517eb646Sdanielk1977   return zType;
1502517eb646Sdanielk1977 }
1503517eb646Sdanielk1977 
1504517eb646Sdanielk1977 /*
1505517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
1506517eb646Sdanielk1977 ** in the result set.
1507517eb646Sdanielk1977 */
1508517eb646Sdanielk1977 static void generateColumnTypes(
1509517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
1510517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
1511517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
1512517eb646Sdanielk1977 ){
15133f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE
1514517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
1515517eb646Sdanielk1977   int i;
1516b3bce662Sdanielk1977   NameContext sNC;
1517b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
1518955de52cSdanielk1977   sNC.pParse = pParse;
1519517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
1520517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
15213f913576Sdrh     const char *zType;
15223f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1523955de52cSdanielk1977     const char *zOrigDb = 0;
1524955de52cSdanielk1977     const char *zOrigTab = 0;
1525955de52cSdanielk1977     const char *zOrigCol = 0;
15265f3e5e74Sdrh     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
1527955de52cSdanielk1977 
152885b623f2Sdrh     /* The vdbe must make its own copy of the column-type and other
15294b1ae99dSdanielk1977     ** column specific strings, in case the schema is reset before this
15304b1ae99dSdanielk1977     ** virtual machine is deleted.
1531fbcd585fSdanielk1977     */
153210fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
153310fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
153410fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
15353f913576Sdrh #else
15365f3e5e74Sdrh     zType = columnType(&sNC, p, 0, 0, 0, 0);
15373f913576Sdrh #endif
153810fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
1539fcb78a49Sdrh   }
15405f3e5e74Sdrh #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
1541fcb78a49Sdrh }
1542fcb78a49Sdrh 
1543fcb78a49Sdrh /*
1544fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
1545fcb78a49Sdrh ** in the result set.  This information is used to provide the
1546fcabd464Sdrh ** azCol[] values in the callback.
154782c3d636Sdrh */
1548832508b7Sdrh static void generateColumnNames(
1549832508b7Sdrh   Parse *pParse,      /* Parser context */
1550ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
1551832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
1552832508b7Sdrh ){
1553d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
15546a3ea0e6Sdrh   int i, j;
15559bb575fdSdrh   sqlite3 *db = pParse->db;
1556fcabd464Sdrh   int fullNames, shortNames;
1557fcabd464Sdrh 
1558fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN
15593cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
15603cf86063Sdanielk1977   if( pParse->explain ){
156161de0d1bSdanielk1977     return;
15623cf86063Sdanielk1977   }
15635338a5f7Sdanielk1977 #endif
15643cf86063Sdanielk1977 
15659802947fSdrh   if( pParse->colNamesSet || db->mallocFailed ) return;
15669802947fSdrh   assert( v!=0 );
1567f7ce4291Sdrh   assert( pTabList!=0 );
1568d8bc7086Sdrh   pParse->colNamesSet = 1;
1569fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
1570fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
157122322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
157282c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
157382c3d636Sdrh     Expr *p;
15745a38705eSdrh     p = pEList->a[i].pExpr;
1575373cc2ddSdrh     if( NEVER(p==0) ) continue;
157682c3d636Sdrh     if( pEList->a[i].zName ){
157782c3d636Sdrh       char *zName = pEList->a[i].zName;
157810fb749bSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
1579f7ce4291Sdrh     }else if( p->op==TK_COLUMN || p->op==TK_AGG_COLUMN ){
15806a3ea0e6Sdrh       Table *pTab;
158197665873Sdrh       char *zCol;
15828aff1015Sdrh       int iCol = p->iColumn;
1583e2f02bacSdrh       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
1584e2f02bacSdrh         if( pTabList->a[j].iCursor==p->iTable ) break;
1585e2f02bacSdrh       }
15866a3ea0e6Sdrh       assert( j<pTabList->nSrc );
15876a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
15888aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
158997665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1590b1363206Sdrh       if( iCol<0 ){
159147a6db2bSdrh         zCol = "rowid";
1592b1363206Sdrh       }else{
1593b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
1594b1363206Sdrh       }
1595e49b146fSdrh       if( !shortNames && !fullNames ){
159610fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
1597b7916a78Sdrh             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
15981c767f0dSdrh       }else if( fullNames ){
159982c3d636Sdrh         char *zName = 0;
16001c767f0dSdrh         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
160110fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
160282c3d636Sdrh       }else{
160310fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
160482c3d636Sdrh       }
16051bee3d7bSdrh     }else{
1606859bc542Sdrh       const char *z = pEList->a[i].zSpan;
1607859bc542Sdrh       z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
1608859bc542Sdrh       sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
160982c3d636Sdrh     }
161082c3d636Sdrh   }
161176d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
16125080aaa7Sdrh }
161382c3d636Sdrh 
1614d8bc7086Sdrh /*
161560ec914cSpeter.d.reid ** Given an expression list (which is really the list of expressions
16167d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate
16177d10d5a6Sdrh ** column names for a table that would hold the expression list.
16187d10d5a6Sdrh **
16197d10d5a6Sdrh ** All column names will be unique.
16207d10d5a6Sdrh **
16217d10d5a6Sdrh ** Only the column names are computed.  Column.zType, Column.zColl,
16227d10d5a6Sdrh ** and other fields of Column are zeroed.
16237d10d5a6Sdrh **
16247d10d5a6Sdrh ** Return SQLITE_OK on success.  If a memory allocation error occurs,
16257d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
1626315555caSdrh */
16278981b904Sdrh int sqlite3ColumnsFromExprList(
16287d10d5a6Sdrh   Parse *pParse,          /* Parsing context */
16297d10d5a6Sdrh   ExprList *pEList,       /* Expr list from which to derive column names */
1630d815f17dSdrh   i16 *pnCol,             /* Write the number of columns here */
16317d10d5a6Sdrh   Column **paCol          /* Write the new column list here */
16327d10d5a6Sdrh ){
1633dc5ea5c7Sdrh   sqlite3 *db = pParse->db;   /* Database connection */
1634dc5ea5c7Sdrh   int i, j;                   /* Loop counters */
1635ebed3fa3Sdrh   u32 cnt;                    /* Index added to make the name unique */
1636dc5ea5c7Sdrh   Column *aCol, *pCol;        /* For looping over result columns */
1637dc5ea5c7Sdrh   int nCol;                   /* Number of columns in the result set */
1638dc5ea5c7Sdrh   Expr *p;                    /* Expression for a single result column */
1639dc5ea5c7Sdrh   char *zName;                /* Column name */
1640dc5ea5c7Sdrh   int nName;                  /* Size of name in zName[] */
16410315e3ccSdrh   Hash ht;                    /* Hash table of column names */
164279d5f63fSdrh 
16430315e3ccSdrh   sqlite3HashInit(&ht);
16448c2e0f02Sdan   if( pEList ){
16458c2e0f02Sdan     nCol = pEList->nExpr;
16468c2e0f02Sdan     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
16478c2e0f02Sdan     testcase( aCol==0 );
16488c2e0f02Sdan   }else{
16498c2e0f02Sdan     nCol = 0;
16508c2e0f02Sdan     aCol = 0;
16518c2e0f02Sdan   }
16528836cbbcSdan   assert( nCol==(i16)nCol );
16538c2e0f02Sdan   *pnCol = nCol;
16548c2e0f02Sdan   *paCol = aCol;
16558c2e0f02Sdan 
16560315e3ccSdrh   for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
165779d5f63fSdrh     /* Get an appropriate name for the column
165879d5f63fSdrh     */
1659580c8c18Sdrh     p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
166091bb0eedSdrh     if( (zName = pEList->a[i].zName)!=0 ){
166179d5f63fSdrh       /* If the column contains an "AS <name>" phrase, use <name> as the name */
16627d10d5a6Sdrh     }else{
1663dc5ea5c7Sdrh       Expr *pColExpr = p;  /* The expression that is the result column name */
1664dc5ea5c7Sdrh       Table *pTab;         /* Table associated with this expression */
1665b07028f7Sdrh       while( pColExpr->op==TK_DOT ){
1666b07028f7Sdrh         pColExpr = pColExpr->pRight;
1667b07028f7Sdrh         assert( pColExpr!=0 );
1668b07028f7Sdrh       }
1669373cc2ddSdrh       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
167093a960a0Sdrh         /* For columns use the column name name */
1671dc5ea5c7Sdrh         int iCol = pColExpr->iColumn;
1672373cc2ddSdrh         pTab = pColExpr->pTab;
1673f0209f74Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
167496ceaf86Sdrh         zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
1675b7916a78Sdrh       }else if( pColExpr->op==TK_ID ){
167633e619fcSdrh         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
167796ceaf86Sdrh         zName = pColExpr->u.zToken;
167893a960a0Sdrh       }else{
167979d5f63fSdrh         /* Use the original text of the column expression as its name */
168096ceaf86Sdrh         zName = pEList->a[i].zSpan;
16817d10d5a6Sdrh       }
168222f70c32Sdrh     }
168396ceaf86Sdrh     zName = sqlite3MPrintf(db, "%s", zName);
168479d5f63fSdrh 
168579d5f63fSdrh     /* Make sure the column name is unique.  If the name is not unique,
168660ec914cSpeter.d.reid     ** append an integer to the name so that it becomes unique.
168779d5f63fSdrh     */
16880315e3ccSdrh     cnt = 0;
16890315e3ccSdrh     while( zName && sqlite3HashFind(&ht, zName)!=0 ){
16900315e3ccSdrh       nName = sqlite3Strlen30(zName);
1691f7ee8965Sdrh       if( nName>0 ){
16920315e3ccSdrh         for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
16930315e3ccSdrh         if( zName[j]==':' ) nName = j;
1694f7ee8965Sdrh       }
169596ceaf86Sdrh       zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
1696ebed3fa3Sdrh       if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
169779d5f63fSdrh     }
169891bb0eedSdrh     pCol->zName = zName;
1699ba68f8f3Sdan     sqlite3ColumnPropertiesFromName(0, pCol);
170003d69a68Sdrh     if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
17014a642b60Sdrh       sqlite3OomFault(db);
17027d10d5a6Sdrh     }
17030315e3ccSdrh   }
17040315e3ccSdrh   sqlite3HashClear(&ht);
17057d10d5a6Sdrh   if( db->mallocFailed ){
17067d10d5a6Sdrh     for(j=0; j<i; j++){
17077d10d5a6Sdrh       sqlite3DbFree(db, aCol[j].zName);
17087d10d5a6Sdrh     }
17097d10d5a6Sdrh     sqlite3DbFree(db, aCol);
17107d10d5a6Sdrh     *paCol = 0;
17117d10d5a6Sdrh     *pnCol = 0;
1712fad3039cSmistachkin     return SQLITE_NOMEM_BKPT;
17137d10d5a6Sdrh   }
17147d10d5a6Sdrh   return SQLITE_OK;
17157d10d5a6Sdrh }
1716e014a838Sdanielk1977 
17177d10d5a6Sdrh /*
17187d10d5a6Sdrh ** Add type and collation information to a column list based on
17197d10d5a6Sdrh ** a SELECT statement.
17207d10d5a6Sdrh **
17217d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList().
17227d10d5a6Sdrh ** The column list has only names, not types or collations.  This
17237d10d5a6Sdrh ** routine goes through and adds the types and collations.
17247d10d5a6Sdrh **
1725b08a67a7Sshane ** This routine requires that all identifiers in the SELECT
17267d10d5a6Sdrh ** statement be resolved.
172779d5f63fSdrh */
1728ed06a131Sdrh void sqlite3SelectAddColumnTypeAndCollation(
17297d10d5a6Sdrh   Parse *pParse,        /* Parsing contexts */
1730186ad8ccSdrh   Table *pTab,          /* Add column type information to this table */
17317d10d5a6Sdrh   Select *pSelect       /* SELECT used to determine types and collations */
17327d10d5a6Sdrh ){
17337d10d5a6Sdrh   sqlite3 *db = pParse->db;
17347d10d5a6Sdrh   NameContext sNC;
17357d10d5a6Sdrh   Column *pCol;
17367d10d5a6Sdrh   CollSeq *pColl;
17377d10d5a6Sdrh   int i;
17387d10d5a6Sdrh   Expr *p;
17397d10d5a6Sdrh   struct ExprList_item *a;
1740186ad8ccSdrh   u64 szAll = 0;
17417d10d5a6Sdrh 
17427d10d5a6Sdrh   assert( pSelect!=0 );
17437d10d5a6Sdrh   assert( (pSelect->selFlags & SF_Resolved)!=0 );
1744186ad8ccSdrh   assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
17457d10d5a6Sdrh   if( db->mallocFailed ) return;
1746c43e8be8Sdrh   memset(&sNC, 0, sizeof(sNC));
1747b3bce662Sdanielk1977   sNC.pSrcList = pSelect->pSrc;
17487d10d5a6Sdrh   a = pSelect->pEList->a;
1749186ad8ccSdrh   for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
1750ed06a131Sdrh     const char *zType;
1751ed06a131Sdrh     int n, m;
17527d10d5a6Sdrh     p = a[i].pExpr;
1753ed06a131Sdrh     zType = columnType(&sNC, p, 0, 0, 0, &pCol->szEst);
1754186ad8ccSdrh     szAll += pCol->szEst;
1755c60e9b82Sdanielk1977     pCol->affinity = sqlite3ExprAffinity(p);
1756ed06a131Sdrh     if( zType && (m = sqlite3Strlen30(zType))>0 ){
1757ed06a131Sdrh       n = sqlite3Strlen30(pCol->zName);
1758ed06a131Sdrh       pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
1759ed06a131Sdrh       if( pCol->zName ){
1760ed06a131Sdrh         memcpy(&pCol->zName[n+1], zType, m+1);
1761ed06a131Sdrh         pCol->colFlags |= COLFLAG_HASTYPE;
1762ed06a131Sdrh       }
1763ed06a131Sdrh     }
176405883a34Sdrh     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
1765b3bf556eSdanielk1977     pColl = sqlite3ExprCollSeq(pParse, p);
17661cb50c88Sdrh     if( pColl && pCol->zColl==0 ){
176717435752Sdrh       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
17680202b29eSdanielk1977     }
176922f70c32Sdrh   }
1770186ad8ccSdrh   pTab->szTabRow = sqlite3LogEst(szAll*4);
17717d10d5a6Sdrh }
17727d10d5a6Sdrh 
17737d10d5a6Sdrh /*
17747d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes
17757d10d5a6Sdrh ** the result set of that SELECT.
17767d10d5a6Sdrh */
17777d10d5a6Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
17787d10d5a6Sdrh   Table *pTab;
17797d10d5a6Sdrh   sqlite3 *db = pParse->db;
17807d10d5a6Sdrh   int savedFlags;
17817d10d5a6Sdrh 
17827d10d5a6Sdrh   savedFlags = db->flags;
17837d10d5a6Sdrh   db->flags &= ~SQLITE_FullColNames;
17847d10d5a6Sdrh   db->flags |= SQLITE_ShortColNames;
17857d10d5a6Sdrh   sqlite3SelectPrep(pParse, pSelect, 0);
17867d10d5a6Sdrh   if( pParse->nErr ) return 0;
17877d10d5a6Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
17887d10d5a6Sdrh   db->flags = savedFlags;
17897d10d5a6Sdrh   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
17907d10d5a6Sdrh   if( pTab==0 ){
17917d10d5a6Sdrh     return 0;
17927d10d5a6Sdrh   }
1793373cc2ddSdrh   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
1794b2468954Sdrh   ** is disabled */
17954a642b60Sdrh   assert( db->lookaside.bDisable );
17967d10d5a6Sdrh   pTab->nRef = 1;
17977d10d5a6Sdrh   pTab->zName = 0;
1798cfc9df76Sdan   pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
17998981b904Sdrh   sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
1800ed06a131Sdrh   sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
180122f70c32Sdrh   pTab->iPKey = -1;
18027ce72f69Sdrh   if( db->mallocFailed ){
18031feeaed2Sdan     sqlite3DeleteTable(db, pTab);
18047ce72f69Sdrh     return 0;
18057ce72f69Sdrh   }
180622f70c32Sdrh   return pTab;
180722f70c32Sdrh }
180822f70c32Sdrh 
180922f70c32Sdrh /*
1810d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1811d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1812d8bc7086Sdrh */
18136f077343Sdrh static SQLITE_NOINLINE Vdbe *allocVdbe(Parse *pParse){
18146f077343Sdrh   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
1815aceb31b1Sdrh   if( v ) sqlite3VdbeAddOp0(v, OP_Init);
1816e0e261a4Sdrh   if( pParse->pToplevel==0
1817e0e261a4Sdrh    && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
1818e0e261a4Sdrh   ){
1819e0e261a4Sdrh     pParse->okConstFactor = 1;
1820949f9cd5Sdrh   }
1821d8bc7086Sdrh   return v;
1822d8bc7086Sdrh }
18236f077343Sdrh Vdbe *sqlite3GetVdbe(Parse *pParse){
18246f077343Sdrh   Vdbe *v = pParse->pVdbe;
18256f077343Sdrh   return v ? v : allocVdbe(pParse);
18266f077343Sdrh }
1827d8bc7086Sdrh 
182815007a99Sdrh 
1829d8bc7086Sdrh /*
18307b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
1831ec7429aeSdrh ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
18327b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
1833a2dc3b1aSdanielk1977 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1834a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute
1835a2dc3b1aSdanielk1977 ** the limit and offset.  If there is no limit and/or offset, then
1836a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative.
18377b58daeaSdrh **
1838d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if
1839ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset.  iLimit and
1840aa9ce707Sdrh ** iOffset should have been preset to appropriate default values (zero)
1841aa9ce707Sdrh ** prior to calling this routine.
1842aa9ce707Sdrh **
1843aa9ce707Sdrh ** The iOffset register (if it exists) is initialized to the value
1844aa9ce707Sdrh ** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
1845aa9ce707Sdrh ** iOffset+1 is initialized to LIMIT+OFFSET.
1846aa9ce707Sdrh **
1847ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
18487b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
18497b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
18507b58daeaSdrh ** SELECT statements.
18517b58daeaSdrh */
1852ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
185302afc861Sdrh   Vdbe *v = 0;
185402afc861Sdrh   int iLimit = 0;
185515007a99Sdrh   int iOffset;
18568b0cf38aSdrh   int n;
18570acb7e48Sdrh   if( p->iLimit ) return;
185815007a99Sdrh 
18597b58daeaSdrh   /*
18607b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
1861f7b5496eSdrh   ** controversy about what the correct behavior should be.
18627b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
18637b58daeaSdrh   ** no rows.
18647b58daeaSdrh   */
1865ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
1866373cc2ddSdrh   assert( p->pOffset==0 || p->pLimit!=0 );
1867a2dc3b1aSdanielk1977   if( p->pLimit ){
18680a07c107Sdrh     p->iLimit = iLimit = ++pParse->nMem;
186915007a99Sdrh     v = sqlite3GetVdbe(pParse);
1870aa9ce707Sdrh     assert( v!=0 );
18719b918ed1Sdrh     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
18729b918ed1Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
18739b918ed1Sdrh       VdbeComment((v, "LIMIT counter"));
1874456e4e4fSdrh       if( n==0 ){
1875076e85f5Sdrh         sqlite3VdbeGoto(v, iBreak);
1876c3489bbfSdrh       }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
1877c3489bbfSdrh         p->nSelectRow = sqlite3LogEst((u64)n);
1878c3489bbfSdrh         p->selFlags |= SF_FixedLimit;
18799b918ed1Sdrh       }
18809b918ed1Sdrh     }else{
1881b7654111Sdrh       sqlite3ExprCode(pParse, p->pLimit, iLimit);
1882688852abSdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
1883d4e70ebdSdrh       VdbeComment((v, "LIMIT counter"));
188416897072Sdrh       sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
18859b918ed1Sdrh     }
1886a2dc3b1aSdanielk1977     if( p->pOffset ){
18870a07c107Sdrh       p->iOffset = iOffset = ++pParse->nMem;
1888b7654111Sdrh       pParse->nMem++;   /* Allocate an extra register for limit+offset */
1889b7654111Sdrh       sqlite3ExprCode(pParse, p->pOffset, iOffset);
1890688852abSdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
1891d4e70ebdSdrh       VdbeComment((v, "OFFSET counter"));
1892cc2fa4cfSdrh       sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
1893d4e70ebdSdrh       VdbeComment((v, "LIMIT+OFFSET"));
1894b7654111Sdrh     }
1895d59ba6ceSdrh   }
18967b58daeaSdrh }
18977b58daeaSdrh 
1898b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1899fbc4ee7bSdrh /*
1900fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
1901fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
1902fbc4ee7bSdrh ** the column has no default collating sequence.
1903fbc4ee7bSdrh **
1904fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
1905fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
1906fbc4ee7bSdrh */
1907dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1908fbc4ee7bSdrh   CollSeq *pRet;
1909dc1bdc4fSdanielk1977   if( p->pPrior ){
1910dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1911fbc4ee7bSdrh   }else{
1912fbc4ee7bSdrh     pRet = 0;
1913dc1bdc4fSdanielk1977   }
191410c081adSdrh   assert( iCol>=0 );
19152ec18a3cSdrh   /* iCol must be less than p->pEList->nExpr.  Otherwise an error would
19162ec18a3cSdrh   ** have been thrown during name resolution and we would not have gotten
19172ec18a3cSdrh   ** this far */
19182ec18a3cSdrh   if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
1919dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1920dc1bdc4fSdanielk1977   }
1921dc1bdc4fSdanielk1977   return pRet;
1922d3d39e93Sdrh }
1923d3d39e93Sdrh 
192453bed45eSdan /*
192553bed45eSdan ** The select statement passed as the second parameter is a compound SELECT
192653bed45eSdan ** with an ORDER BY clause. This function allocates and returns a KeyInfo
192753bed45eSdan ** structure suitable for implementing the ORDER BY.
192853bed45eSdan **
192953bed45eSdan ** Space to hold the KeyInfo structure is obtained from malloc. The calling
193053bed45eSdan ** function is responsible for ensuring that this structure is eventually
193153bed45eSdan ** freed.
193253bed45eSdan */
193353bed45eSdan static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
193453bed45eSdan   ExprList *pOrderBy = p->pOrderBy;
193553bed45eSdan   int nOrderBy = p->pOrderBy->nExpr;
193653bed45eSdan   sqlite3 *db = pParse->db;
193753bed45eSdan   KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
193853bed45eSdan   if( pRet ){
193953bed45eSdan     int i;
194053bed45eSdan     for(i=0; i<nOrderBy; i++){
194153bed45eSdan       struct ExprList_item *pItem = &pOrderBy->a[i];
194253bed45eSdan       Expr *pTerm = pItem->pExpr;
194353bed45eSdan       CollSeq *pColl;
194453bed45eSdan 
194553bed45eSdan       if( pTerm->flags & EP_Collate ){
194653bed45eSdan         pColl = sqlite3ExprCollSeq(pParse, pTerm);
194753bed45eSdan       }else{
194853bed45eSdan         pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
194953bed45eSdan         if( pColl==0 ) pColl = db->pDfltColl;
195053bed45eSdan         pOrderBy->a[i].pExpr =
195153bed45eSdan           sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
195253bed45eSdan       }
195353bed45eSdan       assert( sqlite3KeyInfoIsWriteable(pRet) );
195453bed45eSdan       pRet->aColl[i] = pColl;
195553bed45eSdan       pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
195653bed45eSdan     }
195753bed45eSdan   }
195853bed45eSdan 
195953bed45eSdan   return pRet;
196053bed45eSdan }
1961d3d39e93Sdrh 
1962781def29Sdrh #ifndef SQLITE_OMIT_CTE
1963781def29Sdrh /*
1964781def29Sdrh ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
1965781def29Sdrh ** query of the form:
1966781def29Sdrh **
1967781def29Sdrh **   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
1968781def29Sdrh **                         \___________/             \_______________/
1969781def29Sdrh **                           p->pPrior                      p
1970781def29Sdrh **
1971781def29Sdrh **
1972781def29Sdrh ** There is exactly one reference to the recursive-table in the FROM clause
19738a48b9c0Sdrh ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
1974781def29Sdrh **
1975781def29Sdrh ** The setup-query runs once to generate an initial set of rows that go
1976781def29Sdrh ** into a Queue table.  Rows are extracted from the Queue table one by
1977fe1c6bb9Sdrh ** one.  Each row extracted from Queue is output to pDest.  Then the single
1978fe1c6bb9Sdrh ** extracted row (now in the iCurrent table) becomes the content of the
1979fe1c6bb9Sdrh ** recursive-table for a recursive-query run.  The output of the recursive-query
1980781def29Sdrh ** is added back into the Queue table.  Then another row is extracted from Queue
1981781def29Sdrh ** and the iteration continues until the Queue table is empty.
1982781def29Sdrh **
1983781def29Sdrh ** If the compound query operator is UNION then no duplicate rows are ever
1984781def29Sdrh ** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
1985781def29Sdrh ** that have ever been inserted into Queue and causes duplicates to be
1986781def29Sdrh ** discarded.  If the operator is UNION ALL, then duplicates are allowed.
1987781def29Sdrh **
1988781def29Sdrh ** If the query has an ORDER BY, then entries in the Queue table are kept in
1989781def29Sdrh ** ORDER BY order and the first entry is extracted for each cycle.  Without
1990781def29Sdrh ** an ORDER BY, the Queue table is just a FIFO.
1991781def29Sdrh **
1992781def29Sdrh ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
1993781def29Sdrh ** have been output to pDest.  A LIMIT of zero means to output no rows and a
1994781def29Sdrh ** negative LIMIT means to output all rows.  If there is also an OFFSET clause
1995781def29Sdrh ** with a positive value, then the first OFFSET outputs are discarded rather
1996781def29Sdrh ** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
1997781def29Sdrh ** rows have been skipped.
1998781def29Sdrh */
1999781def29Sdrh static void generateWithRecursiveQuery(
2000781def29Sdrh   Parse *pParse,        /* Parsing context */
2001781def29Sdrh   Select *p,            /* The recursive SELECT to be coded */
2002781def29Sdrh   SelectDest *pDest     /* What to do with query results */
2003781def29Sdrh ){
2004781def29Sdrh   SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
2005781def29Sdrh   int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
2006781def29Sdrh   Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
2007781def29Sdrh   Select *pSetup = p->pPrior;   /* The setup query */
2008781def29Sdrh   int addrTop;                  /* Top of the loop */
2009781def29Sdrh   int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
2010edf83d1eSdrh   int iCurrent = 0;             /* The Current table */
2011781def29Sdrh   int regCurrent;               /* Register holding Current table */
2012781def29Sdrh   int iQueue;                   /* The Queue table */
2013781def29Sdrh   int iDistinct = 0;            /* To ensure unique results if UNION */
20148e1ee88cSdrh   int eDest = SRT_Fifo;         /* How to write to Queue */
2015781def29Sdrh   SelectDest destQueue;         /* SelectDest targetting the Queue table */
2016781def29Sdrh   int i;                        /* Loop counter */
2017781def29Sdrh   int rc;                       /* Result code */
2018fe1c6bb9Sdrh   ExprList *pOrderBy;           /* The ORDER BY clause */
2019aa9ce707Sdrh   Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
2020aa9ce707Sdrh   int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
2021781def29Sdrh 
2022781def29Sdrh   /* Obtain authorization to do a recursive query */
2023781def29Sdrh   if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
2024781def29Sdrh 
2025aa9ce707Sdrh   /* Process the LIMIT and OFFSET clauses, if they exist */
2026aa9ce707Sdrh   addrBreak = sqlite3VdbeMakeLabel(v);
2027aa9ce707Sdrh   computeLimitRegisters(pParse, p, addrBreak);
2028aa9ce707Sdrh   pLimit = p->pLimit;
2029aa9ce707Sdrh   pOffset = p->pOffset;
2030aa9ce707Sdrh   regLimit = p->iLimit;
2031aa9ce707Sdrh   regOffset = p->iOffset;
2032aa9ce707Sdrh   p->pLimit = p->pOffset = 0;
2033aa9ce707Sdrh   p->iLimit = p->iOffset = 0;
203453bed45eSdan   pOrderBy = p->pOrderBy;
2035781def29Sdrh 
2036781def29Sdrh   /* Locate the cursor number of the Current table */
2037781def29Sdrh   for(i=0; ALWAYS(i<pSrc->nSrc); i++){
20388a48b9c0Sdrh     if( pSrc->a[i].fg.isRecursive ){
2039781def29Sdrh       iCurrent = pSrc->a[i].iCursor;
2040781def29Sdrh       break;
2041781def29Sdrh     }
2042781def29Sdrh   }
2043781def29Sdrh 
2044fe1c6bb9Sdrh   /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
2045781def29Sdrh   ** the Distinct table must be exactly one greater than Queue in order
20468e1ee88cSdrh   ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
2047781def29Sdrh   iQueue = pParse->nTab++;
2048781def29Sdrh   if( p->op==TK_UNION ){
20498e1ee88cSdrh     eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
2050781def29Sdrh     iDistinct = pParse->nTab++;
2051fe1c6bb9Sdrh   }else{
20528e1ee88cSdrh     eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
2053781def29Sdrh   }
2054781def29Sdrh   sqlite3SelectDestInit(&destQueue, eDest, iQueue);
2055781def29Sdrh 
2056781def29Sdrh   /* Allocate cursors for Current, Queue, and Distinct. */
2057781def29Sdrh   regCurrent = ++pParse->nMem;
2058781def29Sdrh   sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
2059fe1c6bb9Sdrh   if( pOrderBy ){
206053bed45eSdan     KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
2061fe1c6bb9Sdrh     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
2062fe1c6bb9Sdrh                       (char*)pKeyInfo, P4_KEYINFO);
2063fe1c6bb9Sdrh     destQueue.pOrderBy = pOrderBy;
2064fe1c6bb9Sdrh   }else{
2065781def29Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
2066fe1c6bb9Sdrh   }
2067fe1c6bb9Sdrh   VdbeComment((v, "Queue table"));
2068781def29Sdrh   if( iDistinct ){
2069781def29Sdrh     p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
2070781def29Sdrh     p->selFlags |= SF_UsesEphemeral;
2071781def29Sdrh   }
2072781def29Sdrh 
207353bed45eSdan   /* Detach the ORDER BY clause from the compound SELECT */
207453bed45eSdan   p->pOrderBy = 0;
207553bed45eSdan 
2076781def29Sdrh   /* Store the results of the setup-query in Queue. */
2077d227a291Sdrh   pSetup->pNext = 0;
2078781def29Sdrh   rc = sqlite3Select(pParse, pSetup, &destQueue);
2079d227a291Sdrh   pSetup->pNext = p;
2080fe1c6bb9Sdrh   if( rc ) goto end_of_recursive_query;
2081781def29Sdrh 
2082781def29Sdrh   /* Find the next row in the Queue and output that row */
2083688852abSdrh   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
2084781def29Sdrh 
2085781def29Sdrh   /* Transfer the next row in Queue over to Current */
2086781def29Sdrh   sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
2087fe1c6bb9Sdrh   if( pOrderBy ){
2088fe1c6bb9Sdrh     sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
2089fe1c6bb9Sdrh   }else{
2090781def29Sdrh     sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
2091fe1c6bb9Sdrh   }
2092781def29Sdrh   sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
2093781def29Sdrh 
2094fe1c6bb9Sdrh   /* Output the single row in Current */
2095fe1c6bb9Sdrh   addrCont = sqlite3VdbeMakeLabel(v);
2096aa9ce707Sdrh   codeOffset(v, regOffset, addrCont);
2097fe1c6bb9Sdrh   selectInnerLoop(pParse, p, p->pEList, iCurrent,
2098079a3072Sdrh       0, 0, pDest, addrCont, addrBreak);
2099688852abSdrh   if( regLimit ){
210016897072Sdrh     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
2101688852abSdrh     VdbeCoverage(v);
2102688852abSdrh   }
2103fe1c6bb9Sdrh   sqlite3VdbeResolveLabel(v, addrCont);
2104fe1c6bb9Sdrh 
2105781def29Sdrh   /* Execute the recursive SELECT taking the single row in Current as
2106781def29Sdrh   ** the value for the recursive-table. Store the results in the Queue.
2107781def29Sdrh   */
2108b63ce02fSdrh   if( p->selFlags & SF_Aggregate ){
2109b63ce02fSdrh     sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
2110b63ce02fSdrh   }else{
2111781def29Sdrh     p->pPrior = 0;
2112781def29Sdrh     sqlite3Select(pParse, p, &destQueue);
2113781def29Sdrh     assert( p->pPrior==0 );
2114781def29Sdrh     p->pPrior = pSetup;
2115b63ce02fSdrh   }
2116781def29Sdrh 
2117781def29Sdrh   /* Keep running the loop until the Queue is empty */
2118076e85f5Sdrh   sqlite3VdbeGoto(v, addrTop);
2119781def29Sdrh   sqlite3VdbeResolveLabel(v, addrBreak);
2120fe1c6bb9Sdrh 
2121fe1c6bb9Sdrh end_of_recursive_query:
21229afccba2Sdan   sqlite3ExprListDelete(pParse->db, p->pOrderBy);
2123fe1c6bb9Sdrh   p->pOrderBy = pOrderBy;
2124aa9ce707Sdrh   p->pLimit = pLimit;
2125aa9ce707Sdrh   p->pOffset = pOffset;
2126fe1c6bb9Sdrh   return;
2127781def29Sdrh }
2128b68b9778Sdan #endif /* SQLITE_OMIT_CTE */
2129781def29Sdrh 
2130781def29Sdrh /* Forward references */
2131b21e7c70Sdrh static int multiSelectOrderBy(
2132b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
2133b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
2134a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
2135b21e7c70Sdrh );
2136b21e7c70Sdrh 
213745f54a57Sdrh /*
213845f54a57Sdrh ** Handle the special case of a compound-select that originates from a
213945f54a57Sdrh ** VALUES clause.  By handling this as a special case, we avoid deep
214045f54a57Sdrh ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
214145f54a57Sdrh ** on a VALUES clause.
214245f54a57Sdrh **
214345f54a57Sdrh ** Because the Select object originates from a VALUES clause:
214445f54a57Sdrh **   (1) It has no LIMIT or OFFSET
214545f54a57Sdrh **   (2) All terms are UNION ALL
214645f54a57Sdrh **   (3) There is no ORDER BY clause
214745f54a57Sdrh */
214845f54a57Sdrh static int multiSelectValues(
214945f54a57Sdrh   Parse *pParse,        /* Parsing context */
215045f54a57Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
215145f54a57Sdrh   SelectDest *pDest     /* What to do with query results */
215245f54a57Sdrh ){
215345f54a57Sdrh   Select *pPrior;
215445f54a57Sdrh   int nRow = 1;
215545f54a57Sdrh   int rc = 0;
2156772460fdSdrh   assert( p->selFlags & SF_MultiValue );
215745f54a57Sdrh   do{
215845f54a57Sdrh     assert( p->selFlags & SF_Values );
215945f54a57Sdrh     assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
216045f54a57Sdrh     assert( p->pLimit==0 );
216145f54a57Sdrh     assert( p->pOffset==0 );
2162923cadb1Sdan     assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
216345f54a57Sdrh     if( p->pPrior==0 ) break;
216445f54a57Sdrh     assert( p->pPrior->pNext==p );
216545f54a57Sdrh     p = p->pPrior;
216645f54a57Sdrh     nRow++;
216745f54a57Sdrh   }while(1);
216845f54a57Sdrh   while( p ){
216945f54a57Sdrh     pPrior = p->pPrior;
217045f54a57Sdrh     p->pPrior = 0;
217145f54a57Sdrh     rc = sqlite3Select(pParse, p, pDest);
217245f54a57Sdrh     p->pPrior = pPrior;
217345f54a57Sdrh     if( rc ) break;
217445f54a57Sdrh     p->nSelectRow = nRow;
217545f54a57Sdrh     p = p->pNext;
217645f54a57Sdrh   }
217745f54a57Sdrh   return rc;
217845f54a57Sdrh }
2179b21e7c70Sdrh 
2180d3d39e93Sdrh /*
218116ee60ffSdrh ** This routine is called to process a compound query form from
218216ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
218316ee60ffSdrh ** INTERSECT
2184c926afbcSdrh **
2185e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
2186e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
2187e78e8284Sdrh ** in which case this routine will be called recursively.
2188e78e8284Sdrh **
2189e78e8284Sdrh ** The results of the total query are to be written into a destination
2190e78e8284Sdrh ** of type eDest with parameter iParm.
2191e78e8284Sdrh **
2192e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
2193e78e8284Sdrh **
2194e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
2195e78e8284Sdrh **
2196e78e8284Sdrh ** This statement is parsed up as follows:
2197e78e8284Sdrh **
2198e78e8284Sdrh **     SELECT c FROM t3
2199e78e8284Sdrh **      |
2200e78e8284Sdrh **      `----->  SELECT b FROM t2
2201e78e8284Sdrh **                |
22024b11c6d3Sjplyon **                `------>  SELECT a FROM t1
2203e78e8284Sdrh **
2204e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
2205e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
2206e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
2207e78e8284Sdrh **
2208e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
2209e78e8284Sdrh ** individual selects always group from left to right.
221082c3d636Sdrh */
221184ac9d02Sdanielk1977 static int multiSelect(
2212fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
2213fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
2214a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
221584ac9d02Sdanielk1977 ){
221684ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
221710e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
221810e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
22191013c932Sdrh   SelectDest dest;      /* Alternative data destination */
2220eca7e01aSdanielk1977   Select *pDelete = 0;  /* Chain of simple selects to delete */
2221633e6d57Sdrh   sqlite3 *db;          /* Database connection */
22227f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN
2223edf83d1eSdrh   int iSub1 = 0;        /* EQP id of left-hand query */
2224edf83d1eSdrh   int iSub2 = 0;        /* EQP id of right-hand query */
22257f61e92cSdan #endif
222682c3d636Sdrh 
22277b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
2228fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
222982c3d636Sdrh   */
2230701bb3b4Sdrh   assert( p && p->pPrior );  /* Calling function guarantees this much */
2231eae73fbfSdan   assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
2232633e6d57Sdrh   db = pParse->db;
2233d8bc7086Sdrh   pPrior = p->pPrior;
2234bc10377aSdrh   dest = *pDest;
2235d8bc7086Sdrh   if( pPrior->pOrderBy ){
22364adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
2237da93d238Sdrh       selectOpName(p->op));
223884ac9d02Sdanielk1977     rc = 1;
223984ac9d02Sdanielk1977     goto multi_select_end;
224082c3d636Sdrh   }
2241a2dc3b1aSdanielk1977   if( pPrior->pLimit ){
22424adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
22437b58daeaSdrh       selectOpName(p->op));
224484ac9d02Sdanielk1977     rc = 1;
224584ac9d02Sdanielk1977     goto multi_select_end;
22467b58daeaSdrh   }
224782c3d636Sdrh 
22484adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
2249701bb3b4Sdrh   assert( v!=0 );  /* The VDBE already created by calling function */
2250d8bc7086Sdrh 
22511cc3d75fSdrh   /* Create the destination temporary table if necessary
22521cc3d75fSdrh   */
22536c8c8ce0Sdanielk1977   if( dest.eDest==SRT_EphemTab ){
2254b4964b72Sdanielk1977     assert( p->pEList );
22552b596da8Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
22566c8c8ce0Sdanielk1977     dest.eDest = SRT_Table;
22571cc3d75fSdrh   }
22581cc3d75fSdrh 
225945f54a57Sdrh   /* Special handling for a compound-select that originates as a VALUES clause.
226045f54a57Sdrh   */
2261772460fdSdrh   if( p->selFlags & SF_MultiValue ){
226245f54a57Sdrh     rc = multiSelectValues(pParse, p, &dest);
226345f54a57Sdrh     goto multi_select_end;
226445f54a57Sdrh   }
226545f54a57Sdrh 
2266f6e369a1Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
2267f6e369a1Sdrh   ** in their result sets.
2268f6e369a1Sdrh   */
2269f6e369a1Sdrh   assert( p->pEList && pPrior->pEList );
2270923cadb1Sdan   assert( p->pEList->nExpr==pPrior->pEList->nExpr );
2271f6e369a1Sdrh 
2272eede6a53Sdan #ifndef SQLITE_OMIT_CTE
2273eae73fbfSdan   if( p->selFlags & SF_Recursive ){
2274781def29Sdrh     generateWithRecursiveQuery(pParse, p, &dest);
22758ce7184bSdan   }else
22768ce7184bSdan #endif
2277f6e369a1Sdrh 
2278a9671a22Sdrh   /* Compound SELECTs that have an ORDER BY clause are handled separately.
2279a9671a22Sdrh   */
2280f6e369a1Sdrh   if( p->pOrderBy ){
2281a9671a22Sdrh     return multiSelectOrderBy(pParse, p, pDest);
2282eede6a53Sdan   }else
2283f6e369a1Sdrh 
2284f46f905aSdrh   /* Generate code for the left and right SELECT statements.
2285d8bc7086Sdrh   */
228682c3d636Sdrh   switch( p->op ){
2287f46f905aSdrh     case TK_ALL: {
2288ec7429aeSdrh       int addr = 0;
228995aa47b1Sdrh       int nLimit;
2290a2dc3b1aSdanielk1977       assert( !pPrior->pLimit );
2291547180baSdrh       pPrior->iLimit = p->iLimit;
2292547180baSdrh       pPrior->iOffset = p->iOffset;
2293a2dc3b1aSdanielk1977       pPrior->pLimit = p->pLimit;
2294a2dc3b1aSdanielk1977       pPrior->pOffset = p->pOffset;
22957f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
22967d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &dest);
2297ad68cb6bSdanielk1977       p->pLimit = 0;
2298ad68cb6bSdanielk1977       p->pOffset = 0;
229984ac9d02Sdanielk1977       if( rc ){
230084ac9d02Sdanielk1977         goto multi_select_end;
230184ac9d02Sdanielk1977       }
2302f46f905aSdrh       p->pPrior = 0;
23037b58daeaSdrh       p->iLimit = pPrior->iLimit;
23047b58daeaSdrh       p->iOffset = pPrior->iOffset;
230592b01d53Sdrh       if( p->iLimit ){
230616897072Sdrh         addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
2307d4e70ebdSdrh         VdbeComment((v, "Jump ahead if LIMIT reached"));
23089f1ef45fSdrh         if( p->iOffset ){
2309cc2fa4cfSdrh           sqlite3VdbeAddOp3(v, OP_OffsetLimit,
2310cc2fa4cfSdrh                             p->iLimit, p->iOffset+1, p->iOffset);
23119f1ef45fSdrh         }
2312ec7429aeSdrh       }
23137f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
23147d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &dest);
2315373cc2ddSdrh       testcase( rc!=SQLITE_OK );
2316eca7e01aSdanielk1977       pDelete = p->pPrior;
2317f46f905aSdrh       p->pPrior = pPrior;
2318c3489bbfSdrh       p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
231995aa47b1Sdrh       if( pPrior->pLimit
232095aa47b1Sdrh        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
2321c3489bbfSdrh        && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
232295aa47b1Sdrh       ){
2323c3489bbfSdrh         p->nSelectRow = sqlite3LogEst((u64)nLimit);
232495aa47b1Sdrh       }
2325ec7429aeSdrh       if( addr ){
2326ec7429aeSdrh         sqlite3VdbeJumpHere(v, addr);
2327ec7429aeSdrh       }
2328f46f905aSdrh       break;
2329f46f905aSdrh     }
233082c3d636Sdrh     case TK_EXCEPT:
233182c3d636Sdrh     case TK_UNION: {
2332d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
2333ea678832Sdrh       u8 op = 0;       /* One of the SRT_ operations to apply to self */
2334d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
2335a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
2336dc1bdc4fSdanielk1977       int addr;
23376c8c8ce0Sdanielk1977       SelectDest uniondest;
233882c3d636Sdrh 
2339373cc2ddSdrh       testcase( p->op==TK_EXCEPT );
2340373cc2ddSdrh       testcase( p->op==TK_UNION );
234193a960a0Sdrh       priorOp = SRT_Union;
2342d227a291Sdrh       if( dest.eDest==priorOp ){
2343d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
2344c926afbcSdrh         ** right.
2345d8bc7086Sdrh         */
2346e2f02bacSdrh         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
2347e2f02bacSdrh         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
23482b596da8Sdrh         unionTab = dest.iSDParm;
234982c3d636Sdrh       }else{
2350d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
2351d8bc7086Sdrh         ** intermediate results.
2352d8bc7086Sdrh         */
235382c3d636Sdrh         unionTab = pParse->nTab++;
235493a960a0Sdrh         assert( p->pOrderBy==0 );
235566a5167bSdrh         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
2356b9bb7c18Sdrh         assert( p->addrOpenEphm[0] == -1 );
2357b9bb7c18Sdrh         p->addrOpenEphm[0] = addr;
2358d227a291Sdrh         findRightmost(p)->selFlags |= SF_UsesEphemeral;
235984ac9d02Sdanielk1977         assert( p->pEList );
2360d8bc7086Sdrh       }
2361d8bc7086Sdrh 
2362d8bc7086Sdrh       /* Code the SELECT statements to our left
2363d8bc7086Sdrh       */
2364b3bce662Sdanielk1977       assert( !pPrior->pOrderBy );
23651013c932Sdrh       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
23667f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
23677d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &uniondest);
236884ac9d02Sdanielk1977       if( rc ){
236984ac9d02Sdanielk1977         goto multi_select_end;
237084ac9d02Sdanielk1977       }
2371d8bc7086Sdrh 
2372d8bc7086Sdrh       /* Code the current SELECT statement
2373d8bc7086Sdrh       */
23744cfb22f7Sdrh       if( p->op==TK_EXCEPT ){
23754cfb22f7Sdrh         op = SRT_Except;
23764cfb22f7Sdrh       }else{
23774cfb22f7Sdrh         assert( p->op==TK_UNION );
23784cfb22f7Sdrh         op = SRT_Union;
2379d8bc7086Sdrh       }
238082c3d636Sdrh       p->pPrior = 0;
2381a2dc3b1aSdanielk1977       pLimit = p->pLimit;
2382a2dc3b1aSdanielk1977       p->pLimit = 0;
2383a2dc3b1aSdanielk1977       pOffset = p->pOffset;
2384a2dc3b1aSdanielk1977       p->pOffset = 0;
23856c8c8ce0Sdanielk1977       uniondest.eDest = op;
23867f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
23877d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &uniondest);
2388373cc2ddSdrh       testcase( rc!=SQLITE_OK );
23895bd1bf2eSdrh       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
23905bd1bf2eSdrh       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
2391633e6d57Sdrh       sqlite3ExprListDelete(db, p->pOrderBy);
2392eca7e01aSdanielk1977       pDelete = p->pPrior;
239382c3d636Sdrh       p->pPrior = pPrior;
2394a9671a22Sdrh       p->pOrderBy = 0;
2395c3489bbfSdrh       if( p->op==TK_UNION ){
2396c3489bbfSdrh         p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
2397c3489bbfSdrh       }
2398633e6d57Sdrh       sqlite3ExprDelete(db, p->pLimit);
2399a2dc3b1aSdanielk1977       p->pLimit = pLimit;
2400a2dc3b1aSdanielk1977       p->pOffset = pOffset;
240192b01d53Sdrh       p->iLimit = 0;
240292b01d53Sdrh       p->iOffset = 0;
2403d8bc7086Sdrh 
2404d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
2405d8bc7086Sdrh       ** it is that we currently need.
2406d8bc7086Sdrh       */
24072b596da8Sdrh       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
2408373cc2ddSdrh       if( dest.eDest!=priorOp ){
24096b56344dSdrh         int iCont, iBreak, iStart;
241082c3d636Sdrh         assert( p->pEList );
24117d10d5a6Sdrh         if( dest.eDest==SRT_Output ){
241292378253Sdrh           Select *pFirst = p;
241392378253Sdrh           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
24149a8941fcSdan           generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
241541202ccaSdrh         }
24164adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
24174adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
2418ec7429aeSdrh         computeLimitRegisters(pParse, p, iBreak);
2419688852abSdrh         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
24204adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
2421340309fdSdrh         selectInnerLoop(pParse, p, p->pEList, unionTab,
2422e8e4af76Sdrh                         0, 0, &dest, iCont, iBreak);
24234adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
2424688852abSdrh         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
24254adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
242666a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
242782c3d636Sdrh       }
242882c3d636Sdrh       break;
242982c3d636Sdrh     }
2430373cc2ddSdrh     default: assert( p->op==TK_INTERSECT ); {
243182c3d636Sdrh       int tab1, tab2;
24326b56344dSdrh       int iCont, iBreak, iStart;
2433a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset;
2434dc1bdc4fSdanielk1977       int addr;
24351013c932Sdrh       SelectDest intersectdest;
24369cbf3425Sdrh       int r1;
243782c3d636Sdrh 
2438d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
24396206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
2440d8bc7086Sdrh       ** by allocating the tables we will need.
2441d8bc7086Sdrh       */
244282c3d636Sdrh       tab1 = pParse->nTab++;
244382c3d636Sdrh       tab2 = pParse->nTab++;
244493a960a0Sdrh       assert( p->pOrderBy==0 );
2445dc1bdc4fSdanielk1977 
244666a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
2447b9bb7c18Sdrh       assert( p->addrOpenEphm[0] == -1 );
2448b9bb7c18Sdrh       p->addrOpenEphm[0] = addr;
2449d227a291Sdrh       findRightmost(p)->selFlags |= SF_UsesEphemeral;
245084ac9d02Sdanielk1977       assert( p->pEList );
2451d8bc7086Sdrh 
2452d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
2453d8bc7086Sdrh       */
24541013c932Sdrh       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
24557f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
24567d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &intersectdest);
245784ac9d02Sdanielk1977       if( rc ){
245884ac9d02Sdanielk1977         goto multi_select_end;
245984ac9d02Sdanielk1977       }
2460d8bc7086Sdrh 
2461d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
2462d8bc7086Sdrh       */
246366a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
2464b9bb7c18Sdrh       assert( p->addrOpenEphm[1] == -1 );
2465b9bb7c18Sdrh       p->addrOpenEphm[1] = addr;
246682c3d636Sdrh       p->pPrior = 0;
2467a2dc3b1aSdanielk1977       pLimit = p->pLimit;
2468a2dc3b1aSdanielk1977       p->pLimit = 0;
2469a2dc3b1aSdanielk1977       pOffset = p->pOffset;
2470a2dc3b1aSdanielk1977       p->pOffset = 0;
24712b596da8Sdrh       intersectdest.iSDParm = tab2;
24727f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
24737d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &intersectdest);
2474373cc2ddSdrh       testcase( rc!=SQLITE_OK );
2475eca7e01aSdanielk1977       pDelete = p->pPrior;
247682c3d636Sdrh       p->pPrior = pPrior;
247795aa47b1Sdrh       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
2478633e6d57Sdrh       sqlite3ExprDelete(db, p->pLimit);
2479a2dc3b1aSdanielk1977       p->pLimit = pLimit;
2480a2dc3b1aSdanielk1977       p->pOffset = pOffset;
2481d8bc7086Sdrh 
2482d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
2483d8bc7086Sdrh       ** tables.
2484d8bc7086Sdrh       */
248582c3d636Sdrh       assert( p->pEList );
24867d10d5a6Sdrh       if( dest.eDest==SRT_Output ){
248792378253Sdrh         Select *pFirst = p;
248892378253Sdrh         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
24899a8941fcSdan         generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
249041202ccaSdrh       }
24914adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
24924adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
2493ec7429aeSdrh       computeLimitRegisters(pParse, p, iBreak);
2494688852abSdrh       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
24959cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
24969cbf3425Sdrh       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
2497688852abSdrh       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
24989cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
2499340309fdSdrh       selectInnerLoop(pParse, p, p->pEList, tab1,
2500e8e4af76Sdrh                       0, 0, &dest, iCont, iBreak);
25014adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
2502688852abSdrh       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
25034adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
250466a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
250566a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
250682c3d636Sdrh       break;
250782c3d636Sdrh     }
250882c3d636Sdrh   }
25098cdbf836Sdrh 
25107f61e92cSdan   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
25117f61e92cSdan 
2512a9671a22Sdrh   /* Compute collating sequences used by
2513a9671a22Sdrh   ** temporary tables needed to implement the compound select.
2514a9671a22Sdrh   ** Attach the KeyInfo structure to all temporary tables.
25158cdbf836Sdrh   **
25168cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
25178cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
25188cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
25198cdbf836Sdrh   ** no temp tables are required.
2520fbc4ee7bSdrh   */
25217d10d5a6Sdrh   if( p->selFlags & SF_UsesEphemeral ){
2522fbc4ee7bSdrh     int i;                        /* Loop counter */
2523fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
25240342b1f5Sdrh     Select *pLoop;                /* For looping through SELECT statements */
2525f68d7d17Sdrh     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
252693a960a0Sdrh     int nCol;                     /* Number of columns in result set */
2527fbc4ee7bSdrh 
2528d227a291Sdrh     assert( p->pNext==0 );
252993a960a0Sdrh     nCol = p->pEList->nExpr;
2530ad124329Sdrh     pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
2531dc1bdc4fSdanielk1977     if( !pKeyInfo ){
2532fad3039cSmistachkin       rc = SQLITE_NOMEM_BKPT;
2533dc1bdc4fSdanielk1977       goto multi_select_end;
2534dc1bdc4fSdanielk1977     }
25350342b1f5Sdrh     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
25360342b1f5Sdrh       *apColl = multiSelectCollSeq(pParse, p, i);
25370342b1f5Sdrh       if( 0==*apColl ){
2538633e6d57Sdrh         *apColl = db->pDfltColl;
2539dc1bdc4fSdanielk1977       }
2540dc1bdc4fSdanielk1977     }
2541dc1bdc4fSdanielk1977 
25420342b1f5Sdrh     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
25430342b1f5Sdrh       for(i=0; i<2; i++){
2544b9bb7c18Sdrh         int addr = pLoop->addrOpenEphm[i];
25450342b1f5Sdrh         if( addr<0 ){
25460342b1f5Sdrh           /* If [0] is unused then [1] is also unused.  So we can
25470342b1f5Sdrh           ** always safely abort as soon as the first unused slot is found */
2548b9bb7c18Sdrh           assert( pLoop->addrOpenEphm[1]<0 );
25490342b1f5Sdrh           break;
25500342b1f5Sdrh         }
25510342b1f5Sdrh         sqlite3VdbeChangeP2(v, addr, nCol);
25522ec2fb22Sdrh         sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
25532ec2fb22Sdrh                             P4_KEYINFO);
25540ee5a1e7Sdrh         pLoop->addrOpenEphm[i] = -1;
25550342b1f5Sdrh       }
2556dc1bdc4fSdanielk1977     }
25572ec2fb22Sdrh     sqlite3KeyInfoUnref(pKeyInfo);
2558dc1bdc4fSdanielk1977   }
2559dc1bdc4fSdanielk1977 
2560dc1bdc4fSdanielk1977 multi_select_end:
25612b596da8Sdrh   pDest->iSdst = dest.iSdst;
25622b596da8Sdrh   pDest->nSdst = dest.nSdst;
2563633e6d57Sdrh   sqlite3SelectDelete(db, pDelete);
256484ac9d02Sdanielk1977   return rc;
25652282792aSdrh }
2566b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
25672282792aSdrh 
2568b21e7c70Sdrh /*
256989b31d73Smistachkin ** Error message for when two or more terms of a compound select have different
257089b31d73Smistachkin ** size result sets.
257189b31d73Smistachkin */
257289b31d73Smistachkin void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
257389b31d73Smistachkin   if( p->selFlags & SF_Values ){
257489b31d73Smistachkin     sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
257589b31d73Smistachkin   }else{
257689b31d73Smistachkin     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
257789b31d73Smistachkin       " do not have the same number of result columns", selectOpName(p->op));
257889b31d73Smistachkin   }
257989b31d73Smistachkin }
258089b31d73Smistachkin 
258189b31d73Smistachkin /*
2582b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a
2583b21e7c70Sdrh ** SELECT statment.
25840acb7e48Sdrh **
25852b596da8Sdrh ** The data to be output is contained in pIn->iSdst.  There are
25862b596da8Sdrh ** pIn->nSdst columns to be output.  pDest is where the output should
25870acb7e48Sdrh ** be sent.
25880acb7e48Sdrh **
25890acb7e48Sdrh ** regReturn is the number of the register holding the subroutine
25900acb7e48Sdrh ** return address.
25910acb7e48Sdrh **
2592f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that
25930acb7e48Sdrh ** records the previous output.  mem[regPrev] is a flag that is false
25940acb7e48Sdrh ** if there has been no previous output.  If regPrev>0 then code is
25950acb7e48Sdrh ** generated to suppress duplicates.  pKeyInfo is used for comparing
25960acb7e48Sdrh ** keys.
25970acb7e48Sdrh **
25980acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to
25990acb7e48Sdrh ** iBreak.
2600b21e7c70Sdrh */
26010acb7e48Sdrh static int generateOutputSubroutine(
260292b01d53Sdrh   Parse *pParse,          /* Parsing context */
260392b01d53Sdrh   Select *p,              /* The SELECT statement */
260492b01d53Sdrh   SelectDest *pIn,        /* Coroutine supplying data */
260592b01d53Sdrh   SelectDest *pDest,      /* Where to send the data */
260692b01d53Sdrh   int regReturn,          /* The return address register */
26070acb7e48Sdrh   int regPrev,            /* Previous result register.  No uniqueness if 0 */
26080acb7e48Sdrh   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
260992b01d53Sdrh   int iBreak              /* Jump here if we hit the LIMIT */
2610b21e7c70Sdrh ){
2611b21e7c70Sdrh   Vdbe *v = pParse->pVdbe;
261292b01d53Sdrh   int iContinue;
261392b01d53Sdrh   int addr;
2614b21e7c70Sdrh 
261592b01d53Sdrh   addr = sqlite3VdbeCurrentAddr(v);
261692b01d53Sdrh   iContinue = sqlite3VdbeMakeLabel(v);
26170acb7e48Sdrh 
26180acb7e48Sdrh   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
26190acb7e48Sdrh   */
26200acb7e48Sdrh   if( regPrev ){
2621728e0f91Sdrh     int addr1, addr2;
2622728e0f91Sdrh     addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
2623728e0f91Sdrh     addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
26242ec2fb22Sdrh                               (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
2625728e0f91Sdrh     sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
2626728e0f91Sdrh     sqlite3VdbeJumpHere(v, addr1);
2627e8e4af76Sdrh     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
2628ec86c724Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
26290acb7e48Sdrh   }
26301f9caa41Sdanielk1977   if( pParse->db->mallocFailed ) return 0;
26310acb7e48Sdrh 
2632d5578433Smistachkin   /* Suppress the first OFFSET entries if there is an OFFSET clause
26330acb7e48Sdrh   */
2634aa9ce707Sdrh   codeOffset(v, p->iOffset, iContinue);
2635b21e7c70Sdrh 
2636e2248cfdSdrh   assert( pDest->eDest!=SRT_Exists );
2637e2248cfdSdrh   assert( pDest->eDest!=SRT_Table );
2638b21e7c70Sdrh   switch( pDest->eDest ){
2639b21e7c70Sdrh     /* Store the result as data using a unique key.
2640b21e7c70Sdrh     */
2641b21e7c70Sdrh     case SRT_EphemTab: {
2642b21e7c70Sdrh       int r1 = sqlite3GetTempReg(pParse);
2643b21e7c70Sdrh       int r2 = sqlite3GetTempReg(pParse);
26442b596da8Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
26452b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
26462b596da8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
2647b21e7c70Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
2648b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r2);
2649b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
2650b21e7c70Sdrh       break;
2651b21e7c70Sdrh     }
2652b21e7c70Sdrh 
2653b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY
2654b21e7c70Sdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
2655b21e7c70Sdrh     ** then there should be a single item on the stack.  Write this
2656b21e7c70Sdrh     ** item into the set table with bogus data.
2657b21e7c70Sdrh     */
2658b21e7c70Sdrh     case SRT_Set: {
26596fccc35aSdrh       int r1;
26609af8646dSdrh       assert( pIn->nSdst==1 || pParse->nErr>0 );
2661634d81deSdrh       pDest->affSdst =
26622b596da8Sdrh          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
2663b21e7c70Sdrh       r1 = sqlite3GetTempReg(pParse);
2664634d81deSdrh       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
26652b596da8Sdrh       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
26662b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
2667b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
2668b21e7c70Sdrh       break;
2669b21e7c70Sdrh     }
2670b21e7c70Sdrh 
2671b21e7c70Sdrh     /* If this is a scalar select that is part of an expression, then
2672b21e7c70Sdrh     ** store the results in the appropriate memory cell and break out
2673b21e7c70Sdrh     ** of the scan loop.
2674b21e7c70Sdrh     */
2675b21e7c70Sdrh     case SRT_Mem: {
2676a276e3fdSdrh       assert( pIn->nSdst==1 || pParse->nErr>0 );  testcase( pIn->nSdst!=1 );
26772b596da8Sdrh       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
2678b21e7c70Sdrh       /* The LIMIT clause will jump out of the loop for us */
2679b21e7c70Sdrh       break;
2680b21e7c70Sdrh     }
2681b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
2682b21e7c70Sdrh 
26837d10d5a6Sdrh     /* The results are stored in a sequence of registers
26842b596da8Sdrh     ** starting at pDest->iSdst.  Then the co-routine yields.
2685b21e7c70Sdrh     */
268692b01d53Sdrh     case SRT_Coroutine: {
26872b596da8Sdrh       if( pDest->iSdst==0 ){
26882b596da8Sdrh         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
26892b596da8Sdrh         pDest->nSdst = pIn->nSdst;
2690b21e7c70Sdrh       }
26914b79bde7Sdan       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
26922b596da8Sdrh       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
269392b01d53Sdrh       break;
269492b01d53Sdrh     }
269592b01d53Sdrh 
2696ccfcbceaSdrh     /* If none of the above, then the result destination must be
2697ccfcbceaSdrh     ** SRT_Output.  This routine is never called with any other
2698ccfcbceaSdrh     ** destination other than the ones handled above or SRT_Output.
2699ccfcbceaSdrh     **
2700ccfcbceaSdrh     ** For SRT_Output, results are stored in a sequence of registers.
2701ccfcbceaSdrh     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
2702ccfcbceaSdrh     ** return the next row of result.
27037d10d5a6Sdrh     */
2704ccfcbceaSdrh     default: {
2705ccfcbceaSdrh       assert( pDest->eDest==SRT_Output );
27062b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
27072b596da8Sdrh       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
2708b21e7c70Sdrh       break;
2709b21e7c70Sdrh     }
2710b21e7c70Sdrh   }
271192b01d53Sdrh 
271292b01d53Sdrh   /* Jump to the end of the loop if the LIMIT is reached.
271392b01d53Sdrh   */
271492b01d53Sdrh   if( p->iLimit ){
271516897072Sdrh     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
271692b01d53Sdrh   }
271792b01d53Sdrh 
271892b01d53Sdrh   /* Generate the subroutine return
271992b01d53Sdrh   */
27200acb7e48Sdrh   sqlite3VdbeResolveLabel(v, iContinue);
272192b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
272292b01d53Sdrh 
272392b01d53Sdrh   return addr;
2724b21e7c70Sdrh }
2725b21e7c70Sdrh 
2726b21e7c70Sdrh /*
2727b21e7c70Sdrh ** Alternative compound select code generator for cases when there
2728b21e7c70Sdrh ** is an ORDER BY clause.
2729b21e7c70Sdrh **
2730b21e7c70Sdrh ** We assume a query of the following form:
2731b21e7c70Sdrh **
2732b21e7c70Sdrh **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
2733b21e7c70Sdrh **
2734b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
2735b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as
2736b21e7c70Sdrh ** co-routines.  Then run the co-routines in parallel and merge the results
2737b21e7c70Sdrh ** into the output.  In addition to the two coroutines (called selectA and
2738b21e7c70Sdrh ** selectB) there are 7 subroutines:
2739b21e7c70Sdrh **
2740b21e7c70Sdrh **    outA:    Move the output of the selectA coroutine into the output
2741b21e7c70Sdrh **             of the compound query.
2742b21e7c70Sdrh **
2743b21e7c70Sdrh **    outB:    Move the output of the selectB coroutine into the output
2744b21e7c70Sdrh **             of the compound query.  (Only generated for UNION and
2745b21e7c70Sdrh **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
2746b21e7c70Sdrh **             appears only in B.)
2747b21e7c70Sdrh **
2748b21e7c70Sdrh **    AltB:    Called when there is data from both coroutines and A<B.
2749b21e7c70Sdrh **
2750b21e7c70Sdrh **    AeqB:    Called when there is data from both coroutines and A==B.
2751b21e7c70Sdrh **
2752b21e7c70Sdrh **    AgtB:    Called when there is data from both coroutines and A>B.
2753b21e7c70Sdrh **
2754b21e7c70Sdrh **    EofA:    Called when data is exhausted from selectA.
2755b21e7c70Sdrh **
2756b21e7c70Sdrh **    EofB:    Called when data is exhausted from selectB.
2757b21e7c70Sdrh **
2758b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which
2759b21e7c70Sdrh ** <operator> is used:
2760b21e7c70Sdrh **
2761b21e7c70Sdrh **
2762b21e7c70Sdrh **             UNION ALL         UNION            EXCEPT          INTERSECT
2763b21e7c70Sdrh **          -------------  -----------------  --------------  -----------------
2764b21e7c70Sdrh **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
2765b21e7c70Sdrh **
27660acb7e48Sdrh **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
2767b21e7c70Sdrh **
2768b21e7c70Sdrh **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
2769b21e7c70Sdrh **
27700acb7e48Sdrh **   EofA:   outB, nextB      outB, nextB          halt             halt
2771b21e7c70Sdrh **
27720acb7e48Sdrh **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
27730acb7e48Sdrh **
27740acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
27750acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes
27760acb7e48Sdrh ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
27770acb7e48Sdrh ** following nextX causes a jump to the end of the select processing.
27780acb7e48Sdrh **
27790acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
27800acb7e48Sdrh ** within the output subroutine.  The regPrev register set holds the previously
27810acb7e48Sdrh ** output value.  A comparison is made against this value and the output
27820acb7e48Sdrh ** is skipped if the next results would be the same as the previous.
2783b21e7c70Sdrh **
2784b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven
2785b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom.  Like this:
2786b21e7c70Sdrh **
2787b21e7c70Sdrh **          goto Init
2788b21e7c70Sdrh **     coA: coroutine for left query (A)
2789b21e7c70Sdrh **     coB: coroutine for right query (B)
2790b21e7c70Sdrh **    outA: output one row of A
2791b21e7c70Sdrh **    outB: output one row of B (UNION and UNION ALL only)
2792b21e7c70Sdrh **    EofA: ...
2793b21e7c70Sdrh **    EofB: ...
2794b21e7c70Sdrh **    AltB: ...
2795b21e7c70Sdrh **    AeqB: ...
2796b21e7c70Sdrh **    AgtB: ...
2797b21e7c70Sdrh **    Init: initialize coroutine registers
2798b21e7c70Sdrh **          yield coA
2799b21e7c70Sdrh **          if eof(A) goto EofA
2800b21e7c70Sdrh **          yield coB
2801b21e7c70Sdrh **          if eof(B) goto EofB
2802b21e7c70Sdrh **    Cmpr: Compare A, B
2803b21e7c70Sdrh **          Jump AltB, AeqB, AgtB
2804b21e7c70Sdrh **     End: ...
2805b21e7c70Sdrh **
2806b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
2807b21e7c70Sdrh ** actually called using Gosub and they do not Return.  EofA and EofB loop
2808b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
2809b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB.
2810b21e7c70Sdrh */
2811de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
2812b21e7c70Sdrh static int multiSelectOrderBy(
2813b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
2814b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
2815a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
2816b21e7c70Sdrh ){
28170acb7e48Sdrh   int i, j;             /* Loop counters */
2818b21e7c70Sdrh   Select *pPrior;       /* Another SELECT immediately to our left */
2819b21e7c70Sdrh   Vdbe *v;              /* Generate code to this VDBE */
2820b21e7c70Sdrh   SelectDest destA;     /* Destination for coroutine A */
2821b21e7c70Sdrh   SelectDest destB;     /* Destination for coroutine B */
282292b01d53Sdrh   int regAddrA;         /* Address register for select-A coroutine */
282392b01d53Sdrh   int regAddrB;         /* Address register for select-B coroutine */
282492b01d53Sdrh   int addrSelectA;      /* Address of the select-A coroutine */
282592b01d53Sdrh   int addrSelectB;      /* Address of the select-B coroutine */
282692b01d53Sdrh   int regOutA;          /* Address register for the output-A subroutine */
282792b01d53Sdrh   int regOutB;          /* Address register for the output-B subroutine */
282892b01d53Sdrh   int addrOutA;         /* Address of the output-A subroutine */
2829b27b7f5dSdrh   int addrOutB = 0;     /* Address of the output-B subroutine */
283092b01d53Sdrh   int addrEofA;         /* Address of the select-A-exhausted subroutine */
283181cf13ecSdrh   int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
283292b01d53Sdrh   int addrEofB;         /* Address of the select-B-exhausted subroutine */
283392b01d53Sdrh   int addrAltB;         /* Address of the A<B subroutine */
283492b01d53Sdrh   int addrAeqB;         /* Address of the A==B subroutine */
283592b01d53Sdrh   int addrAgtB;         /* Address of the A>B subroutine */
283692b01d53Sdrh   int regLimitA;        /* Limit register for select-A */
283792b01d53Sdrh   int regLimitB;        /* Limit register for select-A */
28380acb7e48Sdrh   int regPrev;          /* A range of registers to hold previous output */
283992b01d53Sdrh   int savedLimit;       /* Saved value of p->iLimit */
284092b01d53Sdrh   int savedOffset;      /* Saved value of p->iOffset */
284192b01d53Sdrh   int labelCmpr;        /* Label for the start of the merge algorithm */
284292b01d53Sdrh   int labelEnd;         /* Label for the end of the overall SELECT stmt */
2843728e0f91Sdrh   int addr1;            /* Jump instructions that get retargetted */
284492b01d53Sdrh   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
284596067816Sdrh   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
28460acb7e48Sdrh   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
28470acb7e48Sdrh   sqlite3 *db;          /* Database connection */
28480acb7e48Sdrh   ExprList *pOrderBy;   /* The ORDER BY clause */
28490acb7e48Sdrh   int nOrderBy;         /* Number of terms in the ORDER BY clause */
28500acb7e48Sdrh   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
28517f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN
28527f61e92cSdan   int iSub1;            /* EQP id of left-hand query */
28537f61e92cSdan   int iSub2;            /* EQP id of right-hand query */
28547f61e92cSdan #endif
2855b21e7c70Sdrh 
285692b01d53Sdrh   assert( p->pOrderBy!=0 );
285796067816Sdrh   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
28580acb7e48Sdrh   db = pParse->db;
285992b01d53Sdrh   v = pParse->pVdbe;
2860ccfcbceaSdrh   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
286192b01d53Sdrh   labelEnd = sqlite3VdbeMakeLabel(v);
286292b01d53Sdrh   labelCmpr = sqlite3VdbeMakeLabel(v);
28630acb7e48Sdrh 
2864b21e7c70Sdrh 
286592b01d53Sdrh   /* Patch up the ORDER BY clause
286692b01d53Sdrh   */
286792b01d53Sdrh   op = p->op;
2868b21e7c70Sdrh   pPrior = p->pPrior;
286992b01d53Sdrh   assert( pPrior->pOrderBy==0 );
28700acb7e48Sdrh   pOrderBy = p->pOrderBy;
287193a960a0Sdrh   assert( pOrderBy );
28720acb7e48Sdrh   nOrderBy = pOrderBy->nExpr;
287393a960a0Sdrh 
28740acb7e48Sdrh   /* For operators other than UNION ALL we have to make sure that
28750acb7e48Sdrh   ** the ORDER BY clause covers every term of the result set.  Add
28760acb7e48Sdrh   ** terms to the ORDER BY clause as necessary.
28770acb7e48Sdrh   */
28780acb7e48Sdrh   if( op!=TK_ALL ){
28790acb7e48Sdrh     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
28807d10d5a6Sdrh       struct ExprList_item *pItem;
28817d10d5a6Sdrh       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
2882c2acc4e4Sdrh         assert( pItem->u.x.iOrderByCol>0 );
2883c2acc4e4Sdrh         if( pItem->u.x.iOrderByCol==i ) break;
28840acb7e48Sdrh       }
28850acb7e48Sdrh       if( j==nOrderBy ){
2886b7916a78Sdrh         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
2887fad3039cSmistachkin         if( pNew==0 ) return SQLITE_NOMEM_BKPT;
28880acb7e48Sdrh         pNew->flags |= EP_IntValue;
288933e619fcSdrh         pNew->u.iValue = i;
2890b7916a78Sdrh         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
2891c2acc4e4Sdrh         if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
28920acb7e48Sdrh       }
28930acb7e48Sdrh     }
28940acb7e48Sdrh   }
28950acb7e48Sdrh 
28960acb7e48Sdrh   /* Compute the comparison permutation and keyinfo that is used with
289710c081adSdrh   ** the permutation used to determine if the next
28980acb7e48Sdrh   ** row of results comes from selectA or selectB.  Also add explicit
28990acb7e48Sdrh   ** collations to the ORDER BY clause terms so that when the subqueries
29000acb7e48Sdrh   ** to the right and the left are evaluated, they use the correct
29010acb7e48Sdrh   ** collation.
29020acb7e48Sdrh   */
2903575fad65Sdrh   aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
29040acb7e48Sdrh   if( aPermute ){
29057d10d5a6Sdrh     struct ExprList_item *pItem;
2906b1702026Sdrh     aPermute[0] = nOrderBy;
2907b1702026Sdrh     for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
29086736618aSdrh       assert( pItem->u.x.iOrderByCol>0 );
29092ec18a3cSdrh       assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
2910c2acc4e4Sdrh       aPermute[i] = pItem->u.x.iOrderByCol - 1;
29110acb7e48Sdrh     }
291253bed45eSdan     pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
29130acb7e48Sdrh   }else{
29140acb7e48Sdrh     pKeyMerge = 0;
29150acb7e48Sdrh   }
29160acb7e48Sdrh 
29170acb7e48Sdrh   /* Reattach the ORDER BY clause to the query.
29180acb7e48Sdrh   */
29190acb7e48Sdrh   p->pOrderBy = pOrderBy;
29206ab3a2ecSdanielk1977   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
29210acb7e48Sdrh 
29220acb7e48Sdrh   /* Allocate a range of temporary registers and the KeyInfo needed
29230acb7e48Sdrh   ** for the logic that removes duplicate result rows when the
29240acb7e48Sdrh   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
29250acb7e48Sdrh   */
29260acb7e48Sdrh   if( op==TK_ALL ){
29270acb7e48Sdrh     regPrev = 0;
29280acb7e48Sdrh   }else{
29290acb7e48Sdrh     int nExpr = p->pEList->nExpr;
29301c0dc825Sdrh     assert( nOrderBy>=nExpr || db->mallocFailed );
2931c8ac0d16Sdrh     regPrev = pParse->nMem+1;
2932c8ac0d16Sdrh     pParse->nMem += nExpr+1;
29330acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
2934ad124329Sdrh     pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
29350acb7e48Sdrh     if( pKeyDup ){
29362ec2fb22Sdrh       assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
29370acb7e48Sdrh       for(i=0; i<nExpr; i++){
29380acb7e48Sdrh         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
29390acb7e48Sdrh         pKeyDup->aSortOrder[i] = 0;
29400acb7e48Sdrh       }
29410acb7e48Sdrh     }
29420acb7e48Sdrh   }
294392b01d53Sdrh 
294492b01d53Sdrh   /* Separate the left and the right query from one another
294592b01d53Sdrh   */
294692b01d53Sdrh   p->pPrior = 0;
2947d227a291Sdrh   pPrior->pNext = 0;
29487d10d5a6Sdrh   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
29490acb7e48Sdrh   if( pPrior->pPrior==0 ){
29507d10d5a6Sdrh     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
29510acb7e48Sdrh   }
295292b01d53Sdrh 
295392b01d53Sdrh   /* Compute the limit registers */
295492b01d53Sdrh   computeLimitRegisters(pParse, p, labelEnd);
29550acb7e48Sdrh   if( p->iLimit && op==TK_ALL ){
295692b01d53Sdrh     regLimitA = ++pParse->nMem;
295792b01d53Sdrh     regLimitB = ++pParse->nMem;
295892b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
295992b01d53Sdrh                                   regLimitA);
296092b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
296192b01d53Sdrh   }else{
296292b01d53Sdrh     regLimitA = regLimitB = 0;
296392b01d53Sdrh   }
2964633e6d57Sdrh   sqlite3ExprDelete(db, p->pLimit);
29650acb7e48Sdrh   p->pLimit = 0;
2966633e6d57Sdrh   sqlite3ExprDelete(db, p->pOffset);
29670acb7e48Sdrh   p->pOffset = 0;
296892b01d53Sdrh 
2969b21e7c70Sdrh   regAddrA = ++pParse->nMem;
2970b21e7c70Sdrh   regAddrB = ++pParse->nMem;
2971b21e7c70Sdrh   regOutA = ++pParse->nMem;
2972b21e7c70Sdrh   regOutB = ++pParse->nMem;
2973b21e7c70Sdrh   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
2974b21e7c70Sdrh   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
2975b21e7c70Sdrh 
297692b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement to the
29770acb7e48Sdrh   ** left of the compound operator - the "A" select.
29780acb7e48Sdrh   */
2979ed71a839Sdrh   addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
2980728e0f91Sdrh   addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
2981ed71a839Sdrh   VdbeComment((v, "left SELECT"));
298292b01d53Sdrh   pPrior->iLimit = regLimitA;
29837f61e92cSdan   explainSetInteger(iSub1, pParse->iNextSelectId);
29847d10d5a6Sdrh   sqlite3Select(pParse, pPrior, &destA);
29852fade2f7Sdrh   sqlite3VdbeEndCoroutine(v, regAddrA);
2986728e0f91Sdrh   sqlite3VdbeJumpHere(v, addr1);
2987b21e7c70Sdrh 
298892b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement on
298992b01d53Sdrh   ** the right - the "B" select
299092b01d53Sdrh   */
2991ed71a839Sdrh   addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
2992728e0f91Sdrh   addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
2993ed71a839Sdrh   VdbeComment((v, "right SELECT"));
299492b01d53Sdrh   savedLimit = p->iLimit;
299592b01d53Sdrh   savedOffset = p->iOffset;
299692b01d53Sdrh   p->iLimit = regLimitB;
299792b01d53Sdrh   p->iOffset = 0;
29987f61e92cSdan   explainSetInteger(iSub2, pParse->iNextSelectId);
29997d10d5a6Sdrh   sqlite3Select(pParse, p, &destB);
300092b01d53Sdrh   p->iLimit = savedLimit;
300192b01d53Sdrh   p->iOffset = savedOffset;
30022fade2f7Sdrh   sqlite3VdbeEndCoroutine(v, regAddrB);
3003b21e7c70Sdrh 
300492b01d53Sdrh   /* Generate a subroutine that outputs the current row of the A
30050acb7e48Sdrh   ** select as the next output row of the compound select.
300692b01d53Sdrh   */
3007b21e7c70Sdrh   VdbeNoopComment((v, "Output routine for A"));
30080acb7e48Sdrh   addrOutA = generateOutputSubroutine(pParse,
30090acb7e48Sdrh                  p, &destA, pDest, regOutA,
30102ec2fb22Sdrh                  regPrev, pKeyDup, labelEnd);
3011b21e7c70Sdrh 
301292b01d53Sdrh   /* Generate a subroutine that outputs the current row of the B
30130acb7e48Sdrh   ** select as the next output row of the compound select.
301492b01d53Sdrh   */
30150acb7e48Sdrh   if( op==TK_ALL || op==TK_UNION ){
3016b21e7c70Sdrh     VdbeNoopComment((v, "Output routine for B"));
30170acb7e48Sdrh     addrOutB = generateOutputSubroutine(pParse,
30180acb7e48Sdrh                  p, &destB, pDest, regOutB,
30192ec2fb22Sdrh                  regPrev, pKeyDup, labelEnd);
30200acb7e48Sdrh   }
30212ec2fb22Sdrh   sqlite3KeyInfoUnref(pKeyDup);
3022b21e7c70Sdrh 
302392b01d53Sdrh   /* Generate a subroutine to run when the results from select A
302492b01d53Sdrh   ** are exhausted and only data in select B remains.
302592b01d53Sdrh   */
302692b01d53Sdrh   if( op==TK_EXCEPT || op==TK_INTERSECT ){
302781cf13ecSdrh     addrEofA_noB = addrEofA = labelEnd;
302892b01d53Sdrh   }else{
302981cf13ecSdrh     VdbeNoopComment((v, "eof-A subroutine"));
303081cf13ecSdrh     addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
303181cf13ecSdrh     addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
3032688852abSdrh                                      VdbeCoverage(v);
3033076e85f5Sdrh     sqlite3VdbeGoto(v, addrEofA);
3034c3489bbfSdrh     p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
3035b21e7c70Sdrh   }
3036b21e7c70Sdrh 
303792b01d53Sdrh   /* Generate a subroutine to run when the results from select B
303892b01d53Sdrh   ** are exhausted and only data in select A remains.
303992b01d53Sdrh   */
3040b21e7c70Sdrh   if( op==TK_INTERSECT ){
304192b01d53Sdrh     addrEofB = addrEofA;
304295aa47b1Sdrh     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
3043b21e7c70Sdrh   }else{
304492b01d53Sdrh     VdbeNoopComment((v, "eof-B subroutine"));
304581cf13ecSdrh     addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
3046688852abSdrh     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
3047076e85f5Sdrh     sqlite3VdbeGoto(v, addrEofB);
3048b21e7c70Sdrh   }
3049b21e7c70Sdrh 
305092b01d53Sdrh   /* Generate code to handle the case of A<B
305192b01d53Sdrh   */
3052b21e7c70Sdrh   VdbeNoopComment((v, "A-lt-B subroutine"));
30530acb7e48Sdrh   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
3054688852abSdrh   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
3055076e85f5Sdrh   sqlite3VdbeGoto(v, labelCmpr);
3056b21e7c70Sdrh 
305792b01d53Sdrh   /* Generate code to handle the case of A==B
305892b01d53Sdrh   */
3059b21e7c70Sdrh   if( op==TK_ALL ){
3060b21e7c70Sdrh     addrAeqB = addrAltB;
30610acb7e48Sdrh   }else if( op==TK_INTERSECT ){
30620acb7e48Sdrh     addrAeqB = addrAltB;
30630acb7e48Sdrh     addrAltB++;
306492b01d53Sdrh   }else{
3065b21e7c70Sdrh     VdbeNoopComment((v, "A-eq-B subroutine"));
30660acb7e48Sdrh     addrAeqB =
3067688852abSdrh     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
3068076e85f5Sdrh     sqlite3VdbeGoto(v, labelCmpr);
306992b01d53Sdrh   }
3070b21e7c70Sdrh 
307192b01d53Sdrh   /* Generate code to handle the case of A>B
307292b01d53Sdrh   */
3073b21e7c70Sdrh   VdbeNoopComment((v, "A-gt-B subroutine"));
3074b21e7c70Sdrh   addrAgtB = sqlite3VdbeCurrentAddr(v);
3075b21e7c70Sdrh   if( op==TK_ALL || op==TK_UNION ){
3076b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
307792b01d53Sdrh   }
3078688852abSdrh   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
3079076e85f5Sdrh   sqlite3VdbeGoto(v, labelCmpr);
3080b21e7c70Sdrh 
308192b01d53Sdrh   /* This code runs once to initialize everything.
308292b01d53Sdrh   */
3083728e0f91Sdrh   sqlite3VdbeJumpHere(v, addr1);
3084688852abSdrh   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
3085688852abSdrh   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
308692b01d53Sdrh 
308792b01d53Sdrh   /* Implement the main merge loop
308892b01d53Sdrh   */
308992b01d53Sdrh   sqlite3VdbeResolveLabel(v, labelCmpr);
30900acb7e48Sdrh   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
30912b596da8Sdrh   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
30922ec2fb22Sdrh                          (char*)pKeyMerge, P4_KEYINFO);
3093953f7611Sdrh   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
3094688852abSdrh   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
309592b01d53Sdrh 
309692b01d53Sdrh   /* Jump to the this point in order to terminate the query.
309792b01d53Sdrh   */
3098b21e7c70Sdrh   sqlite3VdbeResolveLabel(v, labelEnd);
3099b21e7c70Sdrh 
310092b01d53Sdrh   /* Set the number of output columns
310192b01d53Sdrh   */
31027d10d5a6Sdrh   if( pDest->eDest==SRT_Output ){
31030acb7e48Sdrh     Select *pFirst = pPrior;
310492b01d53Sdrh     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
31059a8941fcSdan     generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
3106b21e7c70Sdrh   }
310792b01d53Sdrh 
31080acb7e48Sdrh   /* Reassembly the compound query so that it will be freed correctly
31090acb7e48Sdrh   ** by the calling function */
31105e7ad508Sdanielk1977   if( p->pPrior ){
3111633e6d57Sdrh     sqlite3SelectDelete(db, p->pPrior);
31125e7ad508Sdanielk1977   }
31130acb7e48Sdrh   p->pPrior = pPrior;
3114d227a291Sdrh   pPrior->pNext = p;
311592b01d53Sdrh 
311692b01d53Sdrh   /*** TBD:  Insert subroutine calls to close cursors on incomplete
311792b01d53Sdrh   **** subqueries ****/
31187f61e92cSdan   explainComposite(pParse, p->op, iSub1, iSub2, 0);
31193dc4cc66Sdrh   return pParse->nErr!=0;
312092b01d53Sdrh }
3121de3e41e3Sdanielk1977 #endif
3122b21e7c70Sdrh 
31233514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
312417435752Sdrh /* Forward Declarations */
312517435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*);
3126d12b6363Sdrh static void substSelect(sqlite3*, Select *, int, ExprList*, int);
312717435752Sdrh 
31282282792aSdrh /*
3129832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
31306a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
313184e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
31326a3ea0e6Sdrh ** unchanged.)
3133832508b7Sdrh **
3134832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
3135832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
3136832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
3137832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
3138832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
3139832508b7Sdrh ** of the subquery rather the result set of the subquery.
3140832508b7Sdrh */
3141b7916a78Sdrh static Expr *substExpr(
314217435752Sdrh   sqlite3 *db,        /* Report malloc errors to this connection */
314317435752Sdrh   Expr *pExpr,        /* Expr in which substitution occurs */
314417435752Sdrh   int iTable,         /* Table to be substituted */
314517435752Sdrh   ExprList *pEList    /* Substitute expressions */
314617435752Sdrh ){
3147b7916a78Sdrh   if( pExpr==0 ) return 0;
314850350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
314950350a15Sdrh     if( pExpr->iColumn<0 ){
315050350a15Sdrh       pExpr->op = TK_NULL;
315150350a15Sdrh     }else{
3152832508b7Sdrh       Expr *pNew;
315384e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
31546ab3a2ecSdanielk1977       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
3155b7916a78Sdrh       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
3156b7916a78Sdrh       sqlite3ExprDelete(db, pExpr);
3157b7916a78Sdrh       pExpr = pNew;
315850350a15Sdrh     }
3159832508b7Sdrh   }else{
3160b7916a78Sdrh     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
3161b7916a78Sdrh     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
31626ab3a2ecSdanielk1977     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
3163d12b6363Sdrh       substSelect(db, pExpr->x.pSelect, iTable, pEList, 1);
31646ab3a2ecSdanielk1977     }else{
31656ab3a2ecSdanielk1977       substExprList(db, pExpr->x.pList, iTable, pEList);
31666ab3a2ecSdanielk1977     }
3167832508b7Sdrh   }
3168b7916a78Sdrh   return pExpr;
3169832508b7Sdrh }
317017435752Sdrh static void substExprList(
317117435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
317217435752Sdrh   ExprList *pList,     /* List to scan and in which to make substitutes */
317317435752Sdrh   int iTable,          /* Table to be substituted */
317417435752Sdrh   ExprList *pEList     /* Substitute values */
317517435752Sdrh ){
3176832508b7Sdrh   int i;
3177832508b7Sdrh   if( pList==0 ) return;
3178832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
3179b7916a78Sdrh     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
3180832508b7Sdrh   }
3181832508b7Sdrh }
318217435752Sdrh static void substSelect(
318317435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
318417435752Sdrh   Select *p,           /* SELECT statement in which to make substitutions */
318517435752Sdrh   int iTable,          /* Table to be replaced */
3186d12b6363Sdrh   ExprList *pEList,    /* Substitute values */
3187d12b6363Sdrh   int doPrior          /* Do substitutes on p->pPrior too */
318817435752Sdrh ){
3189588a9a1aSdrh   SrcList *pSrc;
3190588a9a1aSdrh   struct SrcList_item *pItem;
3191588a9a1aSdrh   int i;
3192b3bce662Sdanielk1977   if( !p ) return;
3193d12b6363Sdrh   do{
319417435752Sdrh     substExprList(db, p->pEList, iTable, pEList);
319517435752Sdrh     substExprList(db, p->pGroupBy, iTable, pEList);
319617435752Sdrh     substExprList(db, p->pOrderBy, iTable, pEList);
3197b7916a78Sdrh     p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
3198b7916a78Sdrh     p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
3199588a9a1aSdrh     pSrc = p->pSrc;
32002906490bSdrh     assert( pSrc!=0 );
3201588a9a1aSdrh     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
3202d12b6363Sdrh       substSelect(db, pItem->pSelect, iTable, pEList, 1);
3203d12b6363Sdrh       if( pItem->fg.isTabFunc ){
3204d12b6363Sdrh         substExprList(db, pItem->u1.pFuncArg, iTable, pEList);
3205588a9a1aSdrh       }
3206588a9a1aSdrh     }
3207d12b6363Sdrh   }while( doPrior && (p = p->pPrior)!=0 );
3208b3bce662Sdanielk1977 }
32093514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
3210832508b7Sdrh 
32113514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3212832508b7Sdrh /*
3213630d296cSdrh ** This routine attempts to flatten subqueries as a performance optimization.
3214630d296cSdrh ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
32151350b030Sdrh **
32161350b030Sdrh ** To understand the concept of flattening, consider the following
32171350b030Sdrh ** query:
32181350b030Sdrh **
32191350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
32201350b030Sdrh **
32211350b030Sdrh ** The default way of implementing this query is to execute the
32221350b030Sdrh ** subquery first and store the results in a temporary table, then
32231350b030Sdrh ** run the outer query on that temporary table.  This requires two
32241350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
32251350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
3226832508b7Sdrh ** optimized.
32271350b030Sdrh **
3228832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
32291350b030Sdrh ** a single flat select, like this:
32301350b030Sdrh **
32311350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
32321350b030Sdrh **
323360ec914cSpeter.d.reid ** The code generated for this simplification gives the same result
3234832508b7Sdrh ** but only has to scan the data once.  And because indices might
3235832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
3236832508b7Sdrh ** avoided.
32371350b030Sdrh **
3238832508b7Sdrh ** Flattening is only attempted if all of the following are true:
32391350b030Sdrh **
3240832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
32411350b030Sdrh **
3242885a5b03Sdrh **   (2)  The subquery is not an aggregate or (2a) the outer query is not a join
3243885a5b03Sdrh **        and (2b) the outer query does not use subqueries other than the one
3244885a5b03Sdrh **        FROM-clause subquery that is a candidate for flattening.  (2b is
3245885a5b03Sdrh **        due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
3246832508b7Sdrh **
32472b300d5dSdrh **   (3)  The subquery is not the right operand of a left outer join
324849ad330dSdan **        (Originally ticket #306.  Strengthened by ticket #3300)
3249832508b7Sdrh **
325049ad330dSdan **   (4)  The subquery is not DISTINCT.
3251832508b7Sdrh **
325249ad330dSdan **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
325349ad330dSdan **        sub-queries that were excluded from this optimization. Restriction
325449ad330dSdan **        (4) has since been expanded to exclude all DISTINCT subqueries.
3255832508b7Sdrh **
3256832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
3257832508b7Sdrh **        DISTINCT.
3258832508b7Sdrh **
3259630d296cSdrh **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
3260630d296cSdrh **        A FROM clause, consider adding a FROM close with the special
3261630d296cSdrh **        table sqlite_once that consists of a single row containing a
3262630d296cSdrh **        single NULL.
326308192d5fSdrh **
3264df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
3265df199a25Sdrh **
3266df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
3267df199a25Sdrh **        aggregates.
3268df199a25Sdrh **
32696092d2bcSdrh **  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
32706092d2bcSdrh **        accidently carried the comment forward until 2014-09-15.  Original
327138b4149cSdrh **        text: "The subquery does not use aggregates or the outer query
327238b4149cSdrh **        does not use LIMIT."
3273df199a25Sdrh **
3274174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
3275174b6195Sdrh **
32767b688edeSdrh **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
32772b300d5dSdrh **        a separate restriction deriving from ticket #350.
32783fc673e6Sdrh **
327949ad330dSdan **  (13)  The subquery and outer query do not both use LIMIT.
3280ac83963aSdrh **
328149ad330dSdan **  (14)  The subquery does not use OFFSET.
3282ac83963aSdrh **
3283ad91c6cdSdrh **  (15)  The outer query is not part of a compound select or the
3284f3913278Sdrh **        subquery does not have a LIMIT clause.
3285f3913278Sdrh **        (See ticket #2339 and ticket [02a8e81d44]).
3286ad91c6cdSdrh **
3287c52e355dSdrh **  (16)  The outer query is not an aggregate or the subquery does
3288c52e355dSdrh **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
3289c52e355dSdrh **        until we introduced the group_concat() function.
3290c52e355dSdrh **
3291f23329a2Sdanielk1977 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
32924914cf92Sdanielk1977 **        compound clause made up entirely of non-aggregate queries, and
3293f23329a2Sdanielk1977 **        the parent query:
3294f23329a2Sdanielk1977 **
3295f23329a2Sdanielk1977 **          * is not itself part of a compound select,
3296f23329a2Sdanielk1977 **          * is not an aggregate or DISTINCT query, and
3297630d296cSdrh **          * is not a join
3298f23329a2Sdanielk1977 **
32994914cf92Sdanielk1977 **        The parent and sub-query may contain WHERE clauses. Subject to
33004914cf92Sdanielk1977 **        rules (11), (13) and (14), they may also contain ORDER BY,
3301630d296cSdrh **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
3302630d296cSdrh **        operator other than UNION ALL because all the other compound
3303630d296cSdrh **        operators have an implied DISTINCT which is disallowed by
3304630d296cSdrh **        restriction (4).
3305f23329a2Sdanielk1977 **
330667c70142Sdan **        Also, each component of the sub-query must return the same number
330767c70142Sdan **        of result columns. This is actually a requirement for any compound
330867c70142Sdan **        SELECT statement, but all the code here does is make sure that no
330967c70142Sdan **        such (illegal) sub-query is flattened. The caller will detect the
331067c70142Sdan **        syntax error and return a detailed message.
331167c70142Sdan **
331249fc1f60Sdanielk1977 **  (18)  If the sub-query is a compound select, then all terms of the
331349fc1f60Sdanielk1977 **        ORDER by clause of the parent must be simple references to
331449fc1f60Sdanielk1977 **        columns of the sub-query.
331549fc1f60Sdanielk1977 **
3316229cf702Sdrh **  (19)  The subquery does not use LIMIT or the outer query does not
3317229cf702Sdrh **        have a WHERE clause.
3318229cf702Sdrh **
3319e8902a70Sdrh **  (20)  If the sub-query is a compound select, then it must not use
3320e8902a70Sdrh **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
3321e8902a70Sdrh **        somewhat by saying that the terms of the ORDER BY clause must
3322630d296cSdrh **        appear as unmodified result columns in the outer query.  But we
3323e8902a70Sdrh **        have other optimizations in mind to deal with that case.
3324e8902a70Sdrh **
3325a91491e5Sshaneh **  (21)  The subquery does not use LIMIT or the outer query is not
3326a91491e5Sshaneh **        DISTINCT.  (See ticket [752e1646fc]).
3327a91491e5Sshaneh **
33288290c2adSdan **  (22)  The subquery is not a recursive CTE.
33298290c2adSdan **
33308290c2adSdan **  (23)  The parent is not a recursive CTE, or the sub-query is not a
33318290c2adSdan **        compound query. This restriction is because transforming the
33328290c2adSdan **        parent to a compound query confuses the code that handles
33338290c2adSdan **        recursive queries in multiSelect().
33348290c2adSdan **
33359588ad95Sdrh **  (24)  The subquery is not an aggregate that uses the built-in min() or
33369588ad95Sdrh **        or max() functions.  (Without this restriction, a query like:
33379588ad95Sdrh **        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
33389588ad95Sdrh **        return the value X for which Y was maximal.)
33399588ad95Sdrh **
33408290c2adSdan **
3341832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
3342832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
3343832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
3344832508b7Sdrh **
3345665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
3346832508b7Sdrh ** If flattening is attempted this routine returns 1.
3347832508b7Sdrh **
3348832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
3349832508b7Sdrh ** the subquery before this routine runs.
33501350b030Sdrh */
33518c74a8caSdrh static int flattenSubquery(
3352524cc21eSdanielk1977   Parse *pParse,       /* Parsing context */
33538c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
33548c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
33558c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
33568c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
33578c74a8caSdrh ){
3358524cc21eSdanielk1977   const char *zSavedAuthContext = pParse->zAuthContext;
3359d12b6363Sdrh   Select *pParent;    /* Current UNION ALL term of the other query */
33600bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
3361f23329a2Sdanielk1977   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
3362ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
3363ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
33640bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
33656a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
336691bb0eedSdrh   int i;              /* Loop counter */
336791bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
336891bb0eedSdrh   struct SrcList_item *pSubitem;   /* The subquery */
3369524cc21eSdanielk1977   sqlite3 *db = pParse->db;
33701350b030Sdrh 
3371832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
3372832508b7Sdrh   */
3373a78c22c4Sdrh   assert( p!=0 );
3374a78c22c4Sdrh   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
33757e5418e4Sdrh   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
3376832508b7Sdrh   pSrc = p->pSrc;
3377ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
337891bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
337949fc1f60Sdanielk1977   iParent = pSubitem->iCursor;
338091bb0eedSdrh   pSub = pSubitem->pSelect;
3381832508b7Sdrh   assert( pSub!=0 );
3382885a5b03Sdrh   if( subqueryIsAgg ){
3383885a5b03Sdrh     if( isAgg ) return 0;                                /* Restriction (1)   */
3384885a5b03Sdrh     if( pSrc->nSrc>1 ) return 0;                         /* Restriction (2a)  */
3385885a5b03Sdrh     if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
33862308ed38Sdrh      || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
33872308ed38Sdrh      || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
3388885a5b03Sdrh     ){
3389885a5b03Sdrh       return 0;                                          /* Restriction (2b)  */
3390885a5b03Sdrh     }
3391885a5b03Sdrh   }
3392885a5b03Sdrh 
3393832508b7Sdrh   pSubSrc = pSub->pSrc;
3394832508b7Sdrh   assert( pSubSrc );
3395ac83963aSdrh   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
339660ec914cSpeter.d.reid   ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
3397ac83963aSdrh   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
3398ac83963aSdrh   ** became arbitrary expressions, we were forced to add restrictions (13)
3399ac83963aSdrh   ** and (14). */
3400ac83963aSdrh   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
3401ac83963aSdrh   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
3402d227a291Sdrh   if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
3403ad91c6cdSdrh     return 0;                                            /* Restriction (15) */
3404ad91c6cdSdrh   }
3405ac83963aSdrh   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
340649ad330dSdan   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
340749ad330dSdan   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
340849ad330dSdan      return 0;         /* Restrictions (8)(9) */
3409df199a25Sdrh   }
34107d10d5a6Sdrh   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
34117d10d5a6Sdrh      return 0;         /* Restriction (6)  */
34127d10d5a6Sdrh   }
34137d10d5a6Sdrh   if( p->pOrderBy && pSub->pOrderBy ){
3414ac83963aSdrh      return 0;                                           /* Restriction (11) */
3415ac83963aSdrh   }
3416c52e355dSdrh   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
3417229cf702Sdrh   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
3418a91491e5Sshaneh   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
3419a91491e5Sshaneh      return 0;         /* Restriction (21) */
3420a91491e5Sshaneh   }
34219588ad95Sdrh   testcase( pSub->selFlags & SF_Recursive );
34229588ad95Sdrh   testcase( pSub->selFlags & SF_MinMaxAgg );
34239588ad95Sdrh   if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
34249588ad95Sdrh     return 0; /* Restrictions (22) and (24) */
34259588ad95Sdrh   }
34269588ad95Sdrh   if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
34279588ad95Sdrh     return 0; /* Restriction (23) */
34289588ad95Sdrh   }
3429832508b7Sdrh 
34302b300d5dSdrh   /* OBSOLETE COMMENT 1:
34312b300d5dSdrh   ** Restriction 3:  If the subquery is a join, make sure the subquery is
34328af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
34338af4d3acSdrh   ** is not allowed:
34348af4d3acSdrh   **
34358af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
34368af4d3acSdrh   **
34378af4d3acSdrh   ** If we flatten the above, we would get
34388af4d3acSdrh   **
34398af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
34408af4d3acSdrh   **
34418af4d3acSdrh   ** which is not at all the same thing.
34422b300d5dSdrh   **
34432b300d5dSdrh   ** OBSOLETE COMMENT 2:
34442b300d5dSdrh   ** Restriction 12:  If the subquery is the right operand of a left outer
34453fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
34463fc673e6Sdrh   ** An examples of why this is not allowed:
34473fc673e6Sdrh   **
34483fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
34493fc673e6Sdrh   **
34503fc673e6Sdrh   ** If we flatten the above, we would get
34513fc673e6Sdrh   **
34523fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
34533fc673e6Sdrh   **
34543fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
34553fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
34562b300d5dSdrh   **
34572b300d5dSdrh   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
34582b300d5dSdrh   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
34592b300d5dSdrh   ** is fraught with danger.  Best to avoid the whole thing.  If the
34602b300d5dSdrh   ** subquery is the right term of a LEFT JOIN, then do not flatten.
34613fc673e6Sdrh   */
34628a48b9c0Sdrh   if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
34633fc673e6Sdrh     return 0;
34643fc673e6Sdrh   }
34653fc673e6Sdrh 
3466f23329a2Sdanielk1977   /* Restriction 17: If the sub-query is a compound SELECT, then it must
3467f23329a2Sdanielk1977   ** use only the UNION ALL operator. And none of the simple select queries
3468f23329a2Sdanielk1977   ** that make up the compound SELECT are allowed to be aggregate or distinct
3469f23329a2Sdanielk1977   ** queries.
3470f23329a2Sdanielk1977   */
3471f23329a2Sdanielk1977   if( pSub->pPrior ){
3472e8902a70Sdrh     if( pSub->pOrderBy ){
3473e8902a70Sdrh       return 0;  /* Restriction 20 */
3474e8902a70Sdrh     }
3475e2f02bacSdrh     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
3476f23329a2Sdanielk1977       return 0;
3477f23329a2Sdanielk1977     }
3478f23329a2Sdanielk1977     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
3479ccfcbceaSdrh       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
3480ccfcbceaSdrh       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
34814b3ac73cSdrh       assert( pSub->pSrc!=0 );
34822ec18a3cSdrh       assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
34837d10d5a6Sdrh       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
348480b3c548Sdanielk1977        || (pSub1->pPrior && pSub1->op!=TK_ALL)
34854b3ac73cSdrh        || pSub1->pSrc->nSrc<1
348680b3c548Sdanielk1977       ){
3487f23329a2Sdanielk1977         return 0;
3488f23329a2Sdanielk1977       }
34894b3ac73cSdrh       testcase( pSub1->pSrc->nSrc>1 );
3490f23329a2Sdanielk1977     }
349149fc1f60Sdanielk1977 
349249fc1f60Sdanielk1977     /* Restriction 18. */
349349fc1f60Sdanielk1977     if( p->pOrderBy ){
349449fc1f60Sdanielk1977       int ii;
349549fc1f60Sdanielk1977       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
3496c2acc4e4Sdrh         if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
349749fc1f60Sdanielk1977       }
349849fc1f60Sdanielk1977     }
3499f23329a2Sdanielk1977   }
3500f23329a2Sdanielk1977 
35017d10d5a6Sdrh   /***** If we reach this point, flattening is permitted. *****/
3502eb9b884cSdrh   SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
3503eb9b884cSdrh                    pSub->zSelName, pSub, iFrom));
35047d10d5a6Sdrh 
35057d10d5a6Sdrh   /* Authorize the subquery */
3506524cc21eSdanielk1977   pParse->zAuthContext = pSubitem->zName;
3507a2acb0d7Sdrh   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
3508a2acb0d7Sdrh   testcase( i==SQLITE_DENY );
3509524cc21eSdanielk1977   pParse->zAuthContext = zSavedAuthContext;
3510524cc21eSdanielk1977 
35117d10d5a6Sdrh   /* If the sub-query is a compound SELECT statement, then (by restrictions
35127d10d5a6Sdrh   ** 17 and 18 above) it must be a UNION ALL and the parent query must
35137d10d5a6Sdrh   ** be of the form:
3514f23329a2Sdanielk1977   **
3515f23329a2Sdanielk1977   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
3516f23329a2Sdanielk1977   **
3517f23329a2Sdanielk1977   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
3518a78c22c4Sdrh   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
3519f23329a2Sdanielk1977   ** OFFSET clauses and joins them to the left-hand-side of the original
3520f23329a2Sdanielk1977   ** using UNION ALL operators. In this case N is the number of simple
3521f23329a2Sdanielk1977   ** select statements in the compound sub-query.
3522a78c22c4Sdrh   **
3523a78c22c4Sdrh   ** Example:
3524a78c22c4Sdrh   **
3525a78c22c4Sdrh   **     SELECT a+1 FROM (
3526a78c22c4Sdrh   **        SELECT x FROM tab
3527a78c22c4Sdrh   **        UNION ALL
3528a78c22c4Sdrh   **        SELECT y FROM tab
3529a78c22c4Sdrh   **        UNION ALL
3530a78c22c4Sdrh   **        SELECT abs(z*2) FROM tab2
3531a78c22c4Sdrh   **     ) WHERE a!=5 ORDER BY 1
3532a78c22c4Sdrh   **
3533a78c22c4Sdrh   ** Transformed into:
3534a78c22c4Sdrh   **
3535a78c22c4Sdrh   **     SELECT x+1 FROM tab WHERE x+1!=5
3536a78c22c4Sdrh   **     UNION ALL
3537a78c22c4Sdrh   **     SELECT y+1 FROM tab WHERE y+1!=5
3538a78c22c4Sdrh   **     UNION ALL
3539a78c22c4Sdrh   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
3540a78c22c4Sdrh   **     ORDER BY 1
3541a78c22c4Sdrh   **
3542a78c22c4Sdrh   ** We call this the "compound-subquery flattening".
3543f23329a2Sdanielk1977   */
3544f23329a2Sdanielk1977   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
3545f23329a2Sdanielk1977     Select *pNew;
3546f23329a2Sdanielk1977     ExprList *pOrderBy = p->pOrderBy;
35474b86ef1dSdanielk1977     Expr *pLimit = p->pLimit;
3548547180baSdrh     Expr *pOffset = p->pOffset;
3549f23329a2Sdanielk1977     Select *pPrior = p->pPrior;
3550f23329a2Sdanielk1977     p->pOrderBy = 0;
3551f23329a2Sdanielk1977     p->pSrc = 0;
3552f23329a2Sdanielk1977     p->pPrior = 0;
35534b86ef1dSdanielk1977     p->pLimit = 0;
3554547180baSdrh     p->pOffset = 0;
35556ab3a2ecSdanielk1977     pNew = sqlite3SelectDup(db, p, 0);
3556eb9b884cSdrh     sqlite3SelectSetName(pNew, pSub->zSelName);
3557547180baSdrh     p->pOffset = pOffset;
35584b86ef1dSdanielk1977     p->pLimit = pLimit;
3559a78c22c4Sdrh     p->pOrderBy = pOrderBy;
3560a78c22c4Sdrh     p->pSrc = pSrc;
3561a78c22c4Sdrh     p->op = TK_ALL;
3562a78c22c4Sdrh     if( pNew==0 ){
3563d227a291Sdrh       p->pPrior = pPrior;
3564a78c22c4Sdrh     }else{
3565a78c22c4Sdrh       pNew->pPrior = pPrior;
3566d227a291Sdrh       if( pPrior ) pPrior->pNext = pNew;
3567d227a291Sdrh       pNew->pNext = p;
3568a78c22c4Sdrh       p->pPrior = pNew;
3569eb9b884cSdrh       SELECTTRACE(2,pParse,p,
3570eb9b884cSdrh          ("compound-subquery flattener creates %s.%p as peer\n",
3571eb9b884cSdrh          pNew->zSelName, pNew));
3572d227a291Sdrh     }
3573a78c22c4Sdrh     if( db->mallocFailed ) return 1;
3574a78c22c4Sdrh   }
3575f23329a2Sdanielk1977 
35767d10d5a6Sdrh   /* Begin flattening the iFrom-th entry of the FROM clause
35777d10d5a6Sdrh   ** in the outer query.
3578832508b7Sdrh   */
3579f23329a2Sdanielk1977   pSub = pSub1 = pSubitem->pSelect;
3580c31c2eb8Sdrh 
3581a78c22c4Sdrh   /* Delete the transient table structure associated with the
3582a78c22c4Sdrh   ** subquery
3583a78c22c4Sdrh   */
3584a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zDatabase);
3585a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zName);
3586a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zAlias);
3587a78c22c4Sdrh   pSubitem->zDatabase = 0;
3588a78c22c4Sdrh   pSubitem->zName = 0;
3589a78c22c4Sdrh   pSubitem->zAlias = 0;
3590a78c22c4Sdrh   pSubitem->pSelect = 0;
3591a78c22c4Sdrh 
3592a78c22c4Sdrh   /* Defer deleting the Table object associated with the
3593a78c22c4Sdrh   ** subquery until code generation is
3594a78c22c4Sdrh   ** complete, since there may still exist Expr.pTab entries that
3595a78c22c4Sdrh   ** refer to the subquery even after flattening.  Ticket #3346.
3596ccfcbceaSdrh   **
3597ccfcbceaSdrh   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
3598a78c22c4Sdrh   */
3599ccfcbceaSdrh   if( ALWAYS(pSubitem->pTab!=0) ){
3600a78c22c4Sdrh     Table *pTabToDel = pSubitem->pTab;
3601a78c22c4Sdrh     if( pTabToDel->nRef==1 ){
360265a7cd16Sdan       Parse *pToplevel = sqlite3ParseToplevel(pParse);
360365a7cd16Sdan       pTabToDel->pNextZombie = pToplevel->pZombieTab;
360465a7cd16Sdan       pToplevel->pZombieTab = pTabToDel;
3605a78c22c4Sdrh     }else{
3606a78c22c4Sdrh       pTabToDel->nRef--;
3607a78c22c4Sdrh     }
3608a78c22c4Sdrh     pSubitem->pTab = 0;
3609a78c22c4Sdrh   }
3610a78c22c4Sdrh 
3611a78c22c4Sdrh   /* The following loop runs once for each term in a compound-subquery
3612a78c22c4Sdrh   ** flattening (as described above).  If we are doing a different kind
3613a78c22c4Sdrh   ** of flattening - a flattening other than a compound-subquery flattening -
3614a78c22c4Sdrh   ** then this loop only runs once.
3615a78c22c4Sdrh   **
3616a78c22c4Sdrh   ** This loop moves all of the FROM elements of the subquery into the
3617c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
3618c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
3619c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
3620c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
3621c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
3622c31c2eb8Sdrh   ** elements we are now copying in.
3623c31c2eb8Sdrh   */
3624a78c22c4Sdrh   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
3625a78c22c4Sdrh     int nSubSrc;
3626ea678832Sdrh     u8 jointype = 0;
3627a78c22c4Sdrh     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
3628a78c22c4Sdrh     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
3629a78c22c4Sdrh     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
3630588a9a1aSdrh 
3631a78c22c4Sdrh     if( pSrc ){
3632a78c22c4Sdrh       assert( pParent==p );  /* First time through the loop */
36338a48b9c0Sdrh       jointype = pSubitem->fg.jointype;
3634588a9a1aSdrh     }else{
3635a78c22c4Sdrh       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
3636a78c22c4Sdrh       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
3637cfa063b3Sdrh       if( pSrc==0 ){
3638a78c22c4Sdrh         assert( db->mallocFailed );
3639a78c22c4Sdrh         break;
3640cfa063b3Sdrh       }
3641c31c2eb8Sdrh     }
3642a78c22c4Sdrh 
3643a78c22c4Sdrh     /* The subquery uses a single slot of the FROM clause of the outer
3644a78c22c4Sdrh     ** query.  If the subquery has more than one element in its FROM clause,
3645a78c22c4Sdrh     ** then expand the outer query to make space for it to hold all elements
3646a78c22c4Sdrh     ** of the subquery.
3647a78c22c4Sdrh     **
3648a78c22c4Sdrh     ** Example:
3649a78c22c4Sdrh     **
3650a78c22c4Sdrh     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
3651a78c22c4Sdrh     **
3652a78c22c4Sdrh     ** The outer query has 3 slots in its FROM clause.  One slot of the
3653a78c22c4Sdrh     ** outer query (the middle slot) is used by the subquery.  The next
3654d12b6363Sdrh     ** block of code will expand the outer query FROM clause to 4 slots.
3655d12b6363Sdrh     ** The middle slot is expanded to two slots in order to make space
3656d12b6363Sdrh     ** for the two elements in the FROM clause of the subquery.
3657a78c22c4Sdrh     */
3658a78c22c4Sdrh     if( nSubSrc>1 ){
3659a78c22c4Sdrh       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
3660a78c22c4Sdrh       if( db->mallocFailed ){
3661a78c22c4Sdrh         break;
3662c31c2eb8Sdrh       }
3663c31c2eb8Sdrh     }
3664a78c22c4Sdrh 
3665a78c22c4Sdrh     /* Transfer the FROM clause terms from the subquery into the
3666a78c22c4Sdrh     ** outer query.
3667a78c22c4Sdrh     */
3668c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
3669c3a8402aSdrh       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
367020292310Sdrh       assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
3671c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
3672c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
3673c31c2eb8Sdrh     }
36748a48b9c0Sdrh     pSrc->a[iFrom].fg.jointype = jointype;
3675c31c2eb8Sdrh 
3676c31c2eb8Sdrh     /* Now begin substituting subquery result set expressions for
3677c31c2eb8Sdrh     ** references to the iParent in the outer query.
3678c31c2eb8Sdrh     **
3679c31c2eb8Sdrh     ** Example:
3680c31c2eb8Sdrh     **
3681c31c2eb8Sdrh     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
3682c31c2eb8Sdrh     **   \                     \_____________ subquery __________/          /
3683c31c2eb8Sdrh     **    \_____________________ outer query ______________________________/
3684c31c2eb8Sdrh     **
3685c31c2eb8Sdrh     ** We look at every expression in the outer query and every place we see
3686c31c2eb8Sdrh     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
3687c31c2eb8Sdrh     */
3688f23329a2Sdanielk1977     pList = pParent->pEList;
3689832508b7Sdrh     for(i=0; i<pList->nExpr; i++){
3690ccfcbceaSdrh       if( pList->a[i].zName==0 ){
369142fbf321Sdrh         char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
369242fbf321Sdrh         sqlite3Dequote(zName);
369342fbf321Sdrh         pList->a[i].zName = zName;
3694832508b7Sdrh       }
3695ccfcbceaSdrh     }
3696174b6195Sdrh     if( pSub->pOrderBy ){
36977c0a4720Sdan       /* At this point, any non-zero iOrderByCol values indicate that the
36987c0a4720Sdan       ** ORDER BY column expression is identical to the iOrderByCol'th
36997c0a4720Sdan       ** expression returned by SELECT statement pSub. Since these values
37007c0a4720Sdan       ** do not necessarily correspond to columns in SELECT statement pParent,
37017c0a4720Sdan       ** zero them before transfering the ORDER BY clause.
37027c0a4720Sdan       **
37037c0a4720Sdan       ** Not doing this may cause an error if a subsequent call to this
37047c0a4720Sdan       ** function attempts to flatten a compound sub-query into pParent
37057c0a4720Sdan       ** (the only way this can happen is if the compound sub-query is
37067c0a4720Sdan       ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
37077c0a4720Sdan       ExprList *pOrderBy = pSub->pOrderBy;
37087c0a4720Sdan       for(i=0; i<pOrderBy->nExpr; i++){
37097c0a4720Sdan         pOrderBy->a[i].u.x.iOrderByCol = 0;
37107c0a4720Sdan       }
3711f23329a2Sdanielk1977       assert( pParent->pOrderBy==0 );
37127c0a4720Sdan       assert( pSub->pPrior==0 );
37137c0a4720Sdan       pParent->pOrderBy = pOrderBy;
3714174b6195Sdrh       pSub->pOrderBy = 0;
3715174b6195Sdrh     }
37166ab3a2ecSdanielk1977     pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
3717832508b7Sdrh     if( subqueryIsAgg ){
3718f23329a2Sdanielk1977       assert( pParent->pHaving==0 );
3719f23329a2Sdanielk1977       pParent->pHaving = pParent->pWhere;
3720f23329a2Sdanielk1977       pParent->pWhere = pWhere;
3721f23329a2Sdanielk1977       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
37226ab3a2ecSdanielk1977                                   sqlite3ExprDup(db, pSub->pHaving, 0));
3723f23329a2Sdanielk1977       assert( pParent->pGroupBy==0 );
37246ab3a2ecSdanielk1977       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
3725832508b7Sdrh     }else{
3726f23329a2Sdanielk1977       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
3727832508b7Sdrh     }
3728d12b6363Sdrh     substSelect(db, pParent, iParent, pSub->pEList, 0);
3729c31c2eb8Sdrh 
3730c31c2eb8Sdrh     /* The flattened query is distinct if either the inner or the
3731c31c2eb8Sdrh     ** outer query is distinct.
3732c31c2eb8Sdrh     */
37337d10d5a6Sdrh     pParent->selFlags |= pSub->selFlags & SF_Distinct;
37348c74a8caSdrh 
3735a58fdfb1Sdanielk1977     /*
3736a58fdfb1Sdanielk1977     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
3737ac83963aSdrh     **
3738ac83963aSdrh     ** One is tempted to try to add a and b to combine the limits.  But this
3739ac83963aSdrh     ** does not work if either limit is negative.
3740a58fdfb1Sdanielk1977     */
3741a2dc3b1aSdanielk1977     if( pSub->pLimit ){
3742f23329a2Sdanielk1977       pParent->pLimit = pSub->pLimit;
3743a2dc3b1aSdanielk1977       pSub->pLimit = 0;
3744df199a25Sdrh     }
3745f23329a2Sdanielk1977   }
37468c74a8caSdrh 
3747c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
3748c31c2eb8Sdrh   ** success.
3749c31c2eb8Sdrh   */
3750633e6d57Sdrh   sqlite3SelectDelete(db, pSub1);
3751f23329a2Sdanielk1977 
3752c90713d3Sdrh #if SELECTTRACE_ENABLED
3753c90713d3Sdrh   if( sqlite3SelectTrace & 0x100 ){
3754bc8edba1Sdrh     SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
3755c90713d3Sdrh     sqlite3TreeViewSelect(0, p, 0);
3756c90713d3Sdrh   }
3757c90713d3Sdrh #endif
3758c90713d3Sdrh 
3759832508b7Sdrh   return 1;
37601350b030Sdrh }
37613514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
37621350b030Sdrh 
376369b72d5aSdrh 
376469b72d5aSdrh 
376569b72d5aSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
376669b72d5aSdrh /*
376769b72d5aSdrh ** Make copies of relevant WHERE clause terms of the outer query into
376869b72d5aSdrh ** the WHERE clause of subquery.  Example:
376969b72d5aSdrh **
377069b72d5aSdrh **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
377169b72d5aSdrh **
377269b72d5aSdrh ** Transformed into:
377369b72d5aSdrh **
377469b72d5aSdrh **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
377569b72d5aSdrh **     WHERE x=5 AND y=10;
377669b72d5aSdrh **
377769b72d5aSdrh ** The hope is that the terms added to the inner query will make it more
377869b72d5aSdrh ** efficient.
377969b72d5aSdrh **
378069b72d5aSdrh ** Do not attempt this optimization if:
378169b72d5aSdrh **
378269b72d5aSdrh **   (1) The inner query is an aggregate.  (In that case, we'd really want
378369b72d5aSdrh **       to copy the outer WHERE-clause terms onto the HAVING clause of the
378469b72d5aSdrh **       inner query.  But they probably won't help there so do not bother.)
378569b72d5aSdrh **
378669b72d5aSdrh **   (2) The inner query is the recursive part of a common table expression.
378769b72d5aSdrh **
378869b72d5aSdrh **   (3) The inner query has a LIMIT clause (since the changes to the WHERE
378969b72d5aSdrh **       close would change the meaning of the LIMIT).
379069b72d5aSdrh **
379169b72d5aSdrh **   (4) The inner query is the right operand of a LEFT JOIN.  (The caller
379269b72d5aSdrh **       enforces this restriction since this routine does not have enough
379369b72d5aSdrh **       information to know.)
379469b72d5aSdrh **
379538978dd4Sdrh **   (5) The WHERE clause expression originates in the ON or USING clause
379638978dd4Sdrh **       of a LEFT JOIN.
379738978dd4Sdrh **
379869b72d5aSdrh ** Return 0 if no changes are made and non-zero if one or more WHERE clause
379969b72d5aSdrh ** terms are duplicated into the subquery.
380069b72d5aSdrh */
380169b72d5aSdrh static int pushDownWhereTerms(
380269b72d5aSdrh   sqlite3 *db,          /* The database connection (for malloc()) */
380369b72d5aSdrh   Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
380469b72d5aSdrh   Expr *pWhere,         /* The WHERE clause of the outer query */
380569b72d5aSdrh   int iCursor           /* Cursor number of the subquery */
380669b72d5aSdrh ){
380769b72d5aSdrh   Expr *pNew;
380869b72d5aSdrh   int nChng = 0;
3809b1ec87afSdrh   Select *pX;           /* For looping over compound SELECTs in pSubq */
381069b72d5aSdrh   if( pWhere==0 ) return 0;
3811b1ec87afSdrh   for(pX=pSubq; pX; pX=pX->pPrior){
3812b1ec87afSdrh     if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
3813b1ec87afSdrh       testcase( pX->selFlags & SF_Aggregate );
3814b1ec87afSdrh       testcase( pX->selFlags & SF_Recursive );
3815b1ec87afSdrh       testcase( pX!=pSubq );
381669b72d5aSdrh       return 0; /* restrictions (1) and (2) */
381769b72d5aSdrh     }
3818b1ec87afSdrh   }
381969b72d5aSdrh   if( pSubq->pLimit!=0 ){
382069b72d5aSdrh     return 0; /* restriction (3) */
382169b72d5aSdrh   }
382269b72d5aSdrh   while( pWhere->op==TK_AND ){
382369b72d5aSdrh     nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
382469b72d5aSdrh     pWhere = pWhere->pLeft;
382569b72d5aSdrh   }
382638978dd4Sdrh   if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
382769b72d5aSdrh   if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
382869b72d5aSdrh     nChng++;
382969b72d5aSdrh     while( pSubq ){
383069b72d5aSdrh       pNew = sqlite3ExprDup(db, pWhere, 0);
383169b72d5aSdrh       pNew = substExpr(db, pNew, iCursor, pSubq->pEList);
383269b72d5aSdrh       pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew);
383369b72d5aSdrh       pSubq = pSubq->pPrior;
383469b72d5aSdrh     }
383569b72d5aSdrh   }
383669b72d5aSdrh   return nChng;
383769b72d5aSdrh }
383869b72d5aSdrh #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
383969b72d5aSdrh 
38401350b030Sdrh /*
38414ac391fcSdan ** Based on the contents of the AggInfo structure indicated by the first
38424ac391fcSdan ** argument, this function checks if the following are true:
3843a9d1ccb9Sdanielk1977 **
38444ac391fcSdan **    * the query contains just a single aggregate function,
38454ac391fcSdan **    * the aggregate function is either min() or max(), and
38464ac391fcSdan **    * the argument to the aggregate function is a column value.
3847738bdcfbSdanielk1977 **
38484ac391fcSdan ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
38494ac391fcSdan ** is returned as appropriate. Also, *ppMinMax is set to point to the
38504ac391fcSdan ** list of arguments passed to the aggregate before returning.
38514ac391fcSdan **
38524ac391fcSdan ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
38534ac391fcSdan ** WHERE_ORDERBY_NORMAL is returned.
3854a9d1ccb9Sdanielk1977 */
38554ac391fcSdan static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
38564ac391fcSdan   int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
3857a9d1ccb9Sdanielk1977 
38584ac391fcSdan   *ppMinMax = 0;
38594ac391fcSdan   if( pAggInfo->nFunc==1 ){
38604ac391fcSdan     Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
38614ac391fcSdan     ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
38624ac391fcSdan 
38634ac391fcSdan     assert( pExpr->op==TK_AGG_FUNCTION );
38644ac391fcSdan     if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
38654ac391fcSdan       const char *zFunc = pExpr->u.zToken;
38664ac391fcSdan       if( sqlite3StrICmp(zFunc, "min")==0 ){
38674ac391fcSdan         eRet = WHERE_ORDERBY_MIN;
38684ac391fcSdan         *ppMinMax = pEList;
38694ac391fcSdan       }else if( sqlite3StrICmp(zFunc, "max")==0 ){
38704ac391fcSdan         eRet = WHERE_ORDERBY_MAX;
38714ac391fcSdan         *ppMinMax = pEList;
3872a9d1ccb9Sdanielk1977       }
38734ac391fcSdan     }
38744ac391fcSdan   }
38754ac391fcSdan 
38764ac391fcSdan   assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
38774ac391fcSdan   return eRet;
3878a9d1ccb9Sdanielk1977 }
3879a9d1ccb9Sdanielk1977 
3880a9d1ccb9Sdanielk1977 /*
3881a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query.
388260ec914cSpeter.d.reid ** The second argument is the associated aggregate-info object. This
3883a5533162Sdanielk1977 ** function tests if the SELECT is of the form:
3884a5533162Sdanielk1977 **
3885a5533162Sdanielk1977 **   SELECT count(*) FROM <tbl>
3886a5533162Sdanielk1977 **
3887a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query
3888a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing
3889a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned.
3890a5533162Sdanielk1977 */
3891a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
3892a5533162Sdanielk1977   Table *pTab;
3893a5533162Sdanielk1977   Expr *pExpr;
3894a5533162Sdanielk1977 
3895a5533162Sdanielk1977   assert( !p->pGroupBy );
3896a5533162Sdanielk1977 
38977a895a80Sdanielk1977   if( p->pWhere || p->pEList->nExpr!=1
3898a5533162Sdanielk1977    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
3899a5533162Sdanielk1977   ){
3900a5533162Sdanielk1977     return 0;
3901a5533162Sdanielk1977   }
3902a5533162Sdanielk1977   pTab = p->pSrc->a[0].pTab;
3903a5533162Sdanielk1977   pExpr = p->pEList->a[0].pExpr;
390402f33725Sdanielk1977   assert( pTab && !pTab->pSelect && pExpr );
390502f33725Sdanielk1977 
390602f33725Sdanielk1977   if( IsVirtual(pTab) ) return 0;
3907a5533162Sdanielk1977   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
3908fb0a6081Sdrh   if( NEVER(pAggInfo->nFunc==0) ) return 0;
3909d36e1041Sdrh   if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
3910a5533162Sdanielk1977   if( pExpr->flags&EP_Distinct ) return 0;
3911a5533162Sdanielk1977 
3912a5533162Sdanielk1977   return pTab;
3913a5533162Sdanielk1977 }
3914a5533162Sdanielk1977 
3915a5533162Sdanielk1977 /*
3916b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an
3917b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there
3918b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return
3919b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
3920b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK.
3921b1c685b0Sdanielk1977 */
3922b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
39238a48b9c0Sdrh   if( pFrom->pTab && pFrom->fg.isIndexedBy ){
3924b1c685b0Sdanielk1977     Table *pTab = pFrom->pTab;
39258a48b9c0Sdrh     char *zIndexedBy = pFrom->u1.zIndexedBy;
3926b1c685b0Sdanielk1977     Index *pIdx;
3927b1c685b0Sdanielk1977     for(pIdx=pTab->pIndex;
3928d62fbb50Sdrh         pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
3929b1c685b0Sdanielk1977         pIdx=pIdx->pNext
3930b1c685b0Sdanielk1977     );
3931b1c685b0Sdanielk1977     if( !pIdx ){
3932d62fbb50Sdrh       sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
39331db95106Sdan       pParse->checkSchema = 1;
3934b1c685b0Sdanielk1977       return SQLITE_ERROR;
3935b1c685b0Sdanielk1977     }
39368a48b9c0Sdrh     pFrom->pIBIndex = pIdx;
3937b1c685b0Sdanielk1977   }
3938b1c685b0Sdanielk1977   return SQLITE_OK;
3939b1c685b0Sdanielk1977 }
3940c01b7306Sdrh /*
3941c01b7306Sdrh ** Detect compound SELECT statements that use an ORDER BY clause with
3942c01b7306Sdrh ** an alternative collating sequence.
3943c01b7306Sdrh **
3944c01b7306Sdrh **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
3945c01b7306Sdrh **
3946c01b7306Sdrh ** These are rewritten as a subquery:
3947c01b7306Sdrh **
3948c01b7306Sdrh **    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
3949c01b7306Sdrh **     ORDER BY ... COLLATE ...
3950c01b7306Sdrh **
3951c01b7306Sdrh ** This transformation is necessary because the multiSelectOrderBy() routine
3952c01b7306Sdrh ** above that generates the code for a compound SELECT with an ORDER BY clause
3953c01b7306Sdrh ** uses a merge algorithm that requires the same collating sequence on the
3954c01b7306Sdrh ** result columns as on the ORDER BY clause.  See ticket
3955c01b7306Sdrh ** http://www.sqlite.org/src/info/6709574d2a
3956c01b7306Sdrh **
3957c01b7306Sdrh ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
3958c01b7306Sdrh ** The UNION ALL operator works fine with multiSelectOrderBy() even when
3959c01b7306Sdrh ** there are COLLATE terms in the ORDER BY.
3960c01b7306Sdrh */
3961c01b7306Sdrh static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
3962c01b7306Sdrh   int i;
3963c01b7306Sdrh   Select *pNew;
3964c01b7306Sdrh   Select *pX;
3965c01b7306Sdrh   sqlite3 *db;
3966c01b7306Sdrh   struct ExprList_item *a;
3967c01b7306Sdrh   SrcList *pNewSrc;
3968c01b7306Sdrh   Parse *pParse;
3969c01b7306Sdrh   Token dummy;
3970c01b7306Sdrh 
3971c01b7306Sdrh   if( p->pPrior==0 ) return WRC_Continue;
3972c01b7306Sdrh   if( p->pOrderBy==0 ) return WRC_Continue;
3973c01b7306Sdrh   for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
3974c01b7306Sdrh   if( pX==0 ) return WRC_Continue;
3975c01b7306Sdrh   a = p->pOrderBy->a;
3976c01b7306Sdrh   for(i=p->pOrderBy->nExpr-1; i>=0; i--){
3977c01b7306Sdrh     if( a[i].pExpr->flags & EP_Collate ) break;
3978c01b7306Sdrh   }
3979c01b7306Sdrh   if( i<0 ) return WRC_Continue;
3980c01b7306Sdrh 
3981c01b7306Sdrh   /* If we reach this point, that means the transformation is required. */
3982c01b7306Sdrh 
3983c01b7306Sdrh   pParse = pWalker->pParse;
3984c01b7306Sdrh   db = pParse->db;
3985c01b7306Sdrh   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
3986c01b7306Sdrh   if( pNew==0 ) return WRC_Abort;
3987c01b7306Sdrh   memset(&dummy, 0, sizeof(dummy));
3988c01b7306Sdrh   pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
3989c01b7306Sdrh   if( pNewSrc==0 ) return WRC_Abort;
3990c01b7306Sdrh   *pNew = *p;
3991c01b7306Sdrh   p->pSrc = pNewSrc;
39921a1d3cd2Sdrh   p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
3993c01b7306Sdrh   p->op = TK_SELECT;
3994c01b7306Sdrh   p->pWhere = 0;
3995c01b7306Sdrh   pNew->pGroupBy = 0;
3996c01b7306Sdrh   pNew->pHaving = 0;
3997c01b7306Sdrh   pNew->pOrderBy = 0;
3998c01b7306Sdrh   p->pPrior = 0;
39998af9ad95Sdrh   p->pNext = 0;
4000f932f714Sdrh   p->pWith = 0;
40018af9ad95Sdrh   p->selFlags &= ~SF_Compound;
4002b33c50f2Sdan   assert( (p->selFlags & SF_Converted)==0 );
4003b33c50f2Sdan   p->selFlags |= SF_Converted;
4004a6e3a8c9Sdrh   assert( pNew->pPrior!=0 );
4005a6e3a8c9Sdrh   pNew->pPrior->pNext = pNew;
4006c01b7306Sdrh   pNew->pLimit = 0;
4007c01b7306Sdrh   pNew->pOffset = 0;
4008c01b7306Sdrh   return WRC_Continue;
4009c01b7306Sdrh }
4010b1c685b0Sdanielk1977 
401120292310Sdrh /*
401220292310Sdrh ** Check to see if the FROM clause term pFrom has table-valued function
401320292310Sdrh ** arguments.  If it does, leave an error message in pParse and return
401420292310Sdrh ** non-zero, since pFrom is not allowed to be a table-valued function.
401520292310Sdrh */
401620292310Sdrh static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
401720292310Sdrh   if( pFrom->fg.isTabFunc ){
401820292310Sdrh     sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
401920292310Sdrh     return 1;
402020292310Sdrh   }
402120292310Sdrh   return 0;
402220292310Sdrh }
402320292310Sdrh 
4024eede6a53Sdan #ifndef SQLITE_OMIT_CTE
4025eede6a53Sdan /*
4026eede6a53Sdan ** Argument pWith (which may be NULL) points to a linked list of nested
4027eede6a53Sdan ** WITH contexts, from inner to outermost. If the table identified by
4028eede6a53Sdan ** FROM clause element pItem is really a common-table-expression (CTE)
4029eede6a53Sdan ** then return a pointer to the CTE definition for that table. Otherwise
4030eede6a53Sdan ** return NULL.
403198f45e53Sdan **
403298f45e53Sdan ** If a non-NULL value is returned, set *ppContext to point to the With
403398f45e53Sdan ** object that the returned CTE belongs to.
403460c1a2f0Sdrh */
403598f45e53Sdan static struct Cte *searchWith(
40362476a6f2Sdrh   With *pWith,                    /* Current innermost WITH clause */
403798f45e53Sdan   struct SrcList_item *pItem,     /* FROM clause element to resolve */
403898f45e53Sdan   With **ppContext                /* OUT: WITH clause return value belongs to */
403998f45e53Sdan ){
40407b19f252Sdrh   const char *zName;
40417b19f252Sdrh   if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
4042eede6a53Sdan     With *p;
4043eede6a53Sdan     for(p=pWith; p; p=p->pOuter){
40444e9119d9Sdan       int i;
4045eede6a53Sdan       for(i=0; i<p->nCte; i++){
4046eede6a53Sdan         if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
404798f45e53Sdan           *ppContext = p;
4048eede6a53Sdan           return &p->a[i];
40494e9119d9Sdan         }
40504e9119d9Sdan       }
40514e9119d9Sdan     }
40524e9119d9Sdan   }
40534e9119d9Sdan   return 0;
40544e9119d9Sdan }
40554e9119d9Sdan 
4056c49832c2Sdrh /* The code generator maintains a stack of active WITH clauses
4057c49832c2Sdrh ** with the inner-most WITH clause being at the top of the stack.
4058c49832c2Sdrh **
4059b290f117Sdan ** This routine pushes the WITH clause passed as the second argument
4060b290f117Sdan ** onto the top of the stack. If argument bFree is true, then this
4061b290f117Sdan ** WITH clause will never be popped from the stack. In this case it
4062b290f117Sdan ** should be freed along with the Parse object. In other cases, when
4063b290f117Sdan ** bFree==0, the With object will be freed along with the SELECT
4064b290f117Sdan ** statement with which it is associated.
4065c49832c2Sdrh */
4066b290f117Sdan void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
40676e772266Sdrh   assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
40684e9119d9Sdan   if( pWith ){
40692476a6f2Sdrh     assert( pParse->pWith!=pWith );
40704e9119d9Sdan     pWith->pOuter = pParse->pWith;
40714e9119d9Sdan     pParse->pWith = pWith;
40726e772266Sdrh     if( bFree ) pParse->pWithToFree = pWith;
40734e9119d9Sdan   }
40744e9119d9Sdan }
40754e9119d9Sdan 
4076eede6a53Sdan /*
4077eede6a53Sdan ** This function checks if argument pFrom refers to a CTE declared by
4078eede6a53Sdan ** a WITH clause on the stack currently maintained by the parser. And,
4079eede6a53Sdan ** if currently processing a CTE expression, if it is a recursive
4080eede6a53Sdan ** reference to the current CTE.
4081eede6a53Sdan **
4082eede6a53Sdan ** If pFrom falls into either of the two categories above, pFrom->pTab
4083eede6a53Sdan ** and other fields are populated accordingly. The caller should check
4084eede6a53Sdan ** (pFrom->pTab!=0) to determine whether or not a successful match
4085eede6a53Sdan ** was found.
4086eede6a53Sdan **
4087eede6a53Sdan ** Whether or not a match is found, SQLITE_OK is returned if no error
4088eede6a53Sdan ** occurs. If an error does occur, an error message is stored in the
4089eede6a53Sdan ** parser and some error code other than SQLITE_OK returned.
4090eede6a53Sdan */
40918ce7184bSdan static int withExpand(
40928ce7184bSdan   Walker *pWalker,
4093eede6a53Sdan   struct SrcList_item *pFrom
40948ce7184bSdan ){
40958ce7184bSdan   Parse *pParse = pWalker->pParse;
40968ce7184bSdan   sqlite3 *db = pParse->db;
409798f45e53Sdan   struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
409898f45e53Sdan   With *pWith;                    /* WITH clause that pCte belongs to */
40998ce7184bSdan 
41008ce7184bSdan   assert( pFrom->pTab==0 );
41018ce7184bSdan 
410298f45e53Sdan   pCte = searchWith(pParse->pWith, pFrom, &pWith);
4103eae73fbfSdan   if( pCte ){
410498f45e53Sdan     Table *pTab;
41058ce7184bSdan     ExprList *pEList;
41068ce7184bSdan     Select *pSel;
410760e7068dSdan     Select *pLeft;                /* Left-most SELECT statement */
4108f2655fe8Sdan     int bMayRecursive;            /* True if compound joined by UNION [ALL] */
410998f45e53Sdan     With *pSavedWith;             /* Initial value of pParse->pWith */
4110f2655fe8Sdan 
41110576bc59Sdrh     /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
4112f2655fe8Sdan     ** recursive reference to CTE pCte. Leave an error in pParse and return
41130576bc59Sdrh     ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
4114f2655fe8Sdan     ** In this case, proceed.  */
41150576bc59Sdrh     if( pCte->zCteErr ){
41160576bc59Sdrh       sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
411798f45e53Sdan       return SQLITE_ERROR;
4118f2655fe8Sdan     }
411920292310Sdrh     if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
41208ce7184bSdan 
4121c25e2ebcSdrh     assert( pFrom->pTab==0 );
41228ce7184bSdan     pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
41238ce7184bSdan     if( pTab==0 ) return WRC_Abort;
41248ce7184bSdan     pTab->nRef = 1;
41252d4dc5fcSdan     pTab->zName = sqlite3DbStrDup(db, pCte->zName);
41268ce7184bSdan     pTab->iPKey = -1;
4127cfc9df76Sdan     pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
4128fccda8a1Sdrh     pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
41298ce7184bSdan     pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
4130fad3039cSmistachkin     if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
41318ce7184bSdan     assert( pFrom->pSelect );
41328ce7184bSdan 
4133eae73fbfSdan     /* Check if this is a recursive CTE. */
41348ce7184bSdan     pSel = pFrom->pSelect;
4135f2655fe8Sdan     bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
4136f2655fe8Sdan     if( bMayRecursive ){
4137eae73fbfSdan       int i;
4138eae73fbfSdan       SrcList *pSrc = pFrom->pSelect->pSrc;
4139eae73fbfSdan       for(i=0; i<pSrc->nSrc; i++){
4140eae73fbfSdan         struct SrcList_item *pItem = &pSrc->a[i];
4141eae73fbfSdan         if( pItem->zDatabase==0
4142eae73fbfSdan          && pItem->zName!=0
4143eae73fbfSdan          && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
4144eae73fbfSdan           ){
4145eae73fbfSdan           pItem->pTab = pTab;
41468a48b9c0Sdrh           pItem->fg.isRecursive = 1;
4147eae73fbfSdan           pTab->nRef++;
4148eae73fbfSdan           pSel->selFlags |= SF_Recursive;
41498ce7184bSdan         }
4150eae73fbfSdan       }
4151eae73fbfSdan     }
4152eae73fbfSdan 
4153eae73fbfSdan     /* Only one recursive reference is permitted. */
4154eae73fbfSdan     if( pTab->nRef>2 ){
4155eae73fbfSdan       sqlite3ErrorMsg(
4156727a99f1Sdrh           pParse, "multiple references to recursive table: %s", pCte->zName
4157eae73fbfSdan       );
415898f45e53Sdan       return SQLITE_ERROR;
4159eae73fbfSdan     }
4160eae73fbfSdan     assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
4161eae73fbfSdan 
41620576bc59Sdrh     pCte->zCteErr = "circular reference: %s";
416398f45e53Sdan     pSavedWith = pParse->pWith;
416498f45e53Sdan     pParse->pWith = pWith;
4165f2655fe8Sdan     sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
41666e772266Sdrh     pParse->pWith = pWith;
41678ce7184bSdan 
41688ce7184bSdan     for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
41698ce7184bSdan     pEList = pLeft->pEList;
417060e7068dSdan     if( pCte->pCols ){
41718f9d0b2bSdrh       if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
4172727a99f1Sdrh         sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
417360e7068dSdan             pCte->zName, pEList->nExpr, pCte->pCols->nExpr
417460e7068dSdan         );
417598f45e53Sdan         pParse->pWith = pSavedWith;
417698f45e53Sdan         return SQLITE_ERROR;
41778ce7184bSdan       }
417860e7068dSdan       pEList = pCte->pCols;
417960e7068dSdan     }
41808ce7184bSdan 
41818981b904Sdrh     sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
4182f2655fe8Sdan     if( bMayRecursive ){
4183f2655fe8Sdan       if( pSel->selFlags & SF_Recursive ){
41840576bc59Sdrh         pCte->zCteErr = "multiple recursive references: %s";
4185f2655fe8Sdan       }else{
41860576bc59Sdrh         pCte->zCteErr = "recursive reference in a subquery: %s";
4187f2655fe8Sdan       }
4188f2655fe8Sdan       sqlite3WalkSelect(pWalker, pSel);
4189f2655fe8Sdan     }
41900576bc59Sdrh     pCte->zCteErr = 0;
419198f45e53Sdan     pParse->pWith = pSavedWith;
41928ce7184bSdan   }
41938ce7184bSdan 
41948ce7184bSdan   return SQLITE_OK;
41958ce7184bSdan }
4196eede6a53Sdan #endif
41974e9119d9Sdan 
4198b290f117Sdan #ifndef SQLITE_OMIT_CTE
419971856944Sdan /*
420071856944Sdan ** If the SELECT passed as the second argument has an associated WITH
420171856944Sdan ** clause, pop it from the stack stored as part of the Parse object.
420271856944Sdan **
420371856944Sdan ** This function is used as the xSelectCallback2() callback by
420471856944Sdan ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
420571856944Sdan ** names and other FROM clause elements.
420671856944Sdan */
4207b290f117Sdan static void selectPopWith(Walker *pWalker, Select *p){
4208b290f117Sdan   Parse *pParse = pWalker->pParse;
4209d227a291Sdrh   With *pWith = findRightmost(p)->pWith;
4210d227a291Sdrh   if( pWith!=0 ){
4211d227a291Sdrh     assert( pParse->pWith==pWith );
4212d227a291Sdrh     pParse->pWith = pWith->pOuter;
4213b290f117Sdan   }
4214b290f117Sdan }
4215b290f117Sdan #else
4216b290f117Sdan #define selectPopWith 0
4217b290f117Sdan #endif
4218b290f117Sdan 
4219b1c685b0Sdanielk1977 /*
42207d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement.
42217d10d5a6Sdrh ** "Expanding" means to do the following:
42227d10d5a6Sdrh **
42237d10d5a6Sdrh **    (1)  Make sure VDBE cursor numbers have been assigned to every
42247d10d5a6Sdrh **         element of the FROM clause.
42257d10d5a6Sdrh **
42267d10d5a6Sdrh **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
42277d10d5a6Sdrh **         defines FROM clause.  When views appear in the FROM clause,
42287d10d5a6Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
42297d10d5a6Sdrh **         that implements the view.  A copy is made of the view's SELECT
42307d10d5a6Sdrh **         statement so that we can freely modify or delete that statement
423160ec914cSpeter.d.reid **         without worrying about messing up the persistent representation
42327d10d5a6Sdrh **         of the view.
42337d10d5a6Sdrh **
423460ec914cSpeter.d.reid **    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
42357d10d5a6Sdrh **         on joins and the ON and USING clause of joins.
42367d10d5a6Sdrh **
42377d10d5a6Sdrh **    (4)  Scan the list of columns in the result set (pEList) looking
42387d10d5a6Sdrh **         for instances of the "*" operator or the TABLE.* operator.
42397d10d5a6Sdrh **         If found, expand each "*" to be every column in every table
42407d10d5a6Sdrh **         and TABLE.* to be every column in TABLE.
42417d10d5a6Sdrh **
4242b3bce662Sdanielk1977 */
42437d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){
42447d10d5a6Sdrh   Parse *pParse = pWalker->pParse;
42457d10d5a6Sdrh   int i, j, k;
42467d10d5a6Sdrh   SrcList *pTabList;
42477d10d5a6Sdrh   ExprList *pEList;
42487d10d5a6Sdrh   struct SrcList_item *pFrom;
42497d10d5a6Sdrh   sqlite3 *db = pParse->db;
42503e3f1a5bSdrh   Expr *pE, *pRight, *pExpr;
4251785097daSdrh   u16 selFlags = p->selFlags;
42527d10d5a6Sdrh 
4253785097daSdrh   p->selFlags |= SF_Expanded;
42547d10d5a6Sdrh   if( db->mallocFailed  ){
42557d10d5a6Sdrh     return WRC_Abort;
42567d10d5a6Sdrh   }
4257785097daSdrh   if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
42587d10d5a6Sdrh     return WRC_Prune;
42597d10d5a6Sdrh   }
42607d10d5a6Sdrh   pTabList = p->pSrc;
42617d10d5a6Sdrh   pEList = p->pEList;
42623afd2b4dSdrh   if( pWalker->xSelectCallback2==selectPopWith ){
4263d227a291Sdrh     sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
42643afd2b4dSdrh   }
42657d10d5a6Sdrh 
42667d10d5a6Sdrh   /* Make sure cursor numbers have been assigned to all entries in
42677d10d5a6Sdrh   ** the FROM clause of the SELECT statement.
42687d10d5a6Sdrh   */
42697d10d5a6Sdrh   sqlite3SrcListAssignCursors(pParse, pTabList);
42707d10d5a6Sdrh 
42717d10d5a6Sdrh   /* Look up every table named in the FROM clause of the select.  If
42727d10d5a6Sdrh   ** an entry of the FROM clause is a subquery instead of a table or view,
42737d10d5a6Sdrh   ** then create a transient table structure to describe the subquery.
42747d10d5a6Sdrh   */
42757d10d5a6Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
42767d10d5a6Sdrh     Table *pTab;
4277e2b7d7a0Sdrh     assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
42788a48b9c0Sdrh     if( pFrom->fg.isRecursive ) continue;
4279e2b7d7a0Sdrh     assert( pFrom->pTab==0 );
42804e9119d9Sdan #ifndef SQLITE_OMIT_CTE
4281eede6a53Sdan     if( withExpand(pWalker, pFrom) ) return WRC_Abort;
4282eede6a53Sdan     if( pFrom->pTab ) {} else
42834e9119d9Sdan #endif
42847d10d5a6Sdrh     if( pFrom->zName==0 ){
42857d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
42867d10d5a6Sdrh       Select *pSel = pFrom->pSelect;
42877d10d5a6Sdrh       /* A sub-query in the FROM clause of a SELECT */
42887d10d5a6Sdrh       assert( pSel!=0 );
42897d10d5a6Sdrh       assert( pFrom->pTab==0 );
42902b8c5a00Sdrh       if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
42917d10d5a6Sdrh       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
42927d10d5a6Sdrh       if( pTab==0 ) return WRC_Abort;
42937d10d5a6Sdrh       pTab->nRef = 1;
4294186ad8ccSdrh       pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
42957d10d5a6Sdrh       while( pSel->pPrior ){ pSel = pSel->pPrior; }
42968981b904Sdrh       sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
42977d10d5a6Sdrh       pTab->iPKey = -1;
4298cfc9df76Sdan       pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
42997d10d5a6Sdrh       pTab->tabFlags |= TF_Ephemeral;
43007d10d5a6Sdrh #endif
43017d10d5a6Sdrh     }else{
43027d10d5a6Sdrh       /* An ordinary table or view name in the FROM clause */
43037d10d5a6Sdrh       assert( pFrom->pTab==0 );
430441fb5cd1Sdan       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
43057d10d5a6Sdrh       if( pTab==0 ) return WRC_Abort;
4306d2a56238Sdrh       if( pTab->nRef==0xffff ){
4307d2a56238Sdrh         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
4308d2a56238Sdrh            pTab->zName);
4309d2a56238Sdrh         pFrom->pTab = 0;
4310d2a56238Sdrh         return WRC_Abort;
4311d2a56238Sdrh       }
43127d10d5a6Sdrh       pTab->nRef++;
431320292310Sdrh       if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
431420292310Sdrh         return WRC_Abort;
431520292310Sdrh       }
43167d10d5a6Sdrh #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
431720292310Sdrh       if( IsVirtual(pTab) || pTab->pSelect ){
4318bfad7be7Sdrh         i16 nCol;
43197d10d5a6Sdrh         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
432043152cf8Sdrh         assert( pFrom->pSelect==0 );
43216ab3a2ecSdanielk1977         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
4322eb9b884cSdrh         sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
4323bfad7be7Sdrh         nCol = pTab->nCol;
4324bfad7be7Sdrh         pTab->nCol = -1;
43257d10d5a6Sdrh         sqlite3WalkSelect(pWalker, pFrom->pSelect);
4326bfad7be7Sdrh         pTab->nCol = nCol;
43277d10d5a6Sdrh       }
43287d10d5a6Sdrh #endif
43297d10d5a6Sdrh     }
433085574e31Sdanielk1977 
433185574e31Sdanielk1977     /* Locate the index named by the INDEXED BY clause, if any. */
4332b1c685b0Sdanielk1977     if( sqlite3IndexedByLookup(pParse, pFrom) ){
433385574e31Sdanielk1977       return WRC_Abort;
433485574e31Sdanielk1977     }
43357d10d5a6Sdrh   }
43367d10d5a6Sdrh 
43377d10d5a6Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
43387d10d5a6Sdrh   */
43397d10d5a6Sdrh   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
43407d10d5a6Sdrh     return WRC_Abort;
43417d10d5a6Sdrh   }
43427d10d5a6Sdrh 
43437d10d5a6Sdrh   /* For every "*" that occurs in the column list, insert the names of
43447d10d5a6Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
43457d10d5a6Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
43461a1d3cd2Sdrh   ** with the TK_ASTERISK operator for each "*" that it found in the column
43471a1d3cd2Sdrh   ** list.  The following code just has to locate the TK_ASTERISK
43481a1d3cd2Sdrh   ** expressions and expand each one to the list of all columns in
43491a1d3cd2Sdrh   ** all tables.
43507d10d5a6Sdrh   **
43517d10d5a6Sdrh   ** The first loop just checks to see if there are any "*" operators
43527d10d5a6Sdrh   ** that need expanding.
43537d10d5a6Sdrh   */
43547d10d5a6Sdrh   for(k=0; k<pEList->nExpr; k++){
43553e3f1a5bSdrh     pE = pEList->a[k].pExpr;
43561a1d3cd2Sdrh     if( pE->op==TK_ASTERISK ) break;
435743152cf8Sdrh     assert( pE->op!=TK_DOT || pE->pRight!=0 );
435843152cf8Sdrh     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
43591a1d3cd2Sdrh     if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
43607d10d5a6Sdrh   }
43617d10d5a6Sdrh   if( k<pEList->nExpr ){
43627d10d5a6Sdrh     /*
43637d10d5a6Sdrh     ** If we get here it means the result set contains one or more "*"
43647d10d5a6Sdrh     ** operators that need to be expanded.  Loop through each expression
43657d10d5a6Sdrh     ** in the result set and expand them one by one.
43667d10d5a6Sdrh     */
43677d10d5a6Sdrh     struct ExprList_item *a = pEList->a;
43687d10d5a6Sdrh     ExprList *pNew = 0;
43697d10d5a6Sdrh     int flags = pParse->db->flags;
43707d10d5a6Sdrh     int longNames = (flags & SQLITE_FullColNames)!=0
437138b384a0Sdrh                       && (flags & SQLITE_ShortColNames)==0;
437238b384a0Sdrh 
43737d10d5a6Sdrh     for(k=0; k<pEList->nExpr; k++){
43743e3f1a5bSdrh       pE = a[k].pExpr;
43753e3f1a5bSdrh       pRight = pE->pRight;
43763e3f1a5bSdrh       assert( pE->op!=TK_DOT || pRight!=0 );
43771a1d3cd2Sdrh       if( pE->op!=TK_ASTERISK
43781a1d3cd2Sdrh        && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
43791a1d3cd2Sdrh       ){
43807d10d5a6Sdrh         /* This particular expression does not need to be expanded.
43817d10d5a6Sdrh         */
4382b7916a78Sdrh         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
43837d10d5a6Sdrh         if( pNew ){
43847d10d5a6Sdrh           pNew->a[pNew->nExpr-1].zName = a[k].zName;
4385b7916a78Sdrh           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
4386b7916a78Sdrh           a[k].zName = 0;
4387b7916a78Sdrh           a[k].zSpan = 0;
43887d10d5a6Sdrh         }
43897d10d5a6Sdrh         a[k].pExpr = 0;
43907d10d5a6Sdrh       }else{
43917d10d5a6Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
43927d10d5a6Sdrh         ** expanded. */
43937d10d5a6Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
43943e3f1a5bSdrh         char *zTName = 0;       /* text of name of TABLE */
439543152cf8Sdrh         if( pE->op==TK_DOT ){
439643152cf8Sdrh           assert( pE->pLeft!=0 );
439733e619fcSdrh           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
439833e619fcSdrh           zTName = pE->pLeft->u.zToken;
43997d10d5a6Sdrh         }
44007d10d5a6Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
44017d10d5a6Sdrh           Table *pTab = pFrom->pTab;
44023e3f1a5bSdrh           Select *pSub = pFrom->pSelect;
44037d10d5a6Sdrh           char *zTabName = pFrom->zAlias;
44043e3f1a5bSdrh           const char *zSchemaName = 0;
4405c75e09c7Sdrh           int iDb;
440643152cf8Sdrh           if( zTabName==0 ){
44077d10d5a6Sdrh             zTabName = pTab->zName;
44087d10d5a6Sdrh           }
44097d10d5a6Sdrh           if( db->mallocFailed ) break;
44103e3f1a5bSdrh           if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
44113e3f1a5bSdrh             pSub = 0;
44127d10d5a6Sdrh             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
44137d10d5a6Sdrh               continue;
44147d10d5a6Sdrh             }
44153e3f1a5bSdrh             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
4416c75e09c7Sdrh             zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
44173e3f1a5bSdrh           }
44187d10d5a6Sdrh           for(j=0; j<pTab->nCol; j++){
44197d10d5a6Sdrh             char *zName = pTab->aCol[j].zName;
4420b7916a78Sdrh             char *zColname;  /* The computed column name */
4421b7916a78Sdrh             char *zToFree;   /* Malloced string that needs to be freed */
4422b7916a78Sdrh             Token sColname;  /* Computed column name as a token */
44237d10d5a6Sdrh 
4424c75e09c7Sdrh             assert( zName );
44253e3f1a5bSdrh             if( zTName && pSub
44263e3f1a5bSdrh              && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
44273e3f1a5bSdrh             ){
44283e3f1a5bSdrh               continue;
44293e3f1a5bSdrh             }
44303e3f1a5bSdrh 
443180090f92Sdrh             /* If a column is marked as 'hidden', omit it from the expanded
443280090f92Sdrh             ** result-set list unless the SELECT has the SF_IncludeHidden
443380090f92Sdrh             ** bit set.
44347d10d5a6Sdrh             */
443580090f92Sdrh             if( (p->selFlags & SF_IncludeHidden)==0
443680090f92Sdrh              && IsHiddenColumn(&pTab->aCol[j])
443780090f92Sdrh             ){
44387d10d5a6Sdrh               continue;
44397d10d5a6Sdrh             }
44403e3f1a5bSdrh             tableSeen = 1;
44417d10d5a6Sdrh 
4442da55c48aSdrh             if( i>0 && zTName==0 ){
44438a48b9c0Sdrh               if( (pFrom->fg.jointype & JT_NATURAL)!=0
44442179b434Sdrh                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
44452179b434Sdrh               ){
44467d10d5a6Sdrh                 /* In a NATURAL join, omit the join columns from the
44472179b434Sdrh                 ** table to the right of the join */
44487d10d5a6Sdrh                 continue;
44497d10d5a6Sdrh               }
44502179b434Sdrh               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
44517d10d5a6Sdrh                 /* In a join with a USING clause, omit columns in the
44527d10d5a6Sdrh                 ** using clause from the table on the right. */
44537d10d5a6Sdrh                 continue;
44547d10d5a6Sdrh               }
44557d10d5a6Sdrh             }
4456b7916a78Sdrh             pRight = sqlite3Expr(db, TK_ID, zName);
4457b7916a78Sdrh             zColname = zName;
4458b7916a78Sdrh             zToFree = 0;
44597d10d5a6Sdrh             if( longNames || pTabList->nSrc>1 ){
4460b7916a78Sdrh               Expr *pLeft;
4461b7916a78Sdrh               pLeft = sqlite3Expr(db, TK_ID, zTabName);
44627d10d5a6Sdrh               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
446338b384a0Sdrh               if( zSchemaName ){
4464c75e09c7Sdrh                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
4465c75e09c7Sdrh                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
4466c75e09c7Sdrh               }
4467b7916a78Sdrh               if( longNames ){
4468b7916a78Sdrh                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
4469b7916a78Sdrh                 zToFree = zColname;
4470b7916a78Sdrh               }
44717d10d5a6Sdrh             }else{
44727d10d5a6Sdrh               pExpr = pRight;
44737d10d5a6Sdrh             }
4474b7916a78Sdrh             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
447540aced5cSdrh             sqlite3TokenInit(&sColname, zColname);
4476b7916a78Sdrh             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
44778f25d18bSdrh             if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
44783e3f1a5bSdrh               struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
44793e3f1a5bSdrh               if( pSub ){
44803e3f1a5bSdrh                 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
4481c75e09c7Sdrh                 testcase( pX->zSpan==0 );
44823e3f1a5bSdrh               }else{
44833e3f1a5bSdrh                 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
44843e3f1a5bSdrh                                            zSchemaName, zTabName, zColname);
4485c75e09c7Sdrh                 testcase( pX->zSpan==0 );
44863e3f1a5bSdrh               }
44873e3f1a5bSdrh               pX->bSpanIsTab = 1;
44888f25d18bSdrh             }
4489b7916a78Sdrh             sqlite3DbFree(db, zToFree);
44907d10d5a6Sdrh           }
44917d10d5a6Sdrh         }
44927d10d5a6Sdrh         if( !tableSeen ){
44937d10d5a6Sdrh           if( zTName ){
44947d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
44957d10d5a6Sdrh           }else{
44967d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no tables specified");
44977d10d5a6Sdrh           }
44987d10d5a6Sdrh         }
44997d10d5a6Sdrh       }
45007d10d5a6Sdrh     }
45017d10d5a6Sdrh     sqlite3ExprListDelete(db, pEList);
45027d10d5a6Sdrh     p->pEList = pNew;
45037d10d5a6Sdrh   }
45047d10d5a6Sdrh #if SQLITE_MAX_COLUMN
45057d10d5a6Sdrh   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
45067d10d5a6Sdrh     sqlite3ErrorMsg(pParse, "too many columns in result set");
45078836cbbcSdan     return WRC_Abort;
45087d10d5a6Sdrh   }
45097d10d5a6Sdrh #endif
45107d10d5a6Sdrh   return WRC_Continue;
45117d10d5a6Sdrh }
45127d10d5a6Sdrh 
45137d10d5a6Sdrh /*
45147d10d5a6Sdrh ** No-op routine for the parse-tree walker.
45157d10d5a6Sdrh **
45167d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees
45177d10d5a6Sdrh ** are walked without any actions being taken at each node.  Presumably,
45187d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then
45197d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every
45207d10d5a6Sdrh ** subquery in the parser tree.
45217d10d5a6Sdrh */
45225b88bc4bSdrh int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
452362c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
45247d10d5a6Sdrh   return WRC_Continue;
45257d10d5a6Sdrh }
45267d10d5a6Sdrh 
45277d10d5a6Sdrh /*
45287d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries.
45297d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT
45307d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above.
45317d10d5a6Sdrh **
45327d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a
45337d10d5a6Sdrh ** SELECT statement.  The SELECT statement must be expanded before
45347d10d5a6Sdrh ** name resolution is performed.
45357d10d5a6Sdrh **
45367d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse.
45377d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr
45387d10d5a6Sdrh ** and/or pParse->db->mallocFailed.
45397d10d5a6Sdrh */
45407d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
45417d10d5a6Sdrh   Walker w;
4542aa87f9a6Sdrh   memset(&w, 0, sizeof(w));
45435b88bc4bSdrh   w.xExprCallback = sqlite3ExprWalkNoop;
45447d10d5a6Sdrh   w.pParse = pParse;
4545d58d3278Sdrh   if( pParse->hasCompound ){
4546d58d3278Sdrh     w.xSelectCallback = convertCompoundSelectToSubquery;
45477d10d5a6Sdrh     sqlite3WalkSelect(&w, pSelect);
4548d58d3278Sdrh   }
4549c01b7306Sdrh   w.xSelectCallback = selectExpander;
4550772460fdSdrh   if( (pSelect->selFlags & SF_MultiValue)==0 ){
4551b290f117Sdan     w.xSelectCallback2 = selectPopWith;
45523afd2b4dSdrh   }
4553c01b7306Sdrh   sqlite3WalkSelect(&w, pSelect);
45547d10d5a6Sdrh }
45557d10d5a6Sdrh 
45567d10d5a6Sdrh 
45577d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
45587d10d5a6Sdrh /*
45597d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
45607d10d5a6Sdrh ** interface.
45617d10d5a6Sdrh **
45627d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl
45637d10d5a6Sdrh ** information to the Table structure that represents the result set
45647d10d5a6Sdrh ** of that subquery.
45657d10d5a6Sdrh **
45667d10d5a6Sdrh ** The Table structure that represents the result set was constructed
45677d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted
45687d10d5a6Sdrh ** at that point because identifiers had not yet been resolved.  This
45697d10d5a6Sdrh ** routine is called after identifier resolution.
45707d10d5a6Sdrh */
4571b290f117Sdan static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
45727d10d5a6Sdrh   Parse *pParse;
45737d10d5a6Sdrh   int i;
45747d10d5a6Sdrh   SrcList *pTabList;
45757d10d5a6Sdrh   struct SrcList_item *pFrom;
45767d10d5a6Sdrh 
45779d8b3072Sdrh   assert( p->selFlags & SF_Resolved );
4578e2b7d7a0Sdrh   assert( (p->selFlags & SF_HasTypeInfo)==0 );
45797d10d5a6Sdrh   p->selFlags |= SF_HasTypeInfo;
45807d10d5a6Sdrh   pParse = pWalker->pParse;
45817d10d5a6Sdrh   pTabList = p->pSrc;
45827d10d5a6Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
45837d10d5a6Sdrh     Table *pTab = pFrom->pTab;
4584e2b7d7a0Sdrh     assert( pTab!=0 );
4585e2b7d7a0Sdrh     if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
45867d10d5a6Sdrh       /* A sub-query in the FROM clause of a SELECT */
45877d10d5a6Sdrh       Select *pSel = pFrom->pSelect;
45888ce7184bSdan       if( pSel ){
45897d10d5a6Sdrh         while( pSel->pPrior ) pSel = pSel->pPrior;
4590ed06a131Sdrh         sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
45917d10d5a6Sdrh       }
45927d10d5a6Sdrh     }
45935a29d9cbSdrh   }
45948ce7184bSdan }
45957d10d5a6Sdrh #endif
45967d10d5a6Sdrh 
45977d10d5a6Sdrh 
45987d10d5a6Sdrh /*
45997d10d5a6Sdrh ** This routine adds datatype and collating sequence information to
46007d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a
46017d10d5a6Sdrh ** SELECT statement.
46027d10d5a6Sdrh **
46037d10d5a6Sdrh ** Use this routine after name resolution.
46047d10d5a6Sdrh */
46057d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
46067d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
46077d10d5a6Sdrh   Walker w;
4608aa87f9a6Sdrh   memset(&w, 0, sizeof(w));
4609b290f117Sdan   w.xSelectCallback2 = selectAddSubqueryTypeInfo;
46105b88bc4bSdrh   w.xExprCallback = sqlite3ExprWalkNoop;
46117d10d5a6Sdrh   w.pParse = pParse;
46127d10d5a6Sdrh   sqlite3WalkSelect(&w, pSelect);
46137d10d5a6Sdrh #endif
46147d10d5a6Sdrh }
46157d10d5a6Sdrh 
46167d10d5a6Sdrh 
46177d10d5a6Sdrh /*
4618030796dfSdrh ** This routine sets up a SELECT statement for processing.  The
46197d10d5a6Sdrh ** following is accomplished:
46207d10d5a6Sdrh **
46217d10d5a6Sdrh **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
46227d10d5a6Sdrh **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
46237d10d5a6Sdrh **     *  ON and USING clauses are shifted into WHERE statements
46247d10d5a6Sdrh **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
46257d10d5a6Sdrh **     *  Identifiers in expression are matched to tables.
46267d10d5a6Sdrh **
46277d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT.
46287d10d5a6Sdrh */
46297d10d5a6Sdrh void sqlite3SelectPrep(
4630b3bce662Sdanielk1977   Parse *pParse,         /* The parser context */
4631b3bce662Sdanielk1977   Select *p,             /* The SELECT statement being coded. */
46327d10d5a6Sdrh   NameContext *pOuterNC  /* Name context for container */
4633b3bce662Sdanielk1977 ){
46347d10d5a6Sdrh   sqlite3 *db;
463543152cf8Sdrh   if( NEVER(p==0) ) return;
46367d10d5a6Sdrh   db = pParse->db;
4637785097daSdrh   if( db->mallocFailed ) return;
46387d10d5a6Sdrh   if( p->selFlags & SF_HasTypeInfo ) return;
46397d10d5a6Sdrh   sqlite3SelectExpand(pParse, p);
46407d10d5a6Sdrh   if( pParse->nErr || db->mallocFailed ) return;
46417d10d5a6Sdrh   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
46427d10d5a6Sdrh   if( pParse->nErr || db->mallocFailed ) return;
46437d10d5a6Sdrh   sqlite3SelectAddTypeInfo(pParse, p);
4644f6bbe022Sdrh }
4645b3bce662Sdanielk1977 
4646b3bce662Sdanielk1977 /*
464713449892Sdrh ** Reset the aggregate accumulator.
464813449892Sdrh **
464913449892Sdrh ** The aggregate accumulator is a set of memory cells that hold
465013449892Sdrh ** intermediate results while calculating an aggregate.  This
4651030796dfSdrh ** routine generates code that stores NULLs in all of those memory
4652030796dfSdrh ** cells.
4653b3bce662Sdanielk1977 */
465413449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
465513449892Sdrh   Vdbe *v = pParse->pVdbe;
465613449892Sdrh   int i;
4657c99130fdSdrh   struct AggInfo_func *pFunc;
46587e61d18eSdrh   int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
46597e61d18eSdrh   if( nReg==0 ) return;
46607e61d18eSdrh #ifdef SQLITE_DEBUG
46617e61d18eSdrh   /* Verify that all AggInfo registers are within the range specified by
46627e61d18eSdrh   ** AggInfo.mnReg..AggInfo.mxReg */
46637e61d18eSdrh   assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
466413449892Sdrh   for(i=0; i<pAggInfo->nColumn; i++){
46657e61d18eSdrh     assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
46667e61d18eSdrh          && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
466713449892Sdrh   }
46687e61d18eSdrh   for(i=0; i<pAggInfo->nFunc; i++){
46697e61d18eSdrh     assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
46707e61d18eSdrh          && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
46717e61d18eSdrh   }
46727e61d18eSdrh #endif
46737e61d18eSdrh   sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
4674c99130fdSdrh   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
4675c99130fdSdrh     if( pFunc->iDistinct>=0 ){
4676c99130fdSdrh       Expr *pE = pFunc->pExpr;
46776ab3a2ecSdanielk1977       assert( !ExprHasProperty(pE, EP_xIsSelect) );
46786ab3a2ecSdanielk1977       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
46790daa002cSdrh         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
46800daa002cSdrh            "argument");
4681c99130fdSdrh         pFunc->iDistinct = -1;
4682c99130fdSdrh       }else{
4683079a3072Sdrh         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
468466a5167bSdrh         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
46852ec2fb22Sdrh                           (char*)pKeyInfo, P4_KEYINFO);
4686c99130fdSdrh       }
4687c99130fdSdrh     }
468813449892Sdrh   }
4689b3bce662Sdanielk1977 }
4690b3bce662Sdanielk1977 
4691b3bce662Sdanielk1977 /*
469213449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function
469313449892Sdrh ** in the AggInfo structure.
4694b3bce662Sdanielk1977 */
469513449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
469613449892Sdrh   Vdbe *v = pParse->pVdbe;
469713449892Sdrh   int i;
469813449892Sdrh   struct AggInfo_func *pF;
469913449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
47006ab3a2ecSdanielk1977     ExprList *pList = pF->pExpr->x.pList;
47016ab3a2ecSdanielk1977     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
470266a5167bSdrh     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
470366a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
4704b3bce662Sdanielk1977   }
470513449892Sdrh }
470613449892Sdrh 
470713449892Sdrh /*
470813449892Sdrh ** Update the accumulator memory cells for an aggregate based on
470913449892Sdrh ** the current cursor position.
471013449892Sdrh */
471113449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
471213449892Sdrh   Vdbe *v = pParse->pVdbe;
471313449892Sdrh   int i;
47147a95789cSdrh   int regHit = 0;
47157a95789cSdrh   int addrHitTest = 0;
471613449892Sdrh   struct AggInfo_func *pF;
471713449892Sdrh   struct AggInfo_col *pC;
471813449892Sdrh 
471913449892Sdrh   pAggInfo->directMode = 1;
472013449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
472113449892Sdrh     int nArg;
4722c99130fdSdrh     int addrNext = 0;
472398757157Sdrh     int regAgg;
47246ab3a2ecSdanielk1977     ExprList *pList = pF->pExpr->x.pList;
47256ab3a2ecSdanielk1977     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
472613449892Sdrh     if( pList ){
472713449892Sdrh       nArg = pList->nExpr;
4728892d3179Sdrh       regAgg = sqlite3GetTempRange(pParse, nArg);
47295579d59fSdrh       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
473013449892Sdrh     }else{
473113449892Sdrh       nArg = 0;
473298757157Sdrh       regAgg = 0;
473313449892Sdrh     }
4734c99130fdSdrh     if( pF->iDistinct>=0 ){
4735c99130fdSdrh       addrNext = sqlite3VdbeMakeLabel(v);
47367c052da5Sdrh       testcase( nArg==0 );  /* Error condition */
47377c052da5Sdrh       testcase( nArg>1 );   /* Also an error */
47382dcef11bSdrh       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
4739c99130fdSdrh     }
4740d36e1041Sdrh     if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
474113449892Sdrh       CollSeq *pColl = 0;
474213449892Sdrh       struct ExprList_item *pItem;
474313449892Sdrh       int j;
4744e82f5d04Sdrh       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
474543617e9aSdrh       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
474613449892Sdrh         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
474713449892Sdrh       }
474813449892Sdrh       if( !pColl ){
474913449892Sdrh         pColl = pParse->db->pDfltColl;
475013449892Sdrh       }
47517a95789cSdrh       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
47527a95789cSdrh       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
475313449892Sdrh     }
47549c7c913cSdrh     sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem,
475566a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
4756ea678832Sdrh     sqlite3VdbeChangeP5(v, (u8)nArg);
4757da250ea5Sdrh     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
4758f49f3523Sdrh     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
4759c99130fdSdrh     if( addrNext ){
4760c99130fdSdrh       sqlite3VdbeResolveLabel(v, addrNext);
4761ceea3321Sdrh       sqlite3ExprCacheClear(pParse);
4762c99130fdSdrh     }
476313449892Sdrh   }
476467a6a40cSdan 
476567a6a40cSdan   /* Before populating the accumulator registers, clear the column cache.
476667a6a40cSdan   ** Otherwise, if any of the required column values are already present
476767a6a40cSdan   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
476867a6a40cSdan   ** to pC->iMem. But by the time the value is used, the original register
476967a6a40cSdan   ** may have been used, invalidating the underlying buffer holding the
477067a6a40cSdan   ** text or blob value. See ticket [883034dcb5].
477167a6a40cSdan   **
477267a6a40cSdan   ** Another solution would be to change the OP_SCopy used to copy cached
477367a6a40cSdan   ** values to an OP_Copy.
477467a6a40cSdan   */
47757a95789cSdrh   if( regHit ){
4776688852abSdrh     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
47777a95789cSdrh   }
477867a6a40cSdan   sqlite3ExprCacheClear(pParse);
477913449892Sdrh   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
4780389a1adbSdrh     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
478113449892Sdrh   }
478213449892Sdrh   pAggInfo->directMode = 0;
4783ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
47847a95789cSdrh   if( addrHitTest ){
47857a95789cSdrh     sqlite3VdbeJumpHere(v, addrHitTest);
47867a95789cSdrh   }
478713449892Sdrh }
478813449892Sdrh 
4789b3bce662Sdanielk1977 /*
4790ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple
4791ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab").
4792ef7075deSdan */
4793ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN
4794ef7075deSdan static void explainSimpleCount(
4795ef7075deSdan   Parse *pParse,                  /* Parse context */
4796ef7075deSdan   Table *pTab,                    /* Table being queried */
4797ef7075deSdan   Index *pIdx                     /* Index used to optimize scan, or NULL */
4798ef7075deSdan ){
4799ef7075deSdan   if( pParse->explain==2 ){
480048dd1d8eSdrh     int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
48018a4380d7Sdrh     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
4802ef7075deSdan         pTab->zName,
4803e96f2df3Sdan         bCover ? " USING COVERING INDEX " : "",
4804e96f2df3Sdan         bCover ? pIdx->zName : ""
4805ef7075deSdan     );
4806ef7075deSdan     sqlite3VdbeAddOp4(
4807ef7075deSdan         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
4808ef7075deSdan     );
4809ef7075deSdan   }
4810ef7075deSdan }
4811ef7075deSdan #else
4812ef7075deSdan # define explainSimpleCount(a,b,c)
4813ef7075deSdan #endif
4814ef7075deSdan 
4815ef7075deSdan /*
48167d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument.
48179bb61fe7Sdrh **
4818340309fdSdrh ** The results are returned according to the SelectDest structure.
4819340309fdSdrh ** See comments in sqliteInt.h for further information.
4820e78e8284Sdrh **
48219bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
48229bb61fe7Sdrh ** encountered, then an appropriate error message is left in
48239bb61fe7Sdrh ** pParse->zErrMsg.
48249bb61fe7Sdrh **
48259bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
48269bb61fe7Sdrh ** calling function needs to do that.
48279bb61fe7Sdrh */
48284adee20fSdanielk1977 int sqlite3Select(
4829cce7d176Sdrh   Parse *pParse,         /* The parser context */
48309bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
48317d10d5a6Sdrh   SelectDest *pDest      /* What to do with the query results */
4832cce7d176Sdrh ){
483313449892Sdrh   int i, j;              /* Loop counters */
483413449892Sdrh   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
483513449892Sdrh   Vdbe *v;               /* The virtual machine under construction */
4836b3bce662Sdanielk1977   int isAgg;             /* True for select lists like "count(*)" */
4837c29cbb0bSmistachkin   ExprList *pEList = 0;  /* List of columns to extract. */
4838ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
48399bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
48402282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
48412282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
48421d83f052Sdrh   int rc = 1;            /* Value to return from this function */
4843e8e4af76Sdrh   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
4844079a3072Sdrh   SortCtx sSort;         /* Info on how to code the ORDER BY clause */
484513449892Sdrh   AggInfo sAggInfo;      /* Information used by aggregate queries */
4846ec7429aeSdrh   int iEnd;              /* Address of the end of the query */
484717435752Sdrh   sqlite3 *db;           /* The database connection */
48489bb61fe7Sdrh 
48492ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN
48502ce22453Sdan   int iRestoreSelectId = pParse->iSelectId;
48512ce22453Sdan   pParse->iSelectId = pParse->iNextSelectId++;
48522ce22453Sdan #endif
48532ce22453Sdan 
485417435752Sdrh   db = pParse->db;
485517435752Sdrh   if( p==0 || db->mallocFailed || pParse->nErr ){
48566f7adc8aSdrh     return 1;
48576f7adc8aSdrh   }
48584adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
485913449892Sdrh   memset(&sAggInfo, 0, sizeof(sAggInfo));
4860eb9b884cSdrh #if SELECTTRACE_ENABLED
4861eb9b884cSdrh   pParse->nSelectIndent++;
4862c90713d3Sdrh   SELECTTRACE(1,pParse,p, ("begin processing:\n"));
4863c90713d3Sdrh   if( sqlite3SelectTrace & 0x100 ){
4864c90713d3Sdrh     sqlite3TreeViewSelect(0, p, 0);
4865c90713d3Sdrh   }
4866eb9b884cSdrh #endif
4867daffd0e5Sdrh 
48688e1ee88cSdrh   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
48698e1ee88cSdrh   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
48709afccba2Sdan   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
48719afccba2Sdan   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
48726c8c8ce0Sdanielk1977   if( IgnorableOrderby(pDest) ){
48739ed1dfa8Sdanielk1977     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
48749afccba2Sdan            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
48758e1ee88cSdrh            pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
48768e1ee88cSdrh            pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
4877ccfcbceaSdrh     /* If ORDER BY makes no difference in the output then neither does
4878ccfcbceaSdrh     ** DISTINCT so it can be removed too. */
4879ccfcbceaSdrh     sqlite3ExprListDelete(db, p->pOrderBy);
4880ccfcbceaSdrh     p->pOrderBy = 0;
48817d10d5a6Sdrh     p->selFlags &= ~SF_Distinct;
48829a99334dSdrh   }
48837d10d5a6Sdrh   sqlite3SelectPrep(pParse, p, 0);
4884079a3072Sdrh   memset(&sSort, 0, sizeof(sSort));
4885079a3072Sdrh   sSort.pOrderBy = p->pOrderBy;
4886b27b7f5dSdrh   pTabList = p->pSrc;
4887956f4319Sdanielk1977   if( pParse->nErr || db->mallocFailed ){
48889a99334dSdrh     goto select_end;
48899a99334dSdrh   }
4890adc57f68Sdrh   assert( p->pEList!=0 );
48917d10d5a6Sdrh   isAgg = (p->selFlags & SF_Aggregate)!=0;
489217645f5eSdrh #if SELECTTRACE_ENABLED
489317645f5eSdrh   if( sqlite3SelectTrace & 0x100 ){
489417645f5eSdrh     SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
489517645f5eSdrh     sqlite3TreeViewSelect(0, p, 0);
489617645f5eSdrh   }
489717645f5eSdrh #endif
4898cce7d176Sdrh 
4899d820cb1bSdrh 
490074b617b2Sdan   /* If writing to memory or generating a set
490174b617b2Sdan   ** only a single column may be output.
490274b617b2Sdan   */
490374b617b2Sdan #ifndef SQLITE_OMIT_SUBQUERY
4904adc57f68Sdrh   if( checkForMultiColumnSelectError(pParse, pDest, p->pEList->nExpr) ){
490574b617b2Sdan     goto select_end;
490674b617b2Sdan   }
490774b617b2Sdan #endif
490874b617b2Sdan 
4909adc57f68Sdrh   /* Try to flatten subqueries in the FROM clause up into the main query
4910d820cb1bSdrh   */
491151522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4912f23329a2Sdanielk1977   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
491313449892Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
4914daf79acbSdanielk1977     Select *pSub = pItem->pSelect;
4915f23329a2Sdanielk1977     int isAggSub;
49162679f14fSdrh     Table *pTab = pItem->pTab;
49174490c40bSdrh     if( pSub==0 ) continue;
49182679f14fSdrh 
49192679f14fSdrh     /* Catch mismatch in the declared columns of a view and the number of
49202679f14fSdrh     ** columns in the SELECT on the RHS */
49212679f14fSdrh     if( pTab->nCol!=pSub->pEList->nExpr ){
49222679f14fSdrh       sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
49232679f14fSdrh                       pTab->nCol, pTab->zName, pSub->pEList->nExpr);
49242679f14fSdrh       goto select_end;
49252679f14fSdrh     }
49262679f14fSdrh 
49274490c40bSdrh     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
49284490c40bSdrh     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
49294490c40bSdrh       /* This subquery can be absorbed into its parent. */
49304490c40bSdrh       if( isAggSub ){
49314490c40bSdrh         isAgg = 1;
49324490c40bSdrh         p->selFlags |= SF_Aggregate;
49334490c40bSdrh       }
49344490c40bSdrh       i = -1;
49354490c40bSdrh     }
49364490c40bSdrh     pTabList = p->pSrc;
49374490c40bSdrh     if( db->mallocFailed ) goto select_end;
49384490c40bSdrh     if( !IgnorableOrderby(pDest) ){
49394490c40bSdrh       sSort.pOrderBy = p->pOrderBy;
49404490c40bSdrh     }
49414490c40bSdrh   }
49424490c40bSdrh #endif
49434490c40bSdrh 
4944adc57f68Sdrh   /* Get a pointer the VDBE under construction, allocating a new VDBE if one
4945adc57f68Sdrh   ** does not already exist */
4946adc57f68Sdrh   v = sqlite3GetVdbe(pParse);
4947adc57f68Sdrh   if( v==0 ) goto select_end;
49484490c40bSdrh 
49494490c40bSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
49504490c40bSdrh   /* Handle compound SELECT statements using the separate multiSelect()
49514490c40bSdrh   ** procedure.
49524490c40bSdrh   */
49534490c40bSdrh   if( p->pPrior ){
49544490c40bSdrh     rc = multiSelect(pParse, p, pDest);
49554490c40bSdrh     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
49564490c40bSdrh #if SELECTTRACE_ENABLED
49574490c40bSdrh     SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
49584490c40bSdrh     pParse->nSelectIndent--;
49594490c40bSdrh #endif
49604490c40bSdrh     return rc;
49614490c40bSdrh   }
49624490c40bSdrh #endif
49634490c40bSdrh 
49646e17529eSdrh   /* Generate code for all sub-queries in the FROM clause
49656e17529eSdrh   */
49666e17529eSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
49674490c40bSdrh   for(i=0; i<pTabList->nSrc; i++){
4968ad3cab52Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
49695cf590c1Sdrh     SelectDest dest;
4970c31c2eb8Sdrh     Select *pSub = pItem->pSelect;
49715b6a9ed4Sdrh     if( pSub==0 ) continue;
497221172c4cSdrh 
497321172c4cSdrh     /* Sometimes the code for a subquery will be generated more than
497421172c4cSdrh     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
497521172c4cSdrh     ** for example.  In that case, do not regenerate the code to manifest
497621172c4cSdrh     ** a view or the co-routine to implement a view.  The first instance
497721172c4cSdrh     ** is sufficient, though the subroutine to manifest the view does need
497821172c4cSdrh     ** to be invoked again. */
49795b6a9ed4Sdrh     if( pItem->addrFillSub ){
49808a48b9c0Sdrh       if( pItem->fg.viaCoroutine==0 ){
49815b6a9ed4Sdrh         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
498221172c4cSdrh       }
49835b6a9ed4Sdrh       continue;
49845b6a9ed4Sdrh     }
4985daf79acbSdanielk1977 
4986fc976065Sdanielk1977     /* Increment Parse.nHeight by the height of the largest expression
4987f7b5496eSdrh     ** tree referred to by this, the parent select. The child select
4988fc976065Sdanielk1977     ** may contain expression trees of at most
4989fc976065Sdanielk1977     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
4990fc976065Sdanielk1977     ** more conservative than necessary, but much easier than enforcing
4991fc976065Sdanielk1977     ** an exact limit.
4992fc976065Sdanielk1977     */
4993fc976065Sdanielk1977     pParse->nHeight += sqlite3SelectExprHeight(p);
4994daf79acbSdanielk1977 
4995adc57f68Sdrh     /* Make copies of constant WHERE-clause terms in the outer query down
4996adc57f68Sdrh     ** inside the subquery.  This can help the subquery to run more efficiently.
4997adc57f68Sdrh     */
49988a48b9c0Sdrh     if( (pItem->fg.jointype & JT_OUTER)==0
499969b72d5aSdrh      && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor)
500069b72d5aSdrh     ){
500169b72d5aSdrh #if SELECTTRACE_ENABLED
500269b72d5aSdrh       if( sqlite3SelectTrace & 0x100 ){
5003bc8edba1Sdrh         SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
500469b72d5aSdrh         sqlite3TreeViewSelect(0, p, 0);
5005daf79acbSdanielk1977       }
500669b72d5aSdrh #endif
500769b72d5aSdrh     }
5008adc57f68Sdrh 
5009adc57f68Sdrh     /* Generate code to implement the subquery
50100ff47e9eSdrh     **
50110ff47e9eSdrh     ** The subquery is implemented as a co-routine if all of these are true:
50120ff47e9eSdrh     **   (1)  The subquery is guaranteed to be the outer loop (so that it
50130ff47e9eSdrh     **        does not need to be computed more than once)
50140ff47e9eSdrh     **   (2)  The ALL keyword after SELECT is omitted.  (Applications are
50150ff47e9eSdrh     **        allowed to say "SELECT ALL" instead of just "SELECT" to disable
50160ff47e9eSdrh     **        the use of co-routines.)
50170ff47e9eSdrh     **   (3)  Co-routines are not disabled using sqlite3_test_control()
50180ff47e9eSdrh     **        with SQLITE_TESTCTRL_OPTIMIZATIONS.
50190ff47e9eSdrh     **
50200ff47e9eSdrh     ** TODO: Are there other reasons beside (1) to use a co-routine
50210ff47e9eSdrh     ** implementation?
5022adc57f68Sdrh     */
50230ff47e9eSdrh     if( i==0
50240ff47e9eSdrh      && (pTabList->nSrc==1
50250ff47e9eSdrh             || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)  /* (1) */
50260ff47e9eSdrh      && (p->selFlags & SF_All)==0                                   /* (2) */
50270ff47e9eSdrh      && OptimizationEnabled(db, SQLITE_SubqCoroutine)               /* (3) */
5028a5759677Sdrh     ){
502921172c4cSdrh       /* Implement a co-routine that will return a single row of the result
503021172c4cSdrh       ** set on each invocation.
503121172c4cSdrh       */
5032725de29aSdrh       int addrTop = sqlite3VdbeCurrentAddr(v)+1;
503321172c4cSdrh       pItem->regReturn = ++pParse->nMem;
5034725de29aSdrh       sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
5035725de29aSdrh       VdbeComment((v, "%s", pItem->pTab->zName));
503621172c4cSdrh       pItem->addrFillSub = addrTop;
503721172c4cSdrh       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
503821172c4cSdrh       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
503921172c4cSdrh       sqlite3Select(pParse, pSub, &dest);
5040c3489bbfSdrh       pItem->pTab->nRowLogEst = pSub->nSelectRow;
50418a48b9c0Sdrh       pItem->fg.viaCoroutine = 1;
50425f612295Sdrh       pItem->regResult = dest.iSdst;
50432fade2f7Sdrh       sqlite3VdbeEndCoroutine(v, pItem->regReturn);
504421172c4cSdrh       sqlite3VdbeJumpHere(v, addrTop-1);
504521172c4cSdrh       sqlite3ClearTempRegCache(pParse);
5046daf79acbSdanielk1977     }else{
50475b6a9ed4Sdrh       /* Generate a subroutine that will fill an ephemeral table with
50485b6a9ed4Sdrh       ** the content of this subquery.  pItem->addrFillSub will point
50495b6a9ed4Sdrh       ** to the address of the generated subroutine.  pItem->regReturn
50505b6a9ed4Sdrh       ** is a register allocated to hold the subroutine return address
50515b6a9ed4Sdrh       */
50527157e8eaSdrh       int topAddr;
505348f2d3b1Sdrh       int onceAddr = 0;
50547157e8eaSdrh       int retAddr;
50555b6a9ed4Sdrh       assert( pItem->addrFillSub==0 );
50565b6a9ed4Sdrh       pItem->regReturn = ++pParse->nMem;
50577157e8eaSdrh       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
50587157e8eaSdrh       pItem->addrFillSub = topAddr+1;
50598a48b9c0Sdrh       if( pItem->fg.isCorrelated==0 ){
5060ed17167eSdrh         /* If the subquery is not correlated and if we are not inside of
50615b6a9ed4Sdrh         ** a trigger, then we only need to compute the value of the subquery
50625b6a9ed4Sdrh         ** once. */
50637d176105Sdrh         onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
5064725de29aSdrh         VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
5065725de29aSdrh       }else{
5066725de29aSdrh         VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
50675b6a9ed4Sdrh       }
50681013c932Sdrh       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
5069ce7e189dSdan       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
50707d10d5a6Sdrh       sqlite3Select(pParse, pSub, &dest);
5071c3489bbfSdrh       pItem->pTab->nRowLogEst = pSub->nSelectRow;
507248f2d3b1Sdrh       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
50737157e8eaSdrh       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
50747157e8eaSdrh       VdbeComment((v, "end %s", pItem->pTab->zName));
50757157e8eaSdrh       sqlite3VdbeChangeP1(v, topAddr, retAddr);
5076cdc69557Sdrh       sqlite3ClearTempRegCache(pParse);
5077daf79acbSdanielk1977     }
5078adc57f68Sdrh     if( db->mallocFailed ) goto select_end;
5079fc976065Sdanielk1977     pParse->nHeight -= sqlite3SelectExprHeight(p);
5080acd4c695Sdrh   }
5081daf79acbSdanielk1977 #endif
5082adc57f68Sdrh 
508338b4149cSdrh   /* Various elements of the SELECT copied into local variables for
508438b4149cSdrh   ** convenience */
5085adc57f68Sdrh   pEList = p->pEList;
5086daf79acbSdanielk1977   pWhere = p->pWhere;
5087832508b7Sdrh   pGroupBy = p->pGroupBy;
5088832508b7Sdrh   pHaving = p->pHaving;
5089e8e4af76Sdrh   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
5090832508b7Sdrh 
5091bc8edba1Sdrh #if SELECTTRACE_ENABLED
5092bc8edba1Sdrh   if( sqlite3SelectTrace & 0x400 ){
5093bc8edba1Sdrh     SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
5094bc8edba1Sdrh     sqlite3TreeViewSelect(0, p, 0);
5095f23329a2Sdanielk1977   }
5096f23329a2Sdanielk1977 #endif
5097f23329a2Sdanielk1977 
509850118cdfSdan   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
509950118cdfSdan   ** if the select-list is the same as the ORDER BY list, then this query
510050118cdfSdan   ** can be rewritten as a GROUP BY. In other words, this:
510150118cdfSdan   **
510250118cdfSdan   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
510350118cdfSdan   **
510450118cdfSdan   ** is transformed to:
510550118cdfSdan   **
5106dea7d70dSdrh   **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
510750118cdfSdan   **
510850118cdfSdan   ** The second form is preferred as a single index (or temp-table) may be
510950118cdfSdan   ** used for both the ORDER BY and DISTINCT processing. As originally
511050118cdfSdan   ** written the query must use a temp-table for at least one of the ORDER
511150118cdfSdan   ** BY and DISTINCT, and an index or separate temp-table for the other.
511250118cdfSdan   */
511350118cdfSdan   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
5114adc57f68Sdrh    && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
511550118cdfSdan   ){
511650118cdfSdan     p->selFlags &= ~SF_Distinct;
5117adc57f68Sdrh     pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
5118e8e4af76Sdrh     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
5119e8e4af76Sdrh     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
5120e8e4af76Sdrh     ** original setting of the SF_Distinct flag, not the current setting */
5121e8e4af76Sdrh     assert( sDistinct.isTnct );
51227512cb47Sdrh 
51237512cb47Sdrh #if SELECTTRACE_ENABLED
51247512cb47Sdrh     if( sqlite3SelectTrace & 0x400 ){
51257512cb47Sdrh       SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
51267512cb47Sdrh       sqlite3TreeViewSelect(0, p, 0);
51277512cb47Sdrh     }
51287512cb47Sdrh #endif
512950118cdfSdan   }
513050118cdfSdan 
5131adc57f68Sdrh   /* If there is an ORDER BY clause, then create an ephemeral index to
5132adc57f68Sdrh   ** do the sorting.  But this sorting ephemeral index might end up
5133adc57f68Sdrh   ** being unused if the data can be extracted in pre-sorted order.
5134adc57f68Sdrh   ** If that is the case, then the OP_OpenEphemeral instruction will be
5135adc57f68Sdrh   ** changed to an OP_Noop once we figure out that the sorting index is
5136adc57f68Sdrh   ** not needed.  The sSort.addrSortIndex variable is used to facilitate
5137adc57f68Sdrh   ** that change.
51387cedc8d4Sdanielk1977   */
5139079a3072Sdrh   if( sSort.pOrderBy ){
51400342b1f5Sdrh     KeyInfo *pKeyInfo;
51413f39bcf5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
5142079a3072Sdrh     sSort.iECursor = pParse->nTab++;
5143079a3072Sdrh     sSort.addrSortIndex =
514466a5167bSdrh       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
5145f45f2326Sdrh           sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
5146f45f2326Sdrh           (char*)pKeyInfo, P4_KEYINFO
5147f45f2326Sdrh       );
51489d2985c7Sdrh   }else{
5149079a3072Sdrh     sSort.addrSortIndex = -1;
51507cedc8d4Sdanielk1977   }
51517cedc8d4Sdanielk1977 
51522d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
51532d0794e3Sdrh   */
51546c8c8ce0Sdanielk1977   if( pDest->eDest==SRT_EphemTab ){
51552b596da8Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
51562d0794e3Sdrh   }
51572d0794e3Sdrh 
5158f42bacc2Sdrh   /* Set the limiter.
5159f42bacc2Sdrh   */
5160f42bacc2Sdrh   iEnd = sqlite3VdbeMakeLabel(v);
5161c3489bbfSdrh   p->nSelectRow = 320;  /* 4 billion rows */
5162f42bacc2Sdrh   computeLimitRegisters(pParse, p, iEnd);
5163079a3072Sdrh   if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
51640ff287fbSdrh     sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
5165079a3072Sdrh     sSort.sortFlags |= SORTFLAG_UseSorter;
5166c6aff30cSdrh   }
5167f42bacc2Sdrh 
5168adc57f68Sdrh   /* Open an ephemeral index to use for the distinct set.
5169cce7d176Sdrh   */
51702ce22453Sdan   if( p->selFlags & SF_Distinct ){
5171e8e4af76Sdrh     sDistinct.tabTnct = pParse->nTab++;
5172e8e4af76Sdrh     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
5173e8e4af76Sdrh                              sDistinct.tabTnct, 0, 0,
5174079a3072Sdrh                              (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
51752ec2fb22Sdrh                              P4_KEYINFO);
5176d4187c71Sdrh     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
5177e8e4af76Sdrh     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
5178832508b7Sdrh   }else{
5179e8e4af76Sdrh     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
5180efb7251dSdrh   }
5181832508b7Sdrh 
518213449892Sdrh   if( !isAgg && pGroupBy==0 ){
5183e8e4af76Sdrh     /* No aggregate functions and no GROUP BY clause */
51846457a353Sdrh     u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
5185c3489bbfSdrh     assert( WHERE_USE_LIMIT==SF_FixedLimit );
5186c3489bbfSdrh     wctrlFlags |= p->selFlags & SF_FixedLimit;
518738cc40c2Sdan 
518838cc40c2Sdan     /* Begin the database scan. */
5189079a3072Sdrh     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
5190c3489bbfSdrh                                p->pEList, wctrlFlags, p->nSelectRow);
51911d83f052Sdrh     if( pWInfo==0 ) goto select_end;
51926f32848dSdrh     if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
51936f32848dSdrh       p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
51946f32848dSdrh     }
51956457a353Sdrh     if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
51966f32848dSdrh       sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
51976f32848dSdrh     }
5198079a3072Sdrh     if( sSort.pOrderBy ){
5199079a3072Sdrh       sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
5200*a536df4eSdrh       sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo);
5201079a3072Sdrh       if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
5202079a3072Sdrh         sSort.pOrderBy = 0;
5203079a3072Sdrh       }
5204079a3072Sdrh     }
5205cce7d176Sdrh 
5206b9bb7c18Sdrh     /* If sorting index that was created by a prior OP_OpenEphemeral
5207b9bb7c18Sdrh     ** instruction ended up not being needed, then change the OP_OpenEphemeral
52089d2985c7Sdrh     ** into an OP_Noop.
52099d2985c7Sdrh     */
5210079a3072Sdrh     if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
5211079a3072Sdrh       sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
52129d2985c7Sdrh     }
52139d2985c7Sdrh 
521438cc40c2Sdan     /* Use the standard inner loop. */
5215079a3072Sdrh     selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
52166f32848dSdrh                     sqlite3WhereContinueLabel(pWInfo),
52176f32848dSdrh                     sqlite3WhereBreakLabel(pWInfo));
52182282792aSdrh 
5219cce7d176Sdrh     /* End the database scan loop.
5220cce7d176Sdrh     */
52214adee20fSdanielk1977     sqlite3WhereEnd(pWInfo);
522213449892Sdrh   }else{
5223e8e4af76Sdrh     /* This case when there exist aggregate functions or a GROUP BY clause
5224e8e4af76Sdrh     ** or both */
522513449892Sdrh     NameContext sNC;    /* Name context for processing aggregate information */
522613449892Sdrh     int iAMem;          /* First Mem address for storing current GROUP BY */
522713449892Sdrh     int iBMem;          /* First Mem address for previous GROUP BY */
522813449892Sdrh     int iUseFlag;       /* Mem address holding flag indicating that at least
522913449892Sdrh                         ** one row of the input to the aggregator has been
523013449892Sdrh                         ** processed */
523113449892Sdrh     int iAbortFlag;     /* Mem address which causes query abort if positive */
523213449892Sdrh     int groupBySort;    /* Rows come from source in GROUP BY order */
5233d176611bSdrh     int addrEnd;        /* End of processing for this SELECT */
52341c9d835dSdrh     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
52351c9d835dSdrh     int sortOut = 0;    /* Output register from the sorter */
5236374cd78cSdan     int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
5237d176611bSdrh 
5238d176611bSdrh     /* Remove any and all aliases between the result set and the
5239d176611bSdrh     ** GROUP BY clause.
5240d176611bSdrh     */
5241d176611bSdrh     if( pGroupBy ){
5242dc5ea5c7Sdrh       int k;                        /* Loop counter */
5243d176611bSdrh       struct ExprList_item *pItem;  /* For looping over expression in a list */
5244d176611bSdrh 
5245dc5ea5c7Sdrh       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
5246c2acc4e4Sdrh         pItem->u.x.iAlias = 0;
5247d176611bSdrh       }
5248dc5ea5c7Sdrh       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
5249c2acc4e4Sdrh         pItem->u.x.iAlias = 0;
5250d176611bSdrh       }
5251c3489bbfSdrh       assert( 66==sqlite3LogEst(100) );
5252c3489bbfSdrh       if( p->nSelectRow>66 ) p->nSelectRow = 66;
525395aa47b1Sdrh     }else{
5254c3489bbfSdrh       assert( 0==sqlite3LogEst(1) );
5255c3489bbfSdrh       p->nSelectRow = 0;
5256d176611bSdrh     }
5257cce7d176Sdrh 
5258374cd78cSdan     /* If there is both a GROUP BY and an ORDER BY clause and they are
5259374cd78cSdan     ** identical, then it may be possible to disable the ORDER BY clause
5260374cd78cSdan     ** on the grounds that the GROUP BY will cause elements to come out
5261adc57f68Sdrh     ** in the correct order. It also may not - the GROUP BY might use a
5262374cd78cSdan     ** database index that causes rows to be grouped together as required
5263374cd78cSdan     ** but not actually sorted. Either way, record the fact that the
5264374cd78cSdan     ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
5265374cd78cSdan     ** variable.  */
5266374cd78cSdan     if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
5267374cd78cSdan       orderByGrp = 1;
5268374cd78cSdan     }
526913449892Sdrh 
5270d176611bSdrh     /* Create a label to jump to when we want to abort the query */
527113449892Sdrh     addrEnd = sqlite3VdbeMakeLabel(v);
527213449892Sdrh 
527313449892Sdrh     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
527413449892Sdrh     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
527513449892Sdrh     ** SELECT statement.
52762282792aSdrh     */
527713449892Sdrh     memset(&sNC, 0, sizeof(sNC));
527813449892Sdrh     sNC.pParse = pParse;
527913449892Sdrh     sNC.pSrcList = pTabList;
528013449892Sdrh     sNC.pAggInfo = &sAggInfo;
52817e61d18eSdrh     sAggInfo.mnReg = pParse->nMem+1;
5282dd23c6bfSdan     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
52839d2985c7Sdrh     sAggInfo.pGroupBy = pGroupBy;
5284d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pEList);
5285079a3072Sdrh     sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
5286d2b3e23bSdrh     if( pHaving ){
5287d2b3e23bSdrh       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
528813449892Sdrh     }
528913449892Sdrh     sAggInfo.nAccumulator = sAggInfo.nColumn;
529013449892Sdrh     for(i=0; i<sAggInfo.nFunc; i++){
52916ab3a2ecSdanielk1977       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
52923a8c4be7Sdrh       sNC.ncFlags |= NC_InAggFunc;
52936ab3a2ecSdanielk1977       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
52943a8c4be7Sdrh       sNC.ncFlags &= ~NC_InAggFunc;
529513449892Sdrh     }
52967e61d18eSdrh     sAggInfo.mxReg = pParse->nMem;
529717435752Sdrh     if( db->mallocFailed ) goto select_end;
529813449892Sdrh 
529913449892Sdrh     /* Processing for aggregates with GROUP BY is very different and
53003c4809a2Sdanielk1977     ** much more complex than aggregates without a GROUP BY.
530113449892Sdrh     */
530213449892Sdrh     if( pGroupBy ){
530313449892Sdrh       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
5304728e0f91Sdrh       int addr1;          /* A-vs-B comparision jump */
5305d176611bSdrh       int addrOutputRow;  /* Start of subroutine that outputs a result row */
5306d176611bSdrh       int regOutputRow;   /* Return address register for output subroutine */
5307d176611bSdrh       int addrSetAbort;   /* Set the abort flag and return */
5308d176611bSdrh       int addrTopOfLoop;  /* Top of the input loop */
5309d176611bSdrh       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
5310d176611bSdrh       int addrReset;      /* Subroutine for resetting the accumulator */
5311d176611bSdrh       int regReset;       /* Return address register for reset subroutine */
531213449892Sdrh 
531313449892Sdrh       /* If there is a GROUP BY clause we might need a sorting index to
531413449892Sdrh       ** implement it.  Allocate that sorting index now.  If it turns out
53151c9d835dSdrh       ** that we do not need it after all, the OP_SorterOpen instruction
531613449892Sdrh       ** will be converted into a Noop.
531713449892Sdrh       */
531813449892Sdrh       sAggInfo.sortingIdx = pParse->nTab++;
53193f39bcf5Sdrh       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
53201c9d835dSdrh       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
5321cd3e8f7cSdanielk1977           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
53222ec2fb22Sdrh           0, (char*)pKeyInfo, P4_KEYINFO);
532313449892Sdrh 
532413449892Sdrh       /* Initialize memory locations used by GROUP BY aggregate processing
532513449892Sdrh       */
53260a07c107Sdrh       iUseFlag = ++pParse->nMem;
53270a07c107Sdrh       iAbortFlag = ++pParse->nMem;
5328d176611bSdrh       regOutputRow = ++pParse->nMem;
5329d176611bSdrh       addrOutputRow = sqlite3VdbeMakeLabel(v);
5330d176611bSdrh       regReset = ++pParse->nMem;
5331d176611bSdrh       addrReset = sqlite3VdbeMakeLabel(v);
53320a07c107Sdrh       iAMem = pParse->nMem + 1;
533313449892Sdrh       pParse->nMem += pGroupBy->nExpr;
53340a07c107Sdrh       iBMem = pParse->nMem + 1;
533513449892Sdrh       pParse->nMem += pGroupBy->nExpr;
53364c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
5337d4e70ebdSdrh       VdbeComment((v, "clear abort flag"));
53384c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
5339d4e70ebdSdrh       VdbeComment((v, "indicate accumulator empty"));
5340b8475df8Sdrh       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
5341e313382eSdrh 
534213449892Sdrh       /* Begin a loop that will extract all source rows in GROUP BY order.
534313449892Sdrh       ** This might involve two separate loops with an OP_Sort in between, or
534413449892Sdrh       ** it might be a single loop that uses an index to extract information
534513449892Sdrh       ** in the right order to begin with.
534613449892Sdrh       */
53472eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
534893ec45d5Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
5349374cd78cSdan           WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
5350374cd78cSdan       );
53515360ad34Sdrh       if( pWInfo==0 ) goto select_end;
5352ddba0c22Sdrh       if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
535313449892Sdrh         /* The optimizer is able to deliver rows in group by order so
5354b9bb7c18Sdrh         ** we do not have to sort.  The OP_OpenEphemeral table will be
535513449892Sdrh         ** cancelled later because we still need to use the pKeyInfo
535613449892Sdrh         */
535713449892Sdrh         groupBySort = 0;
535813449892Sdrh       }else{
535913449892Sdrh         /* Rows are coming out in undetermined order.  We have to push
536013449892Sdrh         ** each row into a sorting index, terminate the first loop,
536113449892Sdrh         ** then loop over the sorting index in order to get the output
536213449892Sdrh         ** in sorted order
536313449892Sdrh         */
5364892d3179Sdrh         int regBase;
5365892d3179Sdrh         int regRecord;
5366892d3179Sdrh         int nCol;
5367892d3179Sdrh         int nGroupBy;
5368892d3179Sdrh 
53692ce22453Sdan         explainTempTable(pParse,
5370e8e4af76Sdrh             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
5371e8e4af76Sdrh                     "DISTINCT" : "GROUP BY");
53722ce22453Sdan 
537313449892Sdrh         groupBySort = 1;
5374892d3179Sdrh         nGroupBy = pGroupBy->nExpr;
5375dd23c6bfSdan         nCol = nGroupBy;
5376dd23c6bfSdan         j = nGroupBy;
537713449892Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
5378892d3179Sdrh           if( sAggInfo.aCol[i].iSorterColumn>=j ){
5379892d3179Sdrh             nCol++;
538013449892Sdrh             j++;
538113449892Sdrh           }
5382892d3179Sdrh         }
5383892d3179Sdrh         regBase = sqlite3GetTempRange(pParse, nCol);
5384ceea3321Sdrh         sqlite3ExprCacheClear(pParse);
53855579d59fSdrh         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
5386dd23c6bfSdan         j = nGroupBy;
5387892d3179Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
5388892d3179Sdrh           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
5389892d3179Sdrh           if( pCol->iSorterColumn>=j ){
5390e55cbd72Sdrh             int r1 = j + regBase;
5391ce78bc6eSdrh             sqlite3ExprCodeGetColumnToReg(pParse,
5392ce78bc6eSdrh                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
53936a012f04Sdrh             j++;
5394892d3179Sdrh           }
5395892d3179Sdrh         }
5396892d3179Sdrh         regRecord = sqlite3GetTempReg(pParse);
53971db639ceSdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
53981c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
5399892d3179Sdrh         sqlite3ReleaseTempReg(pParse, regRecord);
5400892d3179Sdrh         sqlite3ReleaseTempRange(pParse, regBase, nCol);
540113449892Sdrh         sqlite3WhereEnd(pWInfo);
54025134d135Sdan         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
54031c9d835dSdrh         sortOut = sqlite3GetTempReg(pParse);
54041c9d835dSdrh         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
54051c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
5406688852abSdrh         VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
540713449892Sdrh         sAggInfo.useSortingIdx = 1;
5408ceea3321Sdrh         sqlite3ExprCacheClear(pParse);
5409374cd78cSdan 
5410374cd78cSdan       }
5411374cd78cSdan 
5412374cd78cSdan       /* If the index or temporary table used by the GROUP BY sort
5413374cd78cSdan       ** will naturally deliver rows in the order required by the ORDER BY
5414374cd78cSdan       ** clause, cancel the ephemeral table open coded earlier.
5415374cd78cSdan       **
5416374cd78cSdan       ** This is an optimization - the correct answer should result regardless.
5417374cd78cSdan       ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
5418374cd78cSdan       ** disable this optimization for testing purposes.  */
5419374cd78cSdan       if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
5420374cd78cSdan        && (groupBySort || sqlite3WhereIsSorted(pWInfo))
5421374cd78cSdan       ){
5422374cd78cSdan         sSort.pOrderBy = 0;
5423374cd78cSdan         sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
542413449892Sdrh       }
542513449892Sdrh 
542613449892Sdrh       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
542713449892Sdrh       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
542813449892Sdrh       ** Then compare the current GROUP BY terms against the GROUP BY terms
542913449892Sdrh       ** from the previous row currently stored in a0, a1, a2...
543013449892Sdrh       */
543113449892Sdrh       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
5432ceea3321Sdrh       sqlite3ExprCacheClear(pParse);
54331c9d835dSdrh       if( groupBySort ){
543438b4149cSdrh         sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
543538b4149cSdrh                           sortOut, sortPTab);
54361c9d835dSdrh       }
543713449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
543813449892Sdrh         if( groupBySort ){
54391c9d835dSdrh           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
544013449892Sdrh         }else{
544113449892Sdrh           sAggInfo.directMode = 1;
54422dcef11bSdrh           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
544313449892Sdrh         }
544413449892Sdrh       }
544516ee60ffSdrh       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
54462ec2fb22Sdrh                           (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
5447728e0f91Sdrh       addr1 = sqlite3VdbeCurrentAddr(v);
5448728e0f91Sdrh       sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
544913449892Sdrh 
545013449892Sdrh       /* Generate code that runs whenever the GROUP BY changes.
5451e00ee6ebSdrh       ** Changes in the GROUP BY are detected by the previous code
545213449892Sdrh       ** block.  If there were no changes, this block is skipped.
545313449892Sdrh       **
545413449892Sdrh       ** This code copies current group by terms in b0,b1,b2,...
545513449892Sdrh       ** over to a0,a1,a2.  It then calls the output subroutine
545613449892Sdrh       ** and resets the aggregate accumulator registers in preparation
545713449892Sdrh       ** for the next GROUP BY batch.
545813449892Sdrh       */
5459b21e7c70Sdrh       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
54602eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
5461d4e70ebdSdrh       VdbeComment((v, "output one row"));
5462688852abSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
5463d4e70ebdSdrh       VdbeComment((v, "check abort flag"));
54642eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
5465d4e70ebdSdrh       VdbeComment((v, "reset accumulator"));
546613449892Sdrh 
546713449892Sdrh       /* Update the aggregate accumulators based on the content of
546813449892Sdrh       ** the current row
546913449892Sdrh       */
5470728e0f91Sdrh       sqlite3VdbeJumpHere(v, addr1);
547113449892Sdrh       updateAccumulator(pParse, &sAggInfo);
54724c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
5473d4e70ebdSdrh       VdbeComment((v, "indicate data in accumulator"));
547413449892Sdrh 
547513449892Sdrh       /* End of the loop
547613449892Sdrh       */
547713449892Sdrh       if( groupBySort ){
54781c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
5479688852abSdrh         VdbeCoverage(v);
548013449892Sdrh       }else{
548113449892Sdrh         sqlite3WhereEnd(pWInfo);
548248f2d3b1Sdrh         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
548313449892Sdrh       }
548413449892Sdrh 
548513449892Sdrh       /* Output the final row of result
548613449892Sdrh       */
54872eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
5488d4e70ebdSdrh       VdbeComment((v, "output final row"));
548913449892Sdrh 
5490d176611bSdrh       /* Jump over the subroutines
5491d176611bSdrh       */
5492076e85f5Sdrh       sqlite3VdbeGoto(v, addrEnd);
5493d176611bSdrh 
5494d176611bSdrh       /* Generate a subroutine that outputs a single row of the result
5495d176611bSdrh       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
5496d176611bSdrh       ** is less than or equal to zero, the subroutine is a no-op.  If
5497d176611bSdrh       ** the processing calls for the query to abort, this subroutine
5498d176611bSdrh       ** increments the iAbortFlag memory location before returning in
5499d176611bSdrh       ** order to signal the caller to abort.
5500d176611bSdrh       */
5501d176611bSdrh       addrSetAbort = sqlite3VdbeCurrentAddr(v);
5502d176611bSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
5503d176611bSdrh       VdbeComment((v, "set abort flag"));
5504d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5505d176611bSdrh       sqlite3VdbeResolveLabel(v, addrOutputRow);
5506d176611bSdrh       addrOutputRow = sqlite3VdbeCurrentAddr(v);
5507d176611bSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
550838b4149cSdrh       VdbeCoverage(v);
5509d176611bSdrh       VdbeComment((v, "Groupby result generator entry point"));
5510d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5511d176611bSdrh       finalizeAggFunctions(pParse, &sAggInfo);
5512d176611bSdrh       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
5513079a3072Sdrh       selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
5514e8e4af76Sdrh                       &sDistinct, pDest,
5515d176611bSdrh                       addrOutputRow+1, addrSetAbort);
5516d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5517d176611bSdrh       VdbeComment((v, "end groupby result generator"));
5518d176611bSdrh 
5519d176611bSdrh       /* Generate a subroutine that will reset the group-by accumulator
5520d176611bSdrh       */
5521d176611bSdrh       sqlite3VdbeResolveLabel(v, addrReset);
5522d176611bSdrh       resetAccumulator(pParse, &sAggInfo);
5523d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regReset);
5524d176611bSdrh 
552543152cf8Sdrh     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
552613449892Sdrh     else {
5527dba0137eSdanielk1977       ExprList *pDel = 0;
5528a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT
5529a5533162Sdanielk1977       Table *pTab;
5530a5533162Sdanielk1977       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
5531a5533162Sdanielk1977         /* If isSimpleCount() returns a pointer to a Table structure, then
5532a5533162Sdanielk1977         ** the SQL statement is of the form:
5533a5533162Sdanielk1977         **
5534a5533162Sdanielk1977         **   SELECT count(*) FROM <tbl>
5535a5533162Sdanielk1977         **
5536a5533162Sdanielk1977         ** where the Table structure returned represents table <tbl>.
5537a5533162Sdanielk1977         **
5538a5533162Sdanielk1977         ** This statement is so common that it is optimized specially. The
5539a5533162Sdanielk1977         ** OP_Count instruction is executed either on the intkey table that
5540a5533162Sdanielk1977         ** contains the data for table <tbl> or on one of its indexes. It
5541a5533162Sdanielk1977         ** is better to execute the op on an index, as indexes are almost
5542a5533162Sdanielk1977         ** always spread across less pages than their corresponding tables.
5543a5533162Sdanielk1977         */
5544a5533162Sdanielk1977         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
5545a5533162Sdanielk1977         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
5546a5533162Sdanielk1977         Index *pIdx;                         /* Iterator variable */
5547a5533162Sdanielk1977         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
5548a5533162Sdanielk1977         Index *pBest = 0;                    /* Best index found so far */
5549a5533162Sdanielk1977         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
5550a9d1ccb9Sdanielk1977 
5551a5533162Sdanielk1977         sqlite3CodeVerifySchema(pParse, iDb);
5552a5533162Sdanielk1977         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
5553a5533162Sdanielk1977 
5554d9e3cad2Sdrh         /* Search for the index that has the lowest scan cost.
5555a5533162Sdanielk1977         **
55563e9548b3Sdrh         ** (2011-04-15) Do not do a full scan of an unordered index.
55573e9548b3Sdrh         **
5558abcc1941Sdrh         ** (2013-10-03) Do not count the entries in a partial index.
55595f33f375Sdrh         **
5560a5533162Sdanielk1977         ** In practice the KeyInfo structure will not be used. It is only
5561a5533162Sdanielk1977         ** passed to keep OP_OpenRead happy.
5562a5533162Sdanielk1977         */
55635c7917e4Sdrh         if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
5564a5533162Sdanielk1977         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
5565d9e3cad2Sdrh           if( pIdx->bUnordered==0
5566e13e9f54Sdrh            && pIdx->szIdxRow<pTab->szTabRow
5567d3037a41Sdrh            && pIdx->pPartIdxWhere==0
5568e13e9f54Sdrh            && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
5569d9e3cad2Sdrh           ){
5570a5533162Sdanielk1977             pBest = pIdx;
5571a5533162Sdanielk1977           }
5572a5533162Sdanielk1977         }
5573d9e3cad2Sdrh         if( pBest ){
5574a5533162Sdanielk1977           iRoot = pBest->tnum;
55752ec2fb22Sdrh           pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
5576a5533162Sdanielk1977         }
5577a5533162Sdanielk1977 
5578a5533162Sdanielk1977         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
5579261c02d9Sdrh         sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
5580a5533162Sdanielk1977         if( pKeyInfo ){
55812ec2fb22Sdrh           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
5582a5533162Sdanielk1977         }
5583a5533162Sdanielk1977         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
5584a5533162Sdanielk1977         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
5585ef7075deSdan         explainSimpleCount(pParse, pTab, pBest);
5586a5533162Sdanielk1977       }else
5587a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */
5588a5533162Sdanielk1977       {
5589738bdcfbSdanielk1977         /* Check if the query is of one of the following forms:
5590738bdcfbSdanielk1977         **
5591738bdcfbSdanielk1977         **   SELECT min(x) FROM ...
5592738bdcfbSdanielk1977         **   SELECT max(x) FROM ...
5593738bdcfbSdanielk1977         **
5594738bdcfbSdanielk1977         ** If it is, then ask the code in where.c to attempt to sort results
5595738bdcfbSdanielk1977         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
5596738bdcfbSdanielk1977         ** If where.c is able to produce results sorted in this order, then
5597738bdcfbSdanielk1977         ** add vdbe code to break out of the processing loop after the
5598738bdcfbSdanielk1977         ** first iteration (since the first iteration of the loop is
5599738bdcfbSdanielk1977         ** guaranteed to operate on the row with the minimum or maximum
5600738bdcfbSdanielk1977         ** value of x, the only row required).
5601738bdcfbSdanielk1977         **
5602738bdcfbSdanielk1977         ** A special flag must be passed to sqlite3WhereBegin() to slightly
560348864df9Smistachkin         ** modify behavior as follows:
5604738bdcfbSdanielk1977         **
5605738bdcfbSdanielk1977         **   + If the query is a "SELECT min(x)", then the loop coded by
5606738bdcfbSdanielk1977         **     where.c should not iterate over any values with a NULL value
5607738bdcfbSdanielk1977         **     for x.
5608738bdcfbSdanielk1977         **
5609738bdcfbSdanielk1977         **   + The optimizer code in where.c (the thing that decides which
5610738bdcfbSdanielk1977         **     index or indices to use) should place a different priority on
5611738bdcfbSdanielk1977         **     satisfying the 'ORDER BY' clause than it does in other cases.
5612738bdcfbSdanielk1977         **     Refer to code and comments in where.c for details.
5613738bdcfbSdanielk1977         */
5614a5533162Sdanielk1977         ExprList *pMinMax = 0;
56154ac391fcSdan         u8 flag = WHERE_ORDERBY_NORMAL;
56164ac391fcSdan 
56174ac391fcSdan         assert( p->pGroupBy==0 );
56184ac391fcSdan         assert( flag==0 );
56194ac391fcSdan         if( p->pHaving==0 ){
56204ac391fcSdan           flag = minMaxQuery(&sAggInfo, &pMinMax);
56214ac391fcSdan         }
56224ac391fcSdan         assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
56234ac391fcSdan 
5624a9d1ccb9Sdanielk1977         if( flag ){
56254ac391fcSdan           pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
56266ab3a2ecSdanielk1977           pDel = pMinMax;
56274a642b60Sdrh           assert( db->mallocFailed || pMinMax!=0 );
56284a642b60Sdrh           if( !db->mallocFailed ){
5629ea678832Sdrh             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
5630a9d1ccb9Sdanielk1977             pMinMax->a[0].pExpr->op = TK_COLUMN;
5631a9d1ccb9Sdanielk1977           }
56321013c932Sdrh         }
5633a9d1ccb9Sdanielk1977 
563413449892Sdrh         /* This case runs if the aggregate has no GROUP BY clause.  The
563513449892Sdrh         ** processing is much simpler since there is only a single row
563613449892Sdrh         ** of output.
563713449892Sdrh         */
563813449892Sdrh         resetAccumulator(pParse, &sAggInfo);
563946ec5b63Sdrh         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
5640dba0137eSdanielk1977         if( pWInfo==0 ){
5641633e6d57Sdrh           sqlite3ExprListDelete(db, pDel);
5642dba0137eSdanielk1977           goto select_end;
5643dba0137eSdanielk1977         }
564413449892Sdrh         updateAccumulator(pParse, &sAggInfo);
564546c35f9bSdrh         assert( pMinMax==0 || pMinMax->nExpr==1 );
5646ddba0c22Sdrh         if( sqlite3WhereIsOrdered(pWInfo)>0 ){
5647076e85f5Sdrh           sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
5648a5533162Sdanielk1977           VdbeComment((v, "%s() by index",
5649a5533162Sdanielk1977                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
5650a9d1ccb9Sdanielk1977         }
565113449892Sdrh         sqlite3WhereEnd(pWInfo);
565213449892Sdrh         finalizeAggFunctions(pParse, &sAggInfo);
56537a895a80Sdanielk1977       }
56547a895a80Sdanielk1977 
5655079a3072Sdrh       sSort.pOrderBy = 0;
565635573356Sdrh       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
5657079a3072Sdrh       selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
5658a9671a22Sdrh                       pDest, addrEnd, addrEnd);
5659633e6d57Sdrh       sqlite3ExprListDelete(db, pDel);
566013449892Sdrh     }
566113449892Sdrh     sqlite3VdbeResolveLabel(v, addrEnd);
566213449892Sdrh 
566313449892Sdrh   } /* endif aggregate query */
56642282792aSdrh 
5665e8e4af76Sdrh   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
56662ce22453Sdan     explainTempTable(pParse, "DISTINCT");
56672ce22453Sdan   }
56682ce22453Sdan 
5669cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
5670cce7d176Sdrh   ** and send them to the callback one by one.
5671cce7d176Sdrh   */
5672079a3072Sdrh   if( sSort.pOrderBy ){
567338b4149cSdrh     explainTempTable(pParse,
567438b4149cSdrh                      sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
5675079a3072Sdrh     generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
5676cce7d176Sdrh   }
56776a535340Sdrh 
5678ec7429aeSdrh   /* Jump here to skip this query
5679ec7429aeSdrh   */
5680ec7429aeSdrh   sqlite3VdbeResolveLabel(v, iEnd);
5681ec7429aeSdrh 
56825b1c07e7Sdan   /* The SELECT has been coded. If there is an error in the Parse structure,
56835b1c07e7Sdan   ** set the return code to 1. Otherwise 0. */
56845b1c07e7Sdan   rc = (pParse->nErr>0);
56851d83f052Sdrh 
56861d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
56871d83f052Sdrh   ** successful coding of the SELECT.
56881d83f052Sdrh   */
56891d83f052Sdrh select_end:
569017c0bc0cSdan   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
5691955de52cSdanielk1977 
56927d10d5a6Sdrh   /* Identify column names if results of the SELECT are to be output.
5693955de52cSdanielk1977   */
56947d10d5a6Sdrh   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
5695955de52cSdanielk1977     generateColumnNames(pParse, pTabList, pEList);
5696955de52cSdanielk1977   }
5697955de52cSdanielk1977 
5698633e6d57Sdrh   sqlite3DbFree(db, sAggInfo.aCol);
5699633e6d57Sdrh   sqlite3DbFree(db, sAggInfo.aFunc);
5700eb9b884cSdrh #if SELECTTRACE_ENABLED
5701eb9b884cSdrh   SELECTTRACE(1,pParse,p,("end processing\n"));
5702eb9b884cSdrh   pParse->nSelectIndent--;
5703eb9b884cSdrh #endif
57041d83f052Sdrh   return rc;
5705cce7d176Sdrh }
5706