xref: /sqlite-3.40.0/src/select.c (revision 23768298)
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 */
59a536df4eSdrh   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);
79dbd6a7dcSdrh     if( bFree ) sqlite3DbFreeNN(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;
9171c57db0Sdan   pDest->zAffSdst = 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;
115ef90a6b8Sdrh   pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
116daffd0e5Sdrh   if( pNew==0 ){
117ef90a6b8Sdrh     assert( pParse->db->mallocFailed );
118eda639e1Sdrh     pNew = &standin;
119eda639e1Sdrh   }
120b733d037Sdrh   if( pEList==0 ){
1213d240d21Sdrh     pEList = sqlite3ExprListAppend(pParse, 0,
1223d240d21Sdrh                                    sqlite3Expr(pParse->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;
135ef90a6b8Sdrh   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->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;
1463d240d21Sdrh   assert( pOffset==0 || pLimit!=0 || pParse->nErr>0
1473d240d21Sdrh                      || pParse->db->mallocFailed!=0 );
148ef90a6b8Sdrh   if( pParse->db->mallocFailed ) {
149ef90a6b8Sdrh     clearSelect(pParse->db, pNew, pNew!=&standin);
150eda639e1Sdrh     pNew = 0;
151a464c234Sdrh   }else{
152a464c234Sdrh     assert( pNew->pSrc!=0 || pParse->nErr>0 );
153daffd0e5Sdrh   }
154338ec3e1Sdrh   assert( pNew!=&standin );
1559bb61fe7Sdrh   return pNew;
1569bb61fe7Sdrh }
1579bb61fe7Sdrh 
158eb9b884cSdrh #if SELECTTRACE_ENABLED
159eb9b884cSdrh /*
160eb9b884cSdrh ** Set the name of a Select object
161eb9b884cSdrh */
162eb9b884cSdrh void sqlite3SelectSetName(Select *p, const char *zName){
163eb9b884cSdrh   if( p && zName ){
164eb9b884cSdrh     sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
165eb9b884cSdrh   }
166eb9b884cSdrh }
167eb9b884cSdrh #endif
168eb9b884cSdrh 
169eb9b884cSdrh 
1709bb61fe7Sdrh /*
171eda639e1Sdrh ** Delete the given Select structure and all of its substructures.
172eda639e1Sdrh */
173633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){
174f3c57ff5Sdrh   if( p ) clearSelect(db, p, 1);
175eda639e1Sdrh }
176eda639e1Sdrh 
177eda639e1Sdrh /*
178d227a291Sdrh ** Return a pointer to the right-most SELECT statement in a compound.
179d227a291Sdrh */
180d227a291Sdrh static Select *findRightmost(Select *p){
181d227a291Sdrh   while( p->pNext ) p = p->pNext;
182d227a291Sdrh   return p;
1839bb61fe7Sdrh }
1849bb61fe7Sdrh 
1859bb61fe7Sdrh /*
186f7b5496eSdrh ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
18701f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
18801f3f253Sdrh ** in terms of the following bit values:
18901f3f253Sdrh **
19001f3f253Sdrh **     JT_INNER
1913dec223cSdrh **     JT_CROSS
19201f3f253Sdrh **     JT_OUTER
19301f3f253Sdrh **     JT_NATURAL
19401f3f253Sdrh **     JT_LEFT
19501f3f253Sdrh **     JT_RIGHT
19601f3f253Sdrh **
19701f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
19801f3f253Sdrh **
19901f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
20001f3f253Sdrh ** a join type, but put an error in the pParse structure.
20101f3f253Sdrh */
2024adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
20301f3f253Sdrh   int jointype = 0;
20401f3f253Sdrh   Token *apAll[3];
20501f3f253Sdrh   Token *p;
206373cc2ddSdrh                              /*   0123456789 123456789 123456789 123 */
207373cc2ddSdrh   static const char zKeyText[] = "naturaleftouterightfullinnercross";
2085719628aSdrh   static const struct {
209373cc2ddSdrh     u8 i;        /* Beginning of keyword text in zKeyText[] */
210373cc2ddSdrh     u8 nChar;    /* Length of the keyword in characters */
211373cc2ddSdrh     u8 code;     /* Join type mask */
212373cc2ddSdrh   } aKeyword[] = {
213373cc2ddSdrh     /* natural */ { 0,  7, JT_NATURAL                },
214373cc2ddSdrh     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
215373cc2ddSdrh     /* outer   */ { 10, 5, JT_OUTER                  },
216373cc2ddSdrh     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
217373cc2ddSdrh     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
218373cc2ddSdrh     /* inner   */ { 23, 5, JT_INNER                  },
219373cc2ddSdrh     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
22001f3f253Sdrh   };
22101f3f253Sdrh   int i, j;
22201f3f253Sdrh   apAll[0] = pA;
22301f3f253Sdrh   apAll[1] = pB;
22401f3f253Sdrh   apAll[2] = pC;
225195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
22601f3f253Sdrh     p = apAll[i];
227373cc2ddSdrh     for(j=0; j<ArraySize(aKeyword); j++){
228373cc2ddSdrh       if( p->n==aKeyword[j].nChar
229373cc2ddSdrh           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
230373cc2ddSdrh         jointype |= aKeyword[j].code;
23101f3f253Sdrh         break;
23201f3f253Sdrh       }
23301f3f253Sdrh     }
234373cc2ddSdrh     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
235373cc2ddSdrh     if( j>=ArraySize(aKeyword) ){
23601f3f253Sdrh       jointype |= JT_ERROR;
23701f3f253Sdrh       break;
23801f3f253Sdrh     }
23901f3f253Sdrh   }
240ad2d8307Sdrh   if(
241ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
242195e6967Sdrh      (jointype & JT_ERROR)!=0
243ad2d8307Sdrh   ){
244a9671a22Sdrh     const char *zSp = " ";
245a9671a22Sdrh     assert( pB!=0 );
246a9671a22Sdrh     if( pC==0 ){ zSp++; }
247ae29ffbeSdrh     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
248a9671a22Sdrh        "%T %T%s%T", pA, pB, zSp, pC);
24901f3f253Sdrh     jointype = JT_INNER;
250373cc2ddSdrh   }else if( (jointype & JT_OUTER)!=0
251373cc2ddSdrh          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
2524adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
253da93d238Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported");
254195e6967Sdrh     jointype = JT_INNER;
25501f3f253Sdrh   }
25601f3f253Sdrh   return jointype;
25701f3f253Sdrh }
25801f3f253Sdrh 
25901f3f253Sdrh /*
260ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
261ad2d8307Sdrh ** is not contained in the table.
262ad2d8307Sdrh */
263ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
264ad2d8307Sdrh   int i;
265ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
2664adee20fSdanielk1977     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
267ad2d8307Sdrh   }
268ad2d8307Sdrh   return -1;
269ad2d8307Sdrh }
270ad2d8307Sdrh 
271ad2d8307Sdrh /*
2722179b434Sdrh ** Search the first N tables in pSrc, from left to right, looking for a
2732179b434Sdrh ** table that has a column named zCol.
2742179b434Sdrh **
2752179b434Sdrh ** When found, set *piTab and *piCol to the table index and column index
2762179b434Sdrh ** of the matching column and return TRUE.
2772179b434Sdrh **
2782179b434Sdrh ** If not found, return FALSE.
2792179b434Sdrh */
2802179b434Sdrh static int tableAndColumnIndex(
2812179b434Sdrh   SrcList *pSrc,       /* Array of tables to search */
2822179b434Sdrh   int N,               /* Number of tables in pSrc->a[] to search */
2832179b434Sdrh   const char *zCol,    /* Name of the column we are looking for */
2842179b434Sdrh   int *piTab,          /* Write index of pSrc->a[] here */
2852179b434Sdrh   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
2862179b434Sdrh ){
2872179b434Sdrh   int i;               /* For looping over tables in pSrc */
2882179b434Sdrh   int iCol;            /* Index of column matching zCol */
2892179b434Sdrh 
2902179b434Sdrh   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
2912179b434Sdrh   for(i=0; i<N; i++){
2922179b434Sdrh     iCol = columnIndex(pSrc->a[i].pTab, zCol);
2932179b434Sdrh     if( iCol>=0 ){
2942179b434Sdrh       if( piTab ){
2952179b434Sdrh         *piTab = i;
2962179b434Sdrh         *piCol = iCol;
2972179b434Sdrh       }
2982179b434Sdrh       return 1;
2992179b434Sdrh     }
3002179b434Sdrh   }
3012179b434Sdrh   return 0;
3022179b434Sdrh }
3032179b434Sdrh 
3042179b434Sdrh /*
305f7b0b0adSdan ** This function is used to add terms implied by JOIN syntax to the
306f7b0b0adSdan ** WHERE clause expression of a SELECT statement. The new term, which
307f7b0b0adSdan ** is ANDed with the existing WHERE clause, is of the form:
308f7b0b0adSdan **
309f7b0b0adSdan **    (tab1.col1 = tab2.col2)
310f7b0b0adSdan **
311f7b0b0adSdan ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
312f7b0b0adSdan ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
313f7b0b0adSdan ** column iColRight of tab2.
314ad2d8307Sdrh */
315ad2d8307Sdrh static void addWhereTerm(
31617435752Sdrh   Parse *pParse,                  /* Parsing context */
317f7b0b0adSdan   SrcList *pSrc,                  /* List of tables in FROM clause */
3182179b434Sdrh   int iLeft,                      /* Index of first table to join in pSrc */
319f7b0b0adSdan   int iColLeft,                   /* Index of column in first table */
3202179b434Sdrh   int iRight,                     /* Index of second table in pSrc */
321f7b0b0adSdan   int iColRight,                  /* Index of column in second table */
322f7b0b0adSdan   int isOuterJoin,                /* True if this is an OUTER join */
323f7b0b0adSdan   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
324ad2d8307Sdrh ){
325f7b0b0adSdan   sqlite3 *db = pParse->db;
326f7b0b0adSdan   Expr *pE1;
327f7b0b0adSdan   Expr *pE2;
328f7b0b0adSdan   Expr *pEq;
329ad2d8307Sdrh 
3302179b434Sdrh   assert( iLeft<iRight );
3312179b434Sdrh   assert( pSrc->nSrc>iRight );
3322179b434Sdrh   assert( pSrc->a[iLeft].pTab );
3332179b434Sdrh   assert( pSrc->a[iRight].pTab );
334f7b0b0adSdan 
3352179b434Sdrh   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
3362179b434Sdrh   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
337f7b0b0adSdan 
338abfd35eaSdrh   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
339f7b0b0adSdan   if( pEq && isOuterJoin ){
340f7b0b0adSdan     ExprSetProperty(pEq, EP_FromJoin);
341c5cd1249Sdrh     assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
342ebb6a65dSdrh     ExprSetVVAProperty(pEq, EP_NoReduce);
343f7b0b0adSdan     pEq->iRightJoinTable = (i16)pE2->iTable;
344030530deSdrh   }
345f7b0b0adSdan   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
346ad2d8307Sdrh }
347ad2d8307Sdrh 
348ad2d8307Sdrh /*
3491f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
35022d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the
35122d6a53aSdrh ** expression.
3521cc093c2Sdrh **
353e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
3541cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
3551f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
3561f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
3571f16230bSdrh ** WHERE clause during join processing but we need to remember that they
3581f16230bSdrh ** originated in the ON or USING clause.
35922d6a53aSdrh **
36022d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the
36122d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not
36222d6a53aSdrh ** explicitly mentioned in the expression.  That information is needed
36322d6a53aSdrh ** for cases like this:
36422d6a53aSdrh **
36522d6a53aSdrh **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
36622d6a53aSdrh **
36722d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5
36822d6a53aSdrh ** term until after the t2 loop of the join.  In that way, a
36922d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
37022d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately
37122d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in
37222d6a53aSdrh ** the output, which is incorrect.
3731cc093c2Sdrh */
37422d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){
3751cc093c2Sdrh   while( p ){
3761f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
377c5cd1249Sdrh     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
378ebb6a65dSdrh     ExprSetVVAProperty(p, EP_NoReduce);
379cf697396Sshane     p->iRightJoinTable = (i16)iTable;
380606f2344Sdrh     if( p->op==TK_FUNCTION && p->x.pList ){
381606f2344Sdrh       int i;
382606f2344Sdrh       for(i=0; i<p->x.pList->nExpr; i++){
383606f2344Sdrh         setJoinExpr(p->x.pList->a[i].pExpr, iTable);
384606f2344Sdrh       }
385606f2344Sdrh     }
38622d6a53aSdrh     setJoinExpr(p->pLeft, iTable);
3871cc093c2Sdrh     p = p->pRight;
3881cc093c2Sdrh   }
3891cc093c2Sdrh }
3901cc093c2Sdrh 
3911cc093c2Sdrh /*
392ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
393ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
394ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
395ad2d8307Sdrh **
39691bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure.
39791bb0eedSdrh ** The left most table is the first entry in Select.pSrc.  The right-most
39891bb0eedSdrh ** table is the last entry.  The join operator is held in the entry to
39991bb0eedSdrh ** the left.  Thus entry 0 contains the join operator for the join between
40091bb0eedSdrh ** entries 0 and 1.  Any ON or USING clauses associated with the join are
40191bb0eedSdrh ** also attached to the left entry.
40291bb0eedSdrh **
403ad2d8307Sdrh ** This routine returns the number of errors encountered.
404ad2d8307Sdrh */
405ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
40691bb0eedSdrh   SrcList *pSrc;                  /* All tables in the FROM clause */
40791bb0eedSdrh   int i, j;                       /* Loop counters */
40891bb0eedSdrh   struct SrcList_item *pLeft;     /* Left table being joined */
40991bb0eedSdrh   struct SrcList_item *pRight;    /* Right table being joined */
410ad2d8307Sdrh 
41191bb0eedSdrh   pSrc = p->pSrc;
41291bb0eedSdrh   pLeft = &pSrc->a[0];
41391bb0eedSdrh   pRight = &pLeft[1];
41491bb0eedSdrh   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
41591bb0eedSdrh     Table *pLeftTab = pLeft->pTab;
41691bb0eedSdrh     Table *pRightTab = pRight->pTab;
417ad27e761Sdrh     int isOuter;
41891bb0eedSdrh 
4191c767f0dSdrh     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
4208a48b9c0Sdrh     isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
421ad2d8307Sdrh 
422ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
423ad2d8307Sdrh     ** every column that the two tables have in common.
424ad2d8307Sdrh     */
4258a48b9c0Sdrh     if( pRight->fg.jointype & JT_NATURAL ){
42661dfc31dSdrh       if( pRight->pOn || pRight->pUsing ){
4274adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
428ad2d8307Sdrh            "an ON or USING clause", 0);
429ad2d8307Sdrh         return 1;
430ad2d8307Sdrh       }
4312179b434Sdrh       for(j=0; j<pRightTab->nCol; j++){
4322179b434Sdrh         char *zName;   /* Name of column in the right table */
4332179b434Sdrh         int iLeft;     /* Matching left table */
4342179b434Sdrh         int iLeftCol;  /* Matching column in the left table */
4352179b434Sdrh 
4362179b434Sdrh         zName = pRightTab->aCol[j].zName;
4372179b434Sdrh         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
4382179b434Sdrh           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
4392179b434Sdrh                        isOuter, &p->pWhere);
440ad2d8307Sdrh         }
441ad2d8307Sdrh       }
442ad2d8307Sdrh     }
443ad2d8307Sdrh 
444ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
445ad2d8307Sdrh     */
44661dfc31dSdrh     if( pRight->pOn && pRight->pUsing ){
4474adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
448da93d238Sdrh         "clauses in the same join");
449ad2d8307Sdrh       return 1;
450ad2d8307Sdrh     }
451ad2d8307Sdrh 
452ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
45391bb0eedSdrh     ** an AND operator.
454ad2d8307Sdrh     */
45561dfc31dSdrh     if( pRight->pOn ){
456ad27e761Sdrh       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
45717435752Sdrh       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
45861dfc31dSdrh       pRight->pOn = 0;
459ad2d8307Sdrh     }
460ad2d8307Sdrh 
461ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
462ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
463ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
464ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
465ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
466ad2d8307Sdrh     ** not contained in both tables to be joined.
467ad2d8307Sdrh     */
46861dfc31dSdrh     if( pRight->pUsing ){
46961dfc31dSdrh       IdList *pList = pRight->pUsing;
470ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
4712179b434Sdrh         char *zName;     /* Name of the term in the USING clause */
4722179b434Sdrh         int iLeft;       /* Table on the left with matching column name */
4732179b434Sdrh         int iLeftCol;    /* Column number of matching column on the left */
4742179b434Sdrh         int iRightCol;   /* Column number of matching column on the right */
4752179b434Sdrh 
4762179b434Sdrh         zName = pList->a[j].zName;
4772179b434Sdrh         iRightCol = columnIndex(pRightTab, zName);
4782179b434Sdrh         if( iRightCol<0
4792179b434Sdrh          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
4802179b434Sdrh         ){
4814adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
48291bb0eedSdrh             "not present in both tables", zName);
483ad2d8307Sdrh           return 1;
484ad2d8307Sdrh         }
4852179b434Sdrh         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
4862179b434Sdrh                      isOuter, &p->pWhere);
487ad2d8307Sdrh       }
488ad2d8307Sdrh     }
489ad2d8307Sdrh   }
490ad2d8307Sdrh   return 0;
491ad2d8307Sdrh }
492ad2d8307Sdrh 
493079a3072Sdrh /* Forward reference */
494079a3072Sdrh static KeyInfo *keyInfoFromExprList(
495079a3072Sdrh   Parse *pParse,       /* Parsing context */
496079a3072Sdrh   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
497079a3072Sdrh   int iStart,          /* Begin with this column of pList */
498079a3072Sdrh   int nExtra           /* Add this many extra columns to the end */
499079a3072Sdrh );
500079a3072Sdrh 
501ad2d8307Sdrh /*
502f45f2326Sdrh ** Generate code that will push the record in registers regData
503f45f2326Sdrh ** through regData+nData-1 onto the sorter.
504c926afbcSdrh */
505d59ba6ceSdrh static void pushOntoSorter(
506d59ba6ceSdrh   Parse *pParse,         /* Parser context */
507079a3072Sdrh   SortCtx *pSort,        /* Information about the ORDER BY clause */
508b7654111Sdrh   Select *pSelect,       /* The whole SELECT statement */
509f45f2326Sdrh   int regData,           /* First register holding data to be sorted */
5105579d59fSdrh   int regOrigData,       /* First register holding data before packing */
511fd0a2f97Sdrh   int nData,             /* Number of elements in the data array */
512fd0a2f97Sdrh   int nPrefixReg         /* No. of reg prior to regData available for use */
513d59ba6ceSdrh ){
514f45f2326Sdrh   Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
51578d58432Sdan   int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
516f45f2326Sdrh   int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
51778d58432Sdan   int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
518fd0a2f97Sdrh   int regBase;                                     /* Regs for sorter record */
519fb0d6e56Sdrh   int regRecord = ++pParse->nMem;                  /* Assembled sorter record */
52078d58432Sdan   int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
521f45f2326Sdrh   int op;                            /* Opcode to add sorter record to sorter */
522a04a8be2Sdrh   int iLimit;                        /* LIMIT counter */
523f45f2326Sdrh 
52478d58432Sdan   assert( bSeq==0 || bSeq==1 );
5259af90b72Sdan   assert( nData==1 || regData==regOrigData || regOrigData==0 );
526fd0a2f97Sdrh   if( nPrefixReg ){
52778d58432Sdan     assert( nPrefixReg==nExpr+bSeq );
52878d58432Sdan     regBase = regData - nExpr - bSeq;
529fd0a2f97Sdrh   }else{
530fb0d6e56Sdrh     regBase = pParse->nMem + 1;
531fb0d6e56Sdrh     pParse->nMem += nBase;
532fd0a2f97Sdrh   }
533a04a8be2Sdrh   assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
534a04a8be2Sdrh   iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
535a04a8be2Sdrh   pSort->labelDone = sqlite3VdbeMakeLabel(v);
5365579d59fSdrh   sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
5379af90b72Sdan                           SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
53878d58432Sdan   if( bSeq ){
539079a3072Sdrh     sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
540fd0a2f97Sdrh   }
541257c13faSdan   if( nPrefixReg==0 && nData>0 ){
542236241aeSdrh     sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
54378d58432Sdan   }
544f45f2326Sdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
545079a3072Sdrh   if( nOBSat>0 ){
546079a3072Sdrh     int regPrevKey;   /* The first nOBSat columns of the previous row */
547079a3072Sdrh     int addrFirst;    /* Address of the OP_IfNot opcode */
548079a3072Sdrh     int addrJmp;      /* Address of the OP_Jump opcode */
549079a3072Sdrh     VdbeOp *pOp;      /* Opcode that opens the sorter */
550079a3072Sdrh     int nKey;         /* Number of sorting key columns, including OP_Sequence */
551dbfca2b7Sdrh     KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
552079a3072Sdrh 
55326d7e7c6Sdrh     regPrevKey = pParse->nMem+1;
55426d7e7c6Sdrh     pParse->nMem += pSort->nOBSat;
55578d58432Sdan     nKey = nExpr - pSort->nOBSat + bSeq;
55678d58432Sdan     if( bSeq ){
55778d58432Sdan       addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
55878d58432Sdan     }else{
55978d58432Sdan       addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
56078d58432Sdan     }
56178d58432Sdan     VdbeCoverage(v);
56226d7e7c6Sdrh     sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
563079a3072Sdrh     pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
56459b8f2e1Sdrh     if( pParse->db->mallocFailed ) return;
565fb0d6e56Sdrh     pOp->p2 = nKey + nData;
566dbfca2b7Sdrh     pKI = pOp->p4.pKeyInfo;
567a485ad19Sdrh     memset(pKI->aSortOrder, 0, pKI->nKeyField); /* Makes OP_Jump testable */
568dbfca2b7Sdrh     sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
569a485ad19Sdrh     testcase( pKI->nAllField > pKI->nKeyField+2 );
570fe201effSdrh     pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
571a485ad19Sdrh                                            pKI->nAllField-pKI->nKeyField-1);
572079a3072Sdrh     addrJmp = sqlite3VdbeCurrentAddr(v);
573079a3072Sdrh     sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
574079a3072Sdrh     pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
575079a3072Sdrh     pSort->regReturn = ++pParse->nMem;
576079a3072Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
57765ea12cbSdrh     sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
578a04a8be2Sdrh     if( iLimit ){
579a04a8be2Sdrh       sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
580a04a8be2Sdrh       VdbeCoverage(v);
581a04a8be2Sdrh     }
582079a3072Sdrh     sqlite3VdbeJumpHere(v, addrFirst);
583236241aeSdrh     sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
584079a3072Sdrh     sqlite3VdbeJumpHere(v, addrJmp);
585079a3072Sdrh   }
586079a3072Sdrh   if( pSort->sortFlags & SORTFLAG_UseSorter ){
587c6aff30cSdrh     op = OP_SorterInsert;
588c6aff30cSdrh   }else{
589c6aff30cSdrh     op = OP_IdxInsert;
590c6aff30cSdrh   }
5914a8b013eSdrh   sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
5924a8b013eSdrh                        regBase+nOBSat, nBase-nOBSat);
593a04a8be2Sdrh   if( iLimit ){
59416897072Sdrh     int addr;
595a536df4eSdrh     int r1 = 0;
596a536df4eSdrh     /* Fill the sorter until it contains LIMIT+OFFSET entries.  (The iLimit
597a536df4eSdrh     ** register is initialized with value of LIMIT+OFFSET.)  After the sorter
598a536df4eSdrh     ** fills up, delete the least entry in the sorter after each insert.
599a536df4eSdrh     ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */
600f99dd359Sdrh     addr = sqlite3VdbeAddOp1(v, OP_IfNotZero, iLimit); VdbeCoverage(v);
601079a3072Sdrh     sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
602a536df4eSdrh     if( pSort->bOrderedInnerLoop ){
603a536df4eSdrh       r1 = ++pParse->nMem;
604a536df4eSdrh       sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1);
605a536df4eSdrh       VdbeComment((v, "seq"));
606a536df4eSdrh     }
607079a3072Sdrh     sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
608a536df4eSdrh     if( pSort->bOrderedInnerLoop ){
609a536df4eSdrh       /* If the inner loop is driven by an index such that values from
610a536df4eSdrh       ** the same iteration of the inner loop are in sorted order, then
611a536df4eSdrh       ** immediately jump to the next iteration of an inner loop if the
612a536df4eSdrh       ** entry from the current iteration does not fit into the top
613a536df4eSdrh       ** LIMIT+OFFSET entries of the sorter. */
614a536df4eSdrh       int iBrk = sqlite3VdbeCurrentAddr(v) + 2;
615a536df4eSdrh       sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1);
6166326d9f6Sdrh       sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
617a536df4eSdrh       VdbeCoverage(v);
618a536df4eSdrh     }
61916897072Sdrh     sqlite3VdbeJumpHere(v, addr);
620d59ba6ceSdrh   }
621c926afbcSdrh }
622c926afbcSdrh 
623c926afbcSdrh /*
624ec7429aeSdrh ** Add code to implement the OFFSET
625ea48eb2eSdrh */
626ec7429aeSdrh static void codeOffset(
627bab39e13Sdrh   Vdbe *v,          /* Generate code into this VM */
628aa9ce707Sdrh   int iOffset,      /* Register holding the offset counter */
629b7654111Sdrh   int iContinue     /* Jump here to skip the current record */
630ea48eb2eSdrh ){
631a22a75e5Sdrh   if( iOffset>0 ){
6328b0cf38aSdrh     sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
6338b0cf38aSdrh     VdbeComment((v, "OFFSET"));
634ea48eb2eSdrh   }
635ea48eb2eSdrh }
636ea48eb2eSdrh 
637ea48eb2eSdrh /*
63898757157Sdrh ** Add code that will check to make sure the N registers starting at iMem
63998757157Sdrh ** form a distinct entry.  iTab is a sorting index that holds previously
640a2a49dc9Sdrh ** seen combinations of the N values.  A new entry is made in iTab
641a2a49dc9Sdrh ** if the current N values are new.
642a2a49dc9Sdrh **
643a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the
644a2a49dc9Sdrh ** stack if the top N elements are not distinct.
645a2a49dc9Sdrh */
646a2a49dc9Sdrh static void codeDistinct(
6472dcef11bSdrh   Parse *pParse,     /* Parsing and code generating context */
648a2a49dc9Sdrh   int iTab,          /* A sorting index used to test for distinctness */
649a2a49dc9Sdrh   int addrRepeat,    /* Jump to here if not distinct */
650477df4b3Sdrh   int N,             /* Number of elements */
651a2a49dc9Sdrh   int iMem           /* First element */
652a2a49dc9Sdrh ){
6532dcef11bSdrh   Vdbe *v;
6542dcef11bSdrh   int r1;
6552dcef11bSdrh 
6562dcef11bSdrh   v = pParse->pVdbe;
6572dcef11bSdrh   r1 = sqlite3GetTempReg(pParse);
658688852abSdrh   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
6591db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
6609b4eaebcSdrh   sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
661a67b5cb6Sdrh   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
6622dcef11bSdrh   sqlite3ReleaseTempReg(pParse, r1);
663a2a49dc9Sdrh }
664a2a49dc9Sdrh 
665c99130fdSdrh /*
6662282792aSdrh ** This routine generates the code for the inside of the inner loop
6672282792aSdrh ** of a SELECT.
66882c3d636Sdrh **
6692def2f7eSdrh ** If srcTab is negative, then the p->pEList expressions
670340309fdSdrh ** are evaluated in order to get the data for this row.  If srcTab is
6712def2f7eSdrh ** zero or more, then data is pulled from srcTab and p->pEList is used only
672257c13faSdan ** to get the number of columns and the collation sequence for each column.
6732282792aSdrh */
674d2b3e23bSdrh static void selectInnerLoop(
6752282792aSdrh   Parse *pParse,          /* The parser context */
676df199a25Sdrh   Select *p,              /* The complete select statement being coded */
6772def2f7eSdrh   int srcTab,             /* Pull data from this table if non-negative */
678079a3072Sdrh   SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
679e8e4af76Sdrh   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
6806c8c8ce0Sdanielk1977   SelectDest *pDest,      /* How to dispose of the results */
6812282792aSdrh   int iContinue,          /* Jump here to continue with next row */
682a9671a22Sdrh   int iBreak              /* Jump here to break out of the inner loop */
6832282792aSdrh ){
6842282792aSdrh   Vdbe *v = pParse->pVdbe;
685d847eaadSdrh   int i;
686ea48eb2eSdrh   int hasDistinct;            /* True if the DISTINCT keyword is present */
687d847eaadSdrh   int eDest = pDest->eDest;   /* How to dispose of results */
6882b596da8Sdrh   int iParm = pDest->iSDParm; /* First argument to disposal method */
689d847eaadSdrh   int nResultCol;             /* Number of result columns */
690fd0a2f97Sdrh   int nPrefixReg = 0;         /* Number of extra registers before regResult */
69138640e15Sdrh 
6929af90b72Sdan   /* Usually, regResult is the first cell in an array of memory cells
6939af90b72Sdan   ** containing the current result row. In this case regOrig is set to the
6949af90b72Sdan   ** same value. However, if the results are being sent to the sorter, the
6959af90b72Sdan   ** values for any expressions that are also part of the sort-key are omitted
6969af90b72Sdan   ** from this array. In this case regOrig is set to zero.  */
6979af90b72Sdan   int regResult;              /* Start of memory holding current results */
6989af90b72Sdan   int regOrig;                /* Start of memory holding full result (or 0) */
6999af90b72Sdan 
7001c767f0dSdrh   assert( v );
7012def2f7eSdrh   assert( p->pEList!=0 );
702e8e4af76Sdrh   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
703079a3072Sdrh   if( pSort && pSort->pOrderBy==0 ) pSort = 0;
704079a3072Sdrh   if( pSort==0 && !hasDistinct ){
705a22a75e5Sdrh     assert( iContinue!=0 );
706aa9ce707Sdrh     codeOffset(v, p->iOffset, iContinue);
707df199a25Sdrh   }
708df199a25Sdrh 
709967e8b73Sdrh   /* Pull the requested columns.
7102282792aSdrh   */
7112def2f7eSdrh   nResultCol = p->pEList->nExpr;
71205a86c5cSdrh 
7132b596da8Sdrh   if( pDest->iSdst==0 ){
714fd0a2f97Sdrh     if( pSort ){
71578d58432Sdan       nPrefixReg = pSort->pOrderBy->nExpr;
71678d58432Sdan       if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
717fd0a2f97Sdrh       pParse->nMem += nPrefixReg;
7181013c932Sdrh     }
719a2a49dc9Sdrh     pDest->iSdst = pParse->nMem+1;
720477df4b3Sdrh     pParse->nMem += nResultCol;
72105a86c5cSdrh   }else if( pDest->iSdst+nResultCol > pParse->nMem ){
72205a86c5cSdrh     /* This is an error condition that can result, for example, when a SELECT
72305a86c5cSdrh     ** on the right-hand side of an INSERT contains more result columns than
72405a86c5cSdrh     ** there are columns in the table on the left.  The error will be caught
72505a86c5cSdrh     ** and reported later.  But we need to make sure enough memory is allocated
72605a86c5cSdrh     ** to avoid other spurious errors in the meantime. */
72705a86c5cSdrh     pParse->nMem += nResultCol;
7284c583128Sdrh   }
72905a86c5cSdrh   pDest->nSdst = nResultCol;
7309af90b72Sdan   regOrig = regResult = pDest->iSdst;
731340309fdSdrh   if( srcTab>=0 ){
732340309fdSdrh     for(i=0; i<nResultCol; i++){
733d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
7342def2f7eSdrh       VdbeComment((v, "%s", p->pEList->a[i].zName));
73582c3d636Sdrh     }
7369ed1dfa8Sdanielk1977   }else if( eDest!=SRT_Exists ){
7379ed1dfa8Sdanielk1977     /* If the destination is an EXISTS(...) expression, the actual
7389ed1dfa8Sdanielk1977     ** values returned by the SELECT are not required.
7399ed1dfa8Sdanielk1977     */
740df553659Sdrh     u8 ecelFlags;
741df553659Sdrh     if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
742df553659Sdrh       ecelFlags = SQLITE_ECEL_DUP;
743df553659Sdrh     }else{
744df553659Sdrh       ecelFlags = 0;
745a2a49dc9Sdrh     }
746ac56ab7eSdan     if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
7472def2f7eSdrh       /* For each expression in p->pEList that is a copy of an expression in
748257c13faSdan       ** the ORDER BY clause (pSort->pOrderBy), set the associated
749257c13faSdan       ** iOrderByCol value to one more than the index of the ORDER BY
750257c13faSdan       ** expression within the sort-key that pushOntoSorter() will generate.
7512def2f7eSdrh       ** This allows the p->pEList field to be omitted from the sorted record,
752257c13faSdan       ** saving space and CPU cycles.  */
753257c13faSdan       ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
754257c13faSdan       for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
755257c13faSdan         int j;
756257c13faSdan         if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
7572def2f7eSdrh           p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
758257c13faSdan         }
759257c13faSdan       }
7609af90b72Sdan       regOrig = 0;
761257c13faSdan       assert( eDest==SRT_Set || eDest==SRT_Mem
762257c13faSdan            || eDest==SRT_Coroutine || eDest==SRT_Output );
763257c13faSdan     }
7643d240d21Sdrh     nResultCol = sqlite3ExprCodeExprList(pParse,p->pEList,regResult,
7653d240d21Sdrh                                          0,ecelFlags);
766a2a49dc9Sdrh   }
7672282792aSdrh 
768daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
769daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
770daffd0e5Sdrh   ** part of the result.
7712282792aSdrh   */
772ea48eb2eSdrh   if( hasDistinct ){
773e8e4af76Sdrh     switch( pDistinct->eTnctType ){
774e8e4af76Sdrh       case WHERE_DISTINCT_ORDERED: {
775e8e4af76Sdrh         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
776e8e4af76Sdrh         int iJump;              /* Jump destination */
777e8e4af76Sdrh         int regPrev;            /* Previous row content */
778e8e4af76Sdrh 
779e8e4af76Sdrh         /* Allocate space for the previous row */
780e8e4af76Sdrh         regPrev = pParse->nMem+1;
781340309fdSdrh         pParse->nMem += nResultCol;
782e8e4af76Sdrh 
783e8e4af76Sdrh         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
784e8e4af76Sdrh         ** sets the MEM_Cleared bit on the first register of the
785e8e4af76Sdrh         ** previous value.  This will cause the OP_Ne below to always
786e8e4af76Sdrh         ** fail on the first iteration of the loop even if the first
787e8e4af76Sdrh         ** row is all NULLs.
788e8e4af76Sdrh         */
789e8e4af76Sdrh         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
790e8e4af76Sdrh         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
791e8e4af76Sdrh         pOp->opcode = OP_Null;
792e8e4af76Sdrh         pOp->p1 = 1;
793e8e4af76Sdrh         pOp->p2 = regPrev;
794e8e4af76Sdrh 
795340309fdSdrh         iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
796340309fdSdrh         for(i=0; i<nResultCol; i++){
7972def2f7eSdrh           CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
798340309fdSdrh           if( i<nResultCol-1 ){
799e8e4af76Sdrh             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
800688852abSdrh             VdbeCoverage(v);
801e8e4af76Sdrh           }else{
802e8e4af76Sdrh             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
803688852abSdrh             VdbeCoverage(v);
804e8e4af76Sdrh            }
805e8e4af76Sdrh           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
806e8e4af76Sdrh           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
807e8e4af76Sdrh         }
808fcf2a775Sdrh         assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
809340309fdSdrh         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
810e8e4af76Sdrh         break;
811e8e4af76Sdrh       }
812e8e4af76Sdrh 
813e8e4af76Sdrh       case WHERE_DISTINCT_UNIQUE: {
814e8e4af76Sdrh         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
815e8e4af76Sdrh         break;
816e8e4af76Sdrh       }
817e8e4af76Sdrh 
818e8e4af76Sdrh       default: {
819e8e4af76Sdrh         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
82038b4149cSdrh         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
82138b4149cSdrh                      regResult);
822e8e4af76Sdrh         break;
823e8e4af76Sdrh       }
824e8e4af76Sdrh     }
825079a3072Sdrh     if( pSort==0 ){
826aa9ce707Sdrh       codeOffset(v, p->iOffset, iContinue);
827ea48eb2eSdrh     }
8282282792aSdrh   }
82982c3d636Sdrh 
830c926afbcSdrh   switch( eDest ){
83182c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
83282c3d636Sdrh     ** table iParm.
8332282792aSdrh     */
83413449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
835c926afbcSdrh     case SRT_Union: {
8369cbf3425Sdrh       int r1;
8379cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
838340309fdSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
8399b4eaebcSdrh       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
8409cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
841c926afbcSdrh       break;
842c926afbcSdrh     }
84382c3d636Sdrh 
84482c3d636Sdrh     /* Construct a record from the query result, but instead of
84582c3d636Sdrh     ** saving that record, use it as a key to delete elements from
84682c3d636Sdrh     ** the temporary table iParm.
84782c3d636Sdrh     */
848c926afbcSdrh     case SRT_Except: {
849340309fdSdrh       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
850c926afbcSdrh       break;
851c926afbcSdrh     }
852781def29Sdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
8535338a5f7Sdanielk1977 
8545338a5f7Sdanielk1977     /* Store the result as data using a unique key.
8555338a5f7Sdanielk1977     */
8568e1ee88cSdrh     case SRT_Fifo:
8578e1ee88cSdrh     case SRT_DistFifo:
8585338a5f7Sdanielk1977     case SRT_Table:
859b9bb7c18Sdrh     case SRT_EphemTab: {
860fd0a2f97Sdrh       int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
861373cc2ddSdrh       testcase( eDest==SRT_Table );
862373cc2ddSdrh       testcase( eDest==SRT_EphemTab );
863e2248cfdSdrh       testcase( eDest==SRT_Fifo );
864e2248cfdSdrh       testcase( eDest==SRT_DistFifo );
865fd0a2f97Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
8668ce7184bSdan #ifndef SQLITE_OMIT_CTE
8678e1ee88cSdrh       if( eDest==SRT_DistFifo ){
8688e1ee88cSdrh         /* If the destination is DistFifo, then cursor (iParm+1) is open
8698ce7184bSdan         ** on an ephemeral index. If the current row is already present
8708ce7184bSdan         ** in the index, do not write it to the output. If not, add the
8718ce7184bSdan         ** current row to the index and proceed with writing it to the
8728ce7184bSdan         ** output table as well.  */
8738ce7184bSdan         int addr = sqlite3VdbeCurrentAddr(v) + 4;
87438b4149cSdrh         sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
87538b4149cSdrh         VdbeCoverage(v);
8769b4eaebcSdrh         sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
877079a3072Sdrh         assert( pSort==0 );
8788ce7184bSdan       }
8798ce7184bSdan #endif
880079a3072Sdrh       if( pSort ){
8815579d59fSdrh         pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
8825338a5f7Sdanielk1977       }else{
883b7654111Sdrh         int r2 = sqlite3GetTempReg(pParse);
884b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
885b7654111Sdrh         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
886b7654111Sdrh         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
887b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r2);
8885338a5f7Sdanielk1977       }
889fd0a2f97Sdrh       sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
8905338a5f7Sdanielk1977       break;
8915338a5f7Sdanielk1977     }
8922282792aSdrh 
89393758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
8942282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
8952282792aSdrh     ** then there should be a single item on the stack.  Write this
8962282792aSdrh     ** item into the set table with bogus data.
8972282792aSdrh     */
898c926afbcSdrh     case SRT_Set: {
899079a3072Sdrh       if( pSort ){
900de941c60Sdrh         /* At first glance you would think we could optimize out the
901de941c60Sdrh         ** ORDER BY in this case since the order of entries in the set
902de941c60Sdrh         ** does not matter.  But there might be a LIMIT clause, in which
903de941c60Sdrh         ** case the order does matter */
90451d82d1dSdan         pushOntoSorter(
9059af90b72Sdan             pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
906c926afbcSdrh       }else{
907b7654111Sdrh         int r1 = sqlite3GetTempReg(pParse);
90871c57db0Sdan         assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
90971c57db0Sdan         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
910553168c7Sdan             r1, pDest->zAffSdst, nResultCol);
91171c57db0Sdan         sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
9129b4eaebcSdrh         sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
913b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r1);
914c926afbcSdrh       }
915c926afbcSdrh       break;
916c926afbcSdrh     }
91782c3d636Sdrh 
918504b6989Sdrh     /* If any row exist in the result set, record that fact and abort.
919ec7429aeSdrh     */
920ec7429aeSdrh     case SRT_Exists: {
9214c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
922ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
923ec7429aeSdrh       break;
924ec7429aeSdrh     }
925ec7429aeSdrh 
9262282792aSdrh     /* If this is a scalar select that is part of an expression, then
927870a0705Sdan     ** store the results in the appropriate memory cell or array of
928870a0705Sdan     ** memory cells and break out of the scan loop.
9292282792aSdrh     */
930c926afbcSdrh     case SRT_Mem: {
931079a3072Sdrh       if( pSort ){
932257c13faSdan         assert( nResultCol<=pDest->nSdst );
933870a0705Sdan         pushOntoSorter(
9349af90b72Sdan             pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
935c926afbcSdrh       }else{
936257c13faSdan         assert( nResultCol==pDest->nSdst );
93753932ce8Sdrh         assert( regResult==iParm );
938ec7429aeSdrh         /* The LIMIT clause will jump out of the loop for us */
939c926afbcSdrh       }
940c926afbcSdrh       break;
941c926afbcSdrh     }
94293758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
9432282792aSdrh 
94481cf13ecSdrh     case SRT_Coroutine:       /* Send data to a co-routine */
94581cf13ecSdrh     case SRT_Output: {        /* Return the results */
946373cc2ddSdrh       testcase( eDest==SRT_Coroutine );
947373cc2ddSdrh       testcase( eDest==SRT_Output );
948079a3072Sdrh       if( pSort ){
9499af90b72Sdan         pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
9505579d59fSdrh                        nPrefixReg);
951e00ee6ebSdrh       }else if( eDest==SRT_Coroutine ){
9522b596da8Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
953c182d163Sdrh       }else{
954340309fdSdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
955340309fdSdrh         sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
956ac82fcf5Sdrh       }
957142e30dfSdrh       break;
958142e30dfSdrh     }
959142e30dfSdrh 
960fe1c6bb9Sdrh #ifndef SQLITE_OMIT_CTE
961fe1c6bb9Sdrh     /* Write the results into a priority queue that is order according to
962fe1c6bb9Sdrh     ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
963fe1c6bb9Sdrh     ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
964fe1c6bb9Sdrh     ** pSO->nExpr columns, then make sure all keys are unique by adding a
965fe1c6bb9Sdrh     ** final OP_Sequence column.  The last column is the record as a blob.
966fe1c6bb9Sdrh     */
967fe1c6bb9Sdrh     case SRT_DistQueue:
968fe1c6bb9Sdrh     case SRT_Queue: {
969fe1c6bb9Sdrh       int nKey;
970fe1c6bb9Sdrh       int r1, r2, r3;
971fe1c6bb9Sdrh       int addrTest = 0;
972fe1c6bb9Sdrh       ExprList *pSO;
973fe1c6bb9Sdrh       pSO = pDest->pOrderBy;
974fe1c6bb9Sdrh       assert( pSO );
975fe1c6bb9Sdrh       nKey = pSO->nExpr;
976fe1c6bb9Sdrh       r1 = sqlite3GetTempReg(pParse);
977fe1c6bb9Sdrh       r2 = sqlite3GetTempRange(pParse, nKey+2);
978fe1c6bb9Sdrh       r3 = r2+nKey+1;
979fe1c6bb9Sdrh       if( eDest==SRT_DistQueue ){
980fe1c6bb9Sdrh         /* If the destination is DistQueue, then cursor (iParm+1) is open
981fe1c6bb9Sdrh         ** on a second ephemeral index that holds all values every previously
9827e4efaecSdrh         ** added to the queue. */
9837e4efaecSdrh         addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
9847e4efaecSdrh                                         regResult, nResultCol);
985688852abSdrh         VdbeCoverage(v);
9867e4efaecSdrh       }
9877e4efaecSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
9887e4efaecSdrh       if( eDest==SRT_DistQueue ){
989fe1c6bb9Sdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
990cfe24586Sdan         sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
991fe1c6bb9Sdrh       }
992fe1c6bb9Sdrh       for(i=0; i<nKey; i++){
993fe1c6bb9Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy,
994fe1c6bb9Sdrh                           regResult + pSO->a[i].u.x.iOrderByCol - 1,
995fe1c6bb9Sdrh                           r2+i);
996fe1c6bb9Sdrh       }
997fe1c6bb9Sdrh       sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
998fe1c6bb9Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
9999b4eaebcSdrh       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
1000fe1c6bb9Sdrh       if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
1001fe1c6bb9Sdrh       sqlite3ReleaseTempReg(pParse, r1);
1002fe1c6bb9Sdrh       sqlite3ReleaseTempRange(pParse, r2, nKey+2);
1003fe1c6bb9Sdrh       break;
1004fe1c6bb9Sdrh     }
1005fe1c6bb9Sdrh #endif /* SQLITE_OMIT_CTE */
1006fe1c6bb9Sdrh 
1007fe1c6bb9Sdrh 
1008fe1c6bb9Sdrh 
10096a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER)
1010d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
1011d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
1012d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
1013d7489c39Sdrh     ** about the actual results of the select.
1014d7489c39Sdrh     */
1015c926afbcSdrh     default: {
1016f46f905aSdrh       assert( eDest==SRT_Discard );
1017c926afbcSdrh       break;
1018c926afbcSdrh     }
101993758c8dSdanielk1977 #endif
1020c926afbcSdrh   }
1021ec7429aeSdrh 
10225e87be87Sdrh   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
10235e87be87Sdrh   ** there is a sorter, in which case the sorter has already limited
10245e87be87Sdrh   ** the output for us.
1025ec7429aeSdrh   */
1026079a3072Sdrh   if( pSort==0 && p->iLimit ){
102716897072Sdrh     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
1028ec7429aeSdrh   }
102982c3d636Sdrh }
103082c3d636Sdrh 
103182c3d636Sdrh /*
1032ad124329Sdrh ** Allocate a KeyInfo object sufficient for an index of N key columns and
1033ad124329Sdrh ** X extra columns.
1034323df790Sdrh */
1035ad124329Sdrh KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
1036d4ab003dSdrh   int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
1037d8e4b132Sdrh   KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
1038323df790Sdrh   if( p ){
1039ad124329Sdrh     p->aSortOrder = (u8*)&p->aColl[N+X];
1040a485ad19Sdrh     p->nKeyField = (u16)N;
1041a485ad19Sdrh     p->nAllField = (u16)(N+X);
1042323df790Sdrh     p->enc = ENC(db);
1043323df790Sdrh     p->db = db;
10442ec2fb22Sdrh     p->nRef = 1;
1045c263f7c4Sdrh     memset(&p[1], 0, nExtra);
10462ec2fb22Sdrh   }else{
10474a642b60Sdrh     sqlite3OomFault(db);
1048323df790Sdrh   }
1049323df790Sdrh   return p;
1050323df790Sdrh }
1051323df790Sdrh 
1052323df790Sdrh /*
10532ec2fb22Sdrh ** Deallocate a KeyInfo object
10542ec2fb22Sdrh */
10552ec2fb22Sdrh void sqlite3KeyInfoUnref(KeyInfo *p){
10562ec2fb22Sdrh   if( p ){
10572ec2fb22Sdrh     assert( p->nRef>0 );
10582ec2fb22Sdrh     p->nRef--;
1059dbd6a7dcSdrh     if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
10602ec2fb22Sdrh   }
10612ec2fb22Sdrh }
10622ec2fb22Sdrh 
10632ec2fb22Sdrh /*
10642ec2fb22Sdrh ** Make a new pointer to a KeyInfo object
10652ec2fb22Sdrh */
10662ec2fb22Sdrh KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
10672ec2fb22Sdrh   if( p ){
10682ec2fb22Sdrh     assert( p->nRef>0 );
10692ec2fb22Sdrh     p->nRef++;
10702ec2fb22Sdrh   }
10712ec2fb22Sdrh   return p;
10722ec2fb22Sdrh }
10732ec2fb22Sdrh 
10742ec2fb22Sdrh #ifdef SQLITE_DEBUG
10752ec2fb22Sdrh /*
10762ec2fb22Sdrh ** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
10772ec2fb22Sdrh ** can only be changed if this is just a single reference to the object.
10782ec2fb22Sdrh **
10792ec2fb22Sdrh ** This routine is used only inside of assert() statements.
10802ec2fb22Sdrh */
10812ec2fb22Sdrh int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
10822ec2fb22Sdrh #endif /* SQLITE_DEBUG */
10832ec2fb22Sdrh 
10842ec2fb22Sdrh /*
1085dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records
1086dece1a84Sdrh ** the collating sequence for each expression in that expression list.
1087dece1a84Sdrh **
10880342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
10890342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to
10900342b1f5Sdrh ** implement that clause.  If the ExprList is the result set of a SELECT
10910342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual
10920342b1f5Sdrh ** index to implement a DISTINCT test.
10930342b1f5Sdrh **
109460ec914cSpeter.d.reid ** Space to hold the KeyInfo structure is obtained from malloc.  The calling
1095dece1a84Sdrh ** function is responsible for seeing that this structure is eventually
10962ec2fb22Sdrh ** freed.
1097dece1a84Sdrh */
1098079a3072Sdrh static KeyInfo *keyInfoFromExprList(
1099079a3072Sdrh   Parse *pParse,       /* Parsing context */
1100079a3072Sdrh   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
1101079a3072Sdrh   int iStart,          /* Begin with this column of pList */
1102079a3072Sdrh   int nExtra           /* Add this many extra columns to the end */
1103079a3072Sdrh ){
1104dece1a84Sdrh   int nExpr;
1105dece1a84Sdrh   KeyInfo *pInfo;
1106dece1a84Sdrh   struct ExprList_item *pItem;
1107323df790Sdrh   sqlite3 *db = pParse->db;
1108dece1a84Sdrh   int i;
1109dece1a84Sdrh 
1110dece1a84Sdrh   nExpr = pList->nExpr;
11113f39bcf5Sdrh   pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
1112dece1a84Sdrh   if( pInfo ){
11132ec2fb22Sdrh     assert( sqlite3KeyInfoIsWriteable(pInfo) );
11146284db90Sdrh     for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
111570efa84dSdrh       pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
11166284db90Sdrh       pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
1117dece1a84Sdrh     }
1118dece1a84Sdrh   }
1119dece1a84Sdrh   return pInfo;
1120dece1a84Sdrh }
1121dece1a84Sdrh 
11227f61e92cSdan /*
11237f61e92cSdan ** Name of the connection operator, used for error messages.
11247f61e92cSdan */
11257f61e92cSdan static const char *selectOpName(int id){
11267f61e92cSdan   char *z;
11277f61e92cSdan   switch( id ){
11287f61e92cSdan     case TK_ALL:       z = "UNION ALL";   break;
11297f61e92cSdan     case TK_INTERSECT: z = "INTERSECT";   break;
11307f61e92cSdan     case TK_EXCEPT:    z = "EXCEPT";      break;
11317f61e92cSdan     default:           z = "UNION";       break;
11327f61e92cSdan   }
11337f61e92cSdan   return z;
11347f61e92cSdan }
11357f61e92cSdan 
11362ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN
113717c0bc0cSdan /*
113817c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
113917c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
114017c0bc0cSdan ** where the caption is of the form:
114117c0bc0cSdan **
114217c0bc0cSdan **   "USE TEMP B-TREE FOR xxx"
114317c0bc0cSdan **
114417c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
114517c0bc0cSdan ** is determined by the zUsage argument.
114617c0bc0cSdan */
11472ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){
11482ce22453Sdan   if( pParse->explain==2 ){
11492ce22453Sdan     Vdbe *v = pParse->pVdbe;
11502ce22453Sdan     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
11512ce22453Sdan     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
11522ce22453Sdan   }
11532ce22453Sdan }
115417c0bc0cSdan 
115517c0bc0cSdan /*
1156bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro
1157bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
1158bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that
1159bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
1160bb2b4418Sdan ** code with #ifndef directives.
1161bb2b4418Sdan */
1162bb2b4418Sdan # define explainSetInteger(a, b) a = b
1163bb2b4418Sdan 
1164bb2b4418Sdan #else
1165bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */
1166bb2b4418Sdan # define explainTempTable(y,z)
1167bb2b4418Sdan # define explainSetInteger(y,z)
1168bb2b4418Sdan #endif
1169bb2b4418Sdan 
1170bb2b4418Sdan #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
1171bb2b4418Sdan /*
11727f61e92cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
11737f61e92cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
11747f61e92cSdan ** where the caption is of one of the two forms:
11757f61e92cSdan **
11767f61e92cSdan **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
11777f61e92cSdan **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
11787f61e92cSdan **
11797f61e92cSdan ** where iSub1 and iSub2 are the integers passed as the corresponding
11807f61e92cSdan ** function parameters, and op is the text representation of the parameter
11817f61e92cSdan ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
11827f61e92cSdan ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
11837f61e92cSdan ** false, or the second form if it is true.
11847f61e92cSdan */
11857f61e92cSdan static void explainComposite(
11867f61e92cSdan   Parse *pParse,                  /* Parse context */
11877f61e92cSdan   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
11887f61e92cSdan   int iSub1,                      /* Subquery id 1 */
11897f61e92cSdan   int iSub2,                      /* Subquery id 2 */
11907f61e92cSdan   int bUseTmp                     /* True if a temp table was used */
11917f61e92cSdan ){
11927f61e92cSdan   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
11937f61e92cSdan   if( pParse->explain==2 ){
11947f61e92cSdan     Vdbe *v = pParse->pVdbe;
11957f61e92cSdan     char *zMsg = sqlite3MPrintf(
119630969d3fSdan         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
11977f61e92cSdan         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
11987f61e92cSdan     );
11997f61e92cSdan     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
12007f61e92cSdan   }
12017f61e92cSdan }
12022ce22453Sdan #else
120317c0bc0cSdan /* No-op versions of the explainXXX() functions and macros. */
12047f61e92cSdan # define explainComposite(v,w,x,y,z)
12052ce22453Sdan #endif
1206dece1a84Sdrh 
1207dece1a84Sdrh /*
1208d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
1209d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
1210d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
1211d8bc7086Sdrh ** routine generates the code needed to do that.
1212d8bc7086Sdrh */
1213c926afbcSdrh static void generateSortTail(
1214cdd536f0Sdrh   Parse *pParse,    /* Parsing context */
1215c926afbcSdrh   Select *p,        /* The SELECT statement */
1216079a3072Sdrh   SortCtx *pSort,   /* Information on the ORDER BY clause */
1217c926afbcSdrh   int nColumn,      /* Number of columns of data */
12186c8c8ce0Sdanielk1977   SelectDest *pDest /* Write the sorted results here */
1219c926afbcSdrh ){
1220ddba0c22Sdrh   Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
1221a04a8be2Sdrh   int addrBreak = pSort->labelDone;            /* Jump here to exit loop */
1222dc5ea5c7Sdrh   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
1223d8bc7086Sdrh   int addr;
1224079a3072Sdrh   int addrOnce = 0;
12250342b1f5Sdrh   int iTab;
1226079a3072Sdrh   ExprList *pOrderBy = pSort->pOrderBy;
12276c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
12282b596da8Sdrh   int iParm = pDest->iSDParm;
12292d401ab8Sdrh   int regRow;
12302d401ab8Sdrh   int regRowid;
1231257c13faSdan   int iCol;
1232079a3072Sdrh   int nKey;
1233f45f2326Sdrh   int iSortTab;                   /* Sorter cursor to read from */
1234f45f2326Sdrh   int nSortData;                  /* Trailing values to read from sorter */
1235f45f2326Sdrh   int i;
123678d58432Sdan   int bSeq;                       /* True if sorter record includes seq. no. */
123770f624c3Sdrh   struct ExprList_item *aOutEx = p->pEList->a;
12382d401ab8Sdrh 
1239a04a8be2Sdrh   assert( addrBreak<0 );
1240079a3072Sdrh   if( pSort->labelBkOut ){
1241079a3072Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
1242076e85f5Sdrh     sqlite3VdbeGoto(v, addrBreak);
1243079a3072Sdrh     sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
1244079a3072Sdrh   }
1245079a3072Sdrh   iTab = pSort->iECursor;
124671c57db0Sdan   if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
12473e9ca094Sdrh     regRowid = 0;
1248f45f2326Sdrh     regRow = pDest->iSdst;
1249f45f2326Sdrh     nSortData = nColumn;
1250ed24da4bSdrh   }else{
125151d82d1dSdan     regRowid = sqlite3GetTempReg(pParse);
125251d82d1dSdan     regRow = sqlite3GetTempRange(pParse, nColumn);
125351d82d1dSdan     nSortData = nColumn;
1254cdd536f0Sdrh   }
1255079a3072Sdrh   nKey = pOrderBy->nExpr - pSort->nOBSat;
1256079a3072Sdrh   if( pSort->sortFlags & SORTFLAG_UseSorter ){
1257c2bb3282Sdrh     int regSortOut = ++pParse->nMem;
1258f45f2326Sdrh     iSortTab = pParse->nTab++;
125983553eefSdrh     if( pSort->labelBkOut ){
1260511f9e8dSdrh       addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
126183553eefSdrh     }
1262f45f2326Sdrh     sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
1263079a3072Sdrh     if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
1264c6aff30cSdrh     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
1265688852abSdrh     VdbeCoverage(v);
1266aa9ce707Sdrh     codeOffset(v, p->iOffset, addrContinue);
12676cf4a7dfSdrh     sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
126878d58432Sdan     bSeq = 0;
1269c6aff30cSdrh   }else{
1270688852abSdrh     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
1271aa9ce707Sdrh     codeOffset(v, p->iOffset, addrContinue);
1272f45f2326Sdrh     iSortTab = iTab;
127378d58432Sdan     bSeq = 1;
1274f45f2326Sdrh   }
1275257c13faSdan   for(i=0, iCol=nKey+bSeq; i<nSortData; i++){
1276257c13faSdan     int iRead;
1277257c13faSdan     if( aOutEx[i].u.x.iOrderByCol ){
1278257c13faSdan       iRead = aOutEx[i].u.x.iOrderByCol-1;
1279257c13faSdan     }else{
1280257c13faSdan       iRead = iCol++;
1281257c13faSdan     }
1282257c13faSdan     sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
128370f624c3Sdrh     VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
1284c6aff30cSdrh   }
1285c926afbcSdrh   switch( eDest ){
1286ac56ab7eSdan     case SRT_Table:
1287b9bb7c18Sdrh     case SRT_EphemTab: {
12882d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
12892d401ab8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
12902d401ab8Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1291c926afbcSdrh       break;
1292c926afbcSdrh     }
129393758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
1294c926afbcSdrh     case SRT_Set: {
129571c57db0Sdan       assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
129671c57db0Sdan       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
1297553168c7Sdan                         pDest->zAffSdst, nColumn);
129871c57db0Sdan       sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn);
12999b4eaebcSdrh       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
1300c926afbcSdrh       break;
1301c926afbcSdrh     }
1302c926afbcSdrh     case SRT_Mem: {
1303ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
1304c926afbcSdrh       break;
1305c926afbcSdrh     }
130693758c8dSdanielk1977 #endif
1307373cc2ddSdrh     default: {
1308373cc2ddSdrh       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
13091c767f0dSdrh       testcase( eDest==SRT_Output );
13101c767f0dSdrh       testcase( eDest==SRT_Coroutine );
13117d10d5a6Sdrh       if( eDest==SRT_Output ){
13122b596da8Sdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
13132b596da8Sdrh         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
1314a9671a22Sdrh       }else{
13152b596da8Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1316ce665cf6Sdrh       }
1317ac82fcf5Sdrh       break;
1318ac82fcf5Sdrh     }
1319c926afbcSdrh   }
1320f45f2326Sdrh   if( regRowid ){
132151d82d1dSdan     if( eDest==SRT_Set ){
132251d82d1dSdan       sqlite3ReleaseTempRange(pParse, regRow, nColumn);
132351d82d1dSdan     }else{
13242d401ab8Sdrh       sqlite3ReleaseTempReg(pParse, regRow);
132551d82d1dSdan     }
13262d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regRowid);
1327f45f2326Sdrh   }
1328ec7429aeSdrh   /* The bottom of the loop
1329ec7429aeSdrh   */
1330dc5ea5c7Sdrh   sqlite3VdbeResolveLabel(v, addrContinue);
1331079a3072Sdrh   if( pSort->sortFlags & SORTFLAG_UseSorter ){
1332688852abSdrh     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
1333c6aff30cSdrh   }else{
1334688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
1335c6aff30cSdrh   }
1336079a3072Sdrh   if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
1337dc5ea5c7Sdrh   sqlite3VdbeResolveLabel(v, addrBreak);
1338d8bc7086Sdrh }
1339d8bc7086Sdrh 
1340d8bc7086Sdrh /*
1341517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
1342517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
1343e78e8284Sdrh **
13445f3e5e74Sdrh ** Also try to estimate the size of the returned value and return that
13455f3e5e74Sdrh ** result in *pEstWidth.
13465f3e5e74Sdrh **
1347955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the
1348955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The
1349955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
1350955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The
1351955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is
1352955de52cSdanielk1977 ** considered a column by this function.
1353e78e8284Sdrh **
1354955de52cSdanielk1977 **   SELECT col FROM tbl;
1355955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl;
1356955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl);
1357955de52cSdanielk1977 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
1358955de52cSdanielk1977 **
1359955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL.
13605f3e5e74Sdrh **
13615f3e5e74Sdrh ** This routine has either 3 or 6 parameters depending on whether or not
13625f3e5e74Sdrh ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
1363fcb78a49Sdrh */
13645f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
13655f3e5e74Sdrh # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
1366b121dd14Sdrh #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
1367b121dd14Sdrh # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
1368b121dd14Sdrh #endif
13695f3e5e74Sdrh static const char *columnTypeImpl(
1370955de52cSdanielk1977   NameContext *pNC,
1371955de52cSdanielk1977   Expr *pExpr,
1372b121dd14Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
13735f3e5e74Sdrh   const char **pzOrigDb,
13745f3e5e74Sdrh   const char **pzOrigTab,
13755f3e5e74Sdrh   const char **pzOrigCol,
1376b121dd14Sdrh #endif
13775f3e5e74Sdrh   u8 *pEstWidth
1378955de52cSdanielk1977 ){
1379955de52cSdanielk1977   char const *zType = 0;
1380517eb646Sdanielk1977   int j;
13815f3e5e74Sdrh   u8 estWidth = 1;
1382b121dd14Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1383b121dd14Sdrh   char const *zOrigDb = 0;
1384b121dd14Sdrh   char const *zOrigTab = 0;
1385b121dd14Sdrh   char const *zOrigCol = 0;
1386b121dd14Sdrh #endif
13875338a5f7Sdanielk1977 
1388f7ce4291Sdrh   assert( pExpr!=0 );
1389f7ce4291Sdrh   assert( pNC->pSrcList!=0 );
139000e279d9Sdanielk1977   switch( pExpr->op ){
139130bcf5dbSdrh     case TK_AGG_COLUMN:
139200e279d9Sdanielk1977     case TK_COLUMN: {
1393955de52cSdanielk1977       /* The expression is a column. Locate the table the column is being
1394955de52cSdanielk1977       ** extracted from in NameContext.pSrcList. This table may be real
1395955de52cSdanielk1977       ** database table or a subquery.
1396955de52cSdanielk1977       */
1397955de52cSdanielk1977       Table *pTab = 0;            /* Table structure column is extracted from */
1398955de52cSdanielk1977       Select *pS = 0;             /* Select the column is extracted from */
1399955de52cSdanielk1977       int iCol = pExpr->iColumn;  /* Index of column in pTab */
1400373cc2ddSdrh       testcase( pExpr->op==TK_AGG_COLUMN );
1401373cc2ddSdrh       testcase( pExpr->op==TK_COLUMN );
140243bc88bbSdan       while( pNC && !pTab ){
1403b3bce662Sdanielk1977         SrcList *pTabList = pNC->pSrcList;
1404b3bce662Sdanielk1977         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
1405b3bce662Sdanielk1977         if( j<pTabList->nSrc ){
14066a3ea0e6Sdrh           pTab = pTabList->a[j].pTab;
1407955de52cSdanielk1977           pS = pTabList->a[j].pSelect;
1408b3bce662Sdanielk1977         }else{
1409b3bce662Sdanielk1977           pNC = pNC->pNext;
1410b3bce662Sdanielk1977         }
1411b3bce662Sdanielk1977       }
1412955de52cSdanielk1977 
141343bc88bbSdan       if( pTab==0 ){
1414417168adSdrh         /* At one time, code such as "SELECT new.x" within a trigger would
1415417168adSdrh         ** cause this condition to run.  Since then, we have restructured how
1416417168adSdrh         ** trigger code is generated and so this condition is no longer
141743bc88bbSdan         ** possible. However, it can still be true for statements like
141843bc88bbSdan         ** the following:
141943bc88bbSdan         **
142043bc88bbSdan         **   CREATE TABLE t1(col INTEGER);
142143bc88bbSdan         **   SELECT (SELECT t1.col) FROM FROM t1;
142243bc88bbSdan         **
142343bc88bbSdan         ** when columnType() is called on the expression "t1.col" in the
142443bc88bbSdan         ** sub-select. In this case, set the column type to NULL, even
142543bc88bbSdan         ** though it should really be "INTEGER".
142643bc88bbSdan         **
142743bc88bbSdan         ** This is not a problem, as the column type of "t1.col" is never
142843bc88bbSdan         ** used. When columnType() is called on the expression
142943bc88bbSdan         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
143043bc88bbSdan         ** branch below.  */
14317e62779aSdrh         break;
14327e62779aSdrh       }
1433955de52cSdanielk1977 
143443bc88bbSdan       assert( pTab && pExpr->pTab==pTab );
1435955de52cSdanielk1977       if( pS ){
1436955de52cSdanielk1977         /* The "table" is actually a sub-select or a view in the FROM clause
1437955de52cSdanielk1977         ** of the SELECT statement. Return the declaration type and origin
1438955de52cSdanielk1977         ** data for the result-set column of the sub-select.
1439955de52cSdanielk1977         */
1440f35f2f92Sdrh         if( iCol>=0 && iCol<pS->pEList->nExpr ){
1441955de52cSdanielk1977           /* If iCol is less than zero, then the expression requests the
1442955de52cSdanielk1977           ** rowid of the sub-select or view. This expression is legal (see
1443955de52cSdanielk1977           ** test case misc2.2.2) - it always evaluates to NULL.
1444955de52cSdanielk1977           */
1445955de52cSdanielk1977           NameContext sNC;
1446955de52cSdanielk1977           Expr *p = pS->pEList->a[iCol].pExpr;
1447955de52cSdanielk1977           sNC.pSrcList = pS->pSrc;
144843bc88bbSdan           sNC.pNext = pNC;
1449955de52cSdanielk1977           sNC.pParse = pNC->pParse;
14505f3e5e74Sdrh           zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
1451955de52cSdanielk1977         }
145293c36bb3Sdrh       }else if( pTab->pSchema ){
1453955de52cSdanielk1977         /* A real table */
1454955de52cSdanielk1977         assert( !pS );
1455fcb78a49Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
1456fcb78a49Sdrh         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
14575f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1458fcb78a49Sdrh         if( iCol<0 ){
1459fcb78a49Sdrh           zType = "INTEGER";
14605f3e5e74Sdrh           zOrigCol = "rowid";
1461fcb78a49Sdrh         }else{
14625f3e5e74Sdrh           zOrigCol = pTab->aCol[iCol].zName;
1463d7564865Sdrh           zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
14645f3e5e74Sdrh           estWidth = pTab->aCol[iCol].szEst;
1465955de52cSdanielk1977         }
14665f3e5e74Sdrh         zOrigTab = pTab->zName;
1467955de52cSdanielk1977         if( pNC->pParse ){
1468955de52cSdanielk1977           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
1469e59be010Sdrh           zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
1470955de52cSdanielk1977         }
14715f3e5e74Sdrh #else
14725f3e5e74Sdrh         if( iCol<0 ){
14735f3e5e74Sdrh           zType = "INTEGER";
14745f3e5e74Sdrh         }else{
1475d7564865Sdrh           zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
14765f3e5e74Sdrh           estWidth = pTab->aCol[iCol].szEst;
14775f3e5e74Sdrh         }
14785f3e5e74Sdrh #endif
1479fcb78a49Sdrh       }
148000e279d9Sdanielk1977       break;
1481736c22b8Sdrh     }
148293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
148300e279d9Sdanielk1977     case TK_SELECT: {
1484955de52cSdanielk1977       /* The expression is a sub-select. Return the declaration type and
1485955de52cSdanielk1977       ** origin info for the single column in the result set of the SELECT
1486955de52cSdanielk1977       ** statement.
1487955de52cSdanielk1977       */
1488b3bce662Sdanielk1977       NameContext sNC;
14896ab3a2ecSdanielk1977       Select *pS = pExpr->x.pSelect;
1490955de52cSdanielk1977       Expr *p = pS->pEList->a[0].pExpr;
14916ab3a2ecSdanielk1977       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
1492955de52cSdanielk1977       sNC.pSrcList = pS->pSrc;
1493b3bce662Sdanielk1977       sNC.pNext = pNC;
1494955de52cSdanielk1977       sNC.pParse = pNC->pParse;
14955f3e5e74Sdrh       zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
149600e279d9Sdanielk1977       break;
1497fcb78a49Sdrh     }
149893758c8dSdanielk1977 #endif
149900e279d9Sdanielk1977   }
150000e279d9Sdanielk1977 
15015f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
15025f3e5e74Sdrh   if( pzOrigDb ){
15035f3e5e74Sdrh     assert( pzOrigTab && pzOrigCol );
15045f3e5e74Sdrh     *pzOrigDb = zOrigDb;
15055f3e5e74Sdrh     *pzOrigTab = zOrigTab;
15065f3e5e74Sdrh     *pzOrigCol = zOrigCol;
1507955de52cSdanielk1977   }
15085f3e5e74Sdrh #endif
15095f3e5e74Sdrh   if( pEstWidth ) *pEstWidth = estWidth;
1510517eb646Sdanielk1977   return zType;
1511517eb646Sdanielk1977 }
1512517eb646Sdanielk1977 
1513517eb646Sdanielk1977 /*
1514517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
1515517eb646Sdanielk1977 ** in the result set.
1516517eb646Sdanielk1977 */
1517517eb646Sdanielk1977 static void generateColumnTypes(
1518517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
1519517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
1520517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
1521517eb646Sdanielk1977 ){
15223f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE
1523517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
1524517eb646Sdanielk1977   int i;
1525b3bce662Sdanielk1977   NameContext sNC;
1526b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
1527955de52cSdanielk1977   sNC.pParse = pParse;
1528eac5fc04Sdrh   sNC.pNext = 0;
1529517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
1530517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
15313f913576Sdrh     const char *zType;
15323f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1533955de52cSdanielk1977     const char *zOrigDb = 0;
1534955de52cSdanielk1977     const char *zOrigTab = 0;
1535955de52cSdanielk1977     const char *zOrigCol = 0;
15365f3e5e74Sdrh     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
1537955de52cSdanielk1977 
153885b623f2Sdrh     /* The vdbe must make its own copy of the column-type and other
15394b1ae99dSdanielk1977     ** column specific strings, in case the schema is reset before this
15404b1ae99dSdanielk1977     ** virtual machine is deleted.
1541fbcd585fSdanielk1977     */
154210fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
154310fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
154410fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
15453f913576Sdrh #else
15465f3e5e74Sdrh     zType = columnType(&sNC, p, 0, 0, 0, 0);
15473f913576Sdrh #endif
154810fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
1549fcb78a49Sdrh   }
15505f3e5e74Sdrh #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
1551fcb78a49Sdrh }
1552fcb78a49Sdrh 
1553eac5fc04Sdrh 
1554eac5fc04Sdrh /*
1555ec360a8dSdrh ** Compute the column names for a SELECT statement.
1556ec360a8dSdrh **
1557ec360a8dSdrh ** The only guarantee that SQLite makes about column names is that if the
1558ec360a8dSdrh ** column has an AS clause assigning it a name, that will be the name used.
1559ec360a8dSdrh ** That is the only documented guarantee.  However, countless applications
1560ec360a8dSdrh ** developed over the years have made baseless assumptions about column names
1561ec360a8dSdrh ** and will break if those assumptions changes.  Hence, use extreme caution
1562ec360a8dSdrh ** when modifying this routine to avoid breaking legacy.
1563ec360a8dSdrh **
1564ec360a8dSdrh ** See Also: sqlite3ColumnsFromExprList()
1565ec360a8dSdrh **
1566ec360a8dSdrh ** The PRAGMA short_column_names and PRAGMA full_column_names settings are
1567ec360a8dSdrh ** deprecated.  The default setting is short=ON, full=OFF.  99.9% of all
1568ec360a8dSdrh ** applications should operate this way.  Nevertheless, we need to support the
1569ec360a8dSdrh ** other modes for legacy:
1570ec360a8dSdrh **
1571ec360a8dSdrh **    short=OFF, full=OFF:      Column name is the text of the expression has it
1572ec360a8dSdrh **                              originally appears in the SELECT statement.  In
1573ec360a8dSdrh **                              other words, the zSpan of the result expression.
1574ec360a8dSdrh **
1575ec360a8dSdrh **    short=ON, full=OFF:       (This is the default setting).  If the result
15763d240d21Sdrh **                              refers directly to a table column, then the
15773d240d21Sdrh **                              result column name is just the table column
15783d240d21Sdrh **                              name: COLUMN.  Otherwise use zSpan.
1579ec360a8dSdrh **
1580ec360a8dSdrh **    full=ON, short=ANY:       If the result refers directly to a table column,
1581ec360a8dSdrh **                              then the result column name with the table name
1582ec360a8dSdrh **                              prefix, ex: TABLE.COLUMN.  Otherwise use zSpan.
158382c3d636Sdrh */
1584832508b7Sdrh static void generateColumnNames(
1585832508b7Sdrh   Parse *pParse,      /* Parser context */
1586f35f2f92Sdrh   Select *pSelect     /* Generate column names for this SELECT statement */
1587832508b7Sdrh ){
1588d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1589eac5fc04Sdrh   int i;
1590eac5fc04Sdrh   Table *pTab;
1591f35f2f92Sdrh   SrcList *pTabList;
1592f35f2f92Sdrh   ExprList *pEList;
15939bb575fdSdrh   sqlite3 *db = pParse->db;
1594ec360a8dSdrh   int fullName;    /* TABLE.COLUMN if no AS clause and is a direct table ref */
1595ec360a8dSdrh   int srcName;     /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
1596fcabd464Sdrh 
1597fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN
15983cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
15993cf86063Sdanielk1977   if( pParse->explain ){
160061de0d1bSdanielk1977     return;
16013cf86063Sdanielk1977   }
16025338a5f7Sdanielk1977 #endif
16033cf86063Sdanielk1977 
16049802947fSdrh   if( pParse->colNamesSet || db->mallocFailed ) return;
1605f35f2f92Sdrh   /* Column names are determined by the left-most term of a compound select */
1606f35f2f92Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
1607f35f2f92Sdrh   pTabList = pSelect->pSrc;
1608f35f2f92Sdrh   pEList = pSelect->pEList;
16099802947fSdrh   assert( v!=0 );
1610f7ce4291Sdrh   assert( pTabList!=0 );
1611d8bc7086Sdrh   pParse->colNamesSet = 1;
1612ec360a8dSdrh   fullName = (db->flags & SQLITE_FullColNames)!=0;
1613ec360a8dSdrh   srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
161422322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
161582c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
1616ec360a8dSdrh     Expr *p = pEList->a[i].pExpr;
1617ec360a8dSdrh 
1618ec360a8dSdrh     assert( p!=0 );
16194dd89d5aSdrh     assert( p->op!=TK_AGG_COLUMN );  /* Agg processing has not run yet */
16203d240d21Sdrh     assert( p->op!=TK_COLUMN || p->pTab!=0 ); /* Covering idx not yet coded */
162182c3d636Sdrh     if( pEList->a[i].zName ){
1622ec360a8dSdrh       /* An AS clause always takes first priority */
162382c3d636Sdrh       char *zName = pEList->a[i].zName;
162410fb749bSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
1625f35f2f92Sdrh     }else if( srcName && p->op==TK_COLUMN ){
162697665873Sdrh       char *zCol;
16278aff1015Sdrh       int iCol = p->iColumn;
1628f35f2f92Sdrh       pTab = p->pTab;
1629f35f2f92Sdrh       assert( pTab!=0 );
16308aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
163197665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1632b1363206Sdrh       if( iCol<0 ){
163347a6db2bSdrh         zCol = "rowid";
1634b1363206Sdrh       }else{
1635b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
1636b1363206Sdrh       }
1637ec360a8dSdrh       if( fullName ){
163882c3d636Sdrh         char *zName = 0;
16391c767f0dSdrh         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
164010fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
164182c3d636Sdrh       }else{
164210fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
164382c3d636Sdrh       }
16441bee3d7bSdrh     }else{
1645859bc542Sdrh       const char *z = pEList->a[i].zSpan;
1646859bc542Sdrh       z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
1647859bc542Sdrh       sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
164882c3d636Sdrh     }
164982c3d636Sdrh   }
165076d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
16515080aaa7Sdrh }
165282c3d636Sdrh 
1653d8bc7086Sdrh /*
165460ec914cSpeter.d.reid ** Given an expression list (which is really the list of expressions
16557d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate
16567d10d5a6Sdrh ** column names for a table that would hold the expression list.
16577d10d5a6Sdrh **
16587d10d5a6Sdrh ** All column names will be unique.
16597d10d5a6Sdrh **
16607d10d5a6Sdrh ** Only the column names are computed.  Column.zType, Column.zColl,
16617d10d5a6Sdrh ** and other fields of Column are zeroed.
16627d10d5a6Sdrh **
16637d10d5a6Sdrh ** Return SQLITE_OK on success.  If a memory allocation error occurs,
16647d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
1665ec360a8dSdrh **
1666ec360a8dSdrh ** The only guarantee that SQLite makes about column names is that if the
1667ec360a8dSdrh ** column has an AS clause assigning it a name, that will be the name used.
1668ec360a8dSdrh ** That is the only documented guarantee.  However, countless applications
1669ec360a8dSdrh ** developed over the years have made baseless assumptions about column names
1670ec360a8dSdrh ** and will break if those assumptions changes.  Hence, use extreme caution
1671ec360a8dSdrh ** when modifying this routine to avoid breaking legacy.
1672ec360a8dSdrh **
1673ec360a8dSdrh ** See Also: generateColumnNames()
1674315555caSdrh */
16758981b904Sdrh int sqlite3ColumnsFromExprList(
16767d10d5a6Sdrh   Parse *pParse,          /* Parsing context */
16777d10d5a6Sdrh   ExprList *pEList,       /* Expr list from which to derive column names */
1678d815f17dSdrh   i16 *pnCol,             /* Write the number of columns here */
16797d10d5a6Sdrh   Column **paCol          /* Write the new column list here */
16807d10d5a6Sdrh ){
1681dc5ea5c7Sdrh   sqlite3 *db = pParse->db;   /* Database connection */
1682dc5ea5c7Sdrh   int i, j;                   /* Loop counters */
1683ebed3fa3Sdrh   u32 cnt;                    /* Index added to make the name unique */
1684dc5ea5c7Sdrh   Column *aCol, *pCol;        /* For looping over result columns */
1685dc5ea5c7Sdrh   int nCol;                   /* Number of columns in the result set */
1686dc5ea5c7Sdrh   char *zName;                /* Column name */
1687dc5ea5c7Sdrh   int nName;                  /* Size of name in zName[] */
16880315e3ccSdrh   Hash ht;                    /* Hash table of column names */
168979d5f63fSdrh 
16900315e3ccSdrh   sqlite3HashInit(&ht);
16918c2e0f02Sdan   if( pEList ){
16928c2e0f02Sdan     nCol = pEList->nExpr;
16938c2e0f02Sdan     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
16948c2e0f02Sdan     testcase( aCol==0 );
16958c2e0f02Sdan   }else{
16968c2e0f02Sdan     nCol = 0;
16978c2e0f02Sdan     aCol = 0;
16988c2e0f02Sdan   }
16998836cbbcSdan   assert( nCol==(i16)nCol );
17008c2e0f02Sdan   *pnCol = nCol;
17018c2e0f02Sdan   *paCol = aCol;
17028c2e0f02Sdan 
17030315e3ccSdrh   for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
170479d5f63fSdrh     /* Get an appropriate name for the column
170579d5f63fSdrh     */
170691bb0eedSdrh     if( (zName = pEList->a[i].zName)!=0 ){
170779d5f63fSdrh       /* If the column contains an "AS <name>" phrase, use <name> as the name */
17087d10d5a6Sdrh     }else{
1709ec360a8dSdrh       Expr *pColExpr = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
1710b07028f7Sdrh       while( pColExpr->op==TK_DOT ){
1711b07028f7Sdrh         pColExpr = pColExpr->pRight;
1712b07028f7Sdrh         assert( pColExpr!=0 );
1713b07028f7Sdrh       }
17141112cc79Sdrh       if( (pColExpr->op==TK_COLUMN || pColExpr->op==TK_AGG_COLUMN)
17151112cc79Sdrh        && pColExpr->pTab!=0
17161112cc79Sdrh       ){
171793a960a0Sdrh         /* For columns use the column name name */
1718dc5ea5c7Sdrh         int iCol = pColExpr->iColumn;
1719ec360a8dSdrh         Table *pTab = pColExpr->pTab;
1720f0209f74Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
172196ceaf86Sdrh         zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
1722b7916a78Sdrh       }else if( pColExpr->op==TK_ID ){
172333e619fcSdrh         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
172496ceaf86Sdrh         zName = pColExpr->u.zToken;
172593a960a0Sdrh       }else{
172679d5f63fSdrh         /* Use the original text of the column expression as its name */
172796ceaf86Sdrh         zName = pEList->a[i].zSpan;
17287d10d5a6Sdrh       }
172922f70c32Sdrh     }
1730d7ca600eSdrh     if( zName ){
1731d7ca600eSdrh       zName = sqlite3DbStrDup(db, zName);
1732d7ca600eSdrh     }else{
1733155507b3Sdrh       zName = sqlite3MPrintf(db,"column%d",i+1);
1734d7ca600eSdrh     }
173579d5f63fSdrh 
173679d5f63fSdrh     /* Make sure the column name is unique.  If the name is not unique,
173760ec914cSpeter.d.reid     ** append an integer to the name so that it becomes unique.
173879d5f63fSdrh     */
17390315e3ccSdrh     cnt = 0;
17400315e3ccSdrh     while( zName && sqlite3HashFind(&ht, zName)!=0 ){
17410315e3ccSdrh       nName = sqlite3Strlen30(zName);
1742f7ee8965Sdrh       if( nName>0 ){
17430315e3ccSdrh         for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
17440315e3ccSdrh         if( zName[j]==':' ) nName = j;
1745f7ee8965Sdrh       }
174696ceaf86Sdrh       zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
1747ebed3fa3Sdrh       if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
174879d5f63fSdrh     }
174991bb0eedSdrh     pCol->zName = zName;
1750ba68f8f3Sdan     sqlite3ColumnPropertiesFromName(0, pCol);
175103d69a68Sdrh     if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
17524a642b60Sdrh       sqlite3OomFault(db);
17537d10d5a6Sdrh     }
17540315e3ccSdrh   }
17550315e3ccSdrh   sqlite3HashClear(&ht);
17567d10d5a6Sdrh   if( db->mallocFailed ){
17577d10d5a6Sdrh     for(j=0; j<i; j++){
17587d10d5a6Sdrh       sqlite3DbFree(db, aCol[j].zName);
17597d10d5a6Sdrh     }
17607d10d5a6Sdrh     sqlite3DbFree(db, aCol);
17617d10d5a6Sdrh     *paCol = 0;
17627d10d5a6Sdrh     *pnCol = 0;
1763fad3039cSmistachkin     return SQLITE_NOMEM_BKPT;
17647d10d5a6Sdrh   }
17657d10d5a6Sdrh   return SQLITE_OK;
17667d10d5a6Sdrh }
1767e014a838Sdanielk1977 
17687d10d5a6Sdrh /*
17697d10d5a6Sdrh ** Add type and collation information to a column list based on
17707d10d5a6Sdrh ** a SELECT statement.
17717d10d5a6Sdrh **
17727d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList().
17737d10d5a6Sdrh ** The column list has only names, not types or collations.  This
17747d10d5a6Sdrh ** routine goes through and adds the types and collations.
17757d10d5a6Sdrh **
1776b08a67a7Sshane ** This routine requires that all identifiers in the SELECT
17777d10d5a6Sdrh ** statement be resolved.
177879d5f63fSdrh */
1779ed06a131Sdrh void sqlite3SelectAddColumnTypeAndCollation(
17807d10d5a6Sdrh   Parse *pParse,        /* Parsing contexts */
1781186ad8ccSdrh   Table *pTab,          /* Add column type information to this table */
17827d10d5a6Sdrh   Select *pSelect       /* SELECT used to determine types and collations */
17837d10d5a6Sdrh ){
17847d10d5a6Sdrh   sqlite3 *db = pParse->db;
17857d10d5a6Sdrh   NameContext sNC;
17867d10d5a6Sdrh   Column *pCol;
17877d10d5a6Sdrh   CollSeq *pColl;
17887d10d5a6Sdrh   int i;
17897d10d5a6Sdrh   Expr *p;
17907d10d5a6Sdrh   struct ExprList_item *a;
1791186ad8ccSdrh   u64 szAll = 0;
17927d10d5a6Sdrh 
17937d10d5a6Sdrh   assert( pSelect!=0 );
17947d10d5a6Sdrh   assert( (pSelect->selFlags & SF_Resolved)!=0 );
1795186ad8ccSdrh   assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
17967d10d5a6Sdrh   if( db->mallocFailed ) return;
1797c43e8be8Sdrh   memset(&sNC, 0, sizeof(sNC));
1798b3bce662Sdanielk1977   sNC.pSrcList = pSelect->pSrc;
17997d10d5a6Sdrh   a = pSelect->pEList->a;
1800186ad8ccSdrh   for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
1801ed06a131Sdrh     const char *zType;
1802ed06a131Sdrh     int n, m;
18037d10d5a6Sdrh     p = a[i].pExpr;
1804ed06a131Sdrh     zType = columnType(&sNC, p, 0, 0, 0, &pCol->szEst);
1805186ad8ccSdrh     szAll += pCol->szEst;
1806c60e9b82Sdanielk1977     pCol->affinity = sqlite3ExprAffinity(p);
1807ed06a131Sdrh     if( zType && (m = sqlite3Strlen30(zType))>0 ){
1808ed06a131Sdrh       n = sqlite3Strlen30(pCol->zName);
1809ed06a131Sdrh       pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
1810ed06a131Sdrh       if( pCol->zName ){
1811ed06a131Sdrh         memcpy(&pCol->zName[n+1], zType, m+1);
1812ed06a131Sdrh         pCol->colFlags |= COLFLAG_HASTYPE;
1813ed06a131Sdrh       }
1814ed06a131Sdrh     }
181505883a34Sdrh     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
1816b3bf556eSdanielk1977     pColl = sqlite3ExprCollSeq(pParse, p);
18171cb50c88Sdrh     if( pColl && pCol->zColl==0 ){
181817435752Sdrh       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
18190202b29eSdanielk1977     }
182022f70c32Sdrh   }
1821186ad8ccSdrh   pTab->szTabRow = sqlite3LogEst(szAll*4);
18227d10d5a6Sdrh }
18237d10d5a6Sdrh 
18247d10d5a6Sdrh /*
18257d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes
18267d10d5a6Sdrh ** the result set of that SELECT.
18277d10d5a6Sdrh */
18287d10d5a6Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
18297d10d5a6Sdrh   Table *pTab;
18307d10d5a6Sdrh   sqlite3 *db = pParse->db;
18317d10d5a6Sdrh   int savedFlags;
18327d10d5a6Sdrh 
18337d10d5a6Sdrh   savedFlags = db->flags;
18347d10d5a6Sdrh   db->flags &= ~SQLITE_FullColNames;
18357d10d5a6Sdrh   db->flags |= SQLITE_ShortColNames;
18367d10d5a6Sdrh   sqlite3SelectPrep(pParse, pSelect, 0);
18377d10d5a6Sdrh   if( pParse->nErr ) return 0;
18387d10d5a6Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
18397d10d5a6Sdrh   db->flags = savedFlags;
18407d10d5a6Sdrh   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
18417d10d5a6Sdrh   if( pTab==0 ){
18427d10d5a6Sdrh     return 0;
18437d10d5a6Sdrh   }
1844373cc2ddSdrh   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
1845b2468954Sdrh   ** is disabled */
18464a642b60Sdrh   assert( db->lookaside.bDisable );
184779df7782Sdrh   pTab->nTabRef = 1;
18487d10d5a6Sdrh   pTab->zName = 0;
1849cfc9df76Sdan   pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
18508981b904Sdrh   sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
1851ed06a131Sdrh   sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
185222f70c32Sdrh   pTab->iPKey = -1;
18537ce72f69Sdrh   if( db->mallocFailed ){
18541feeaed2Sdan     sqlite3DeleteTable(db, pTab);
18557ce72f69Sdrh     return 0;
18567ce72f69Sdrh   }
185722f70c32Sdrh   return pTab;
185822f70c32Sdrh }
185922f70c32Sdrh 
186022f70c32Sdrh /*
1861d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1862d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1863d8bc7086Sdrh */
186455965619Sdrh Vdbe *sqlite3GetVdbe(Parse *pParse){
186555965619Sdrh   if( pParse->pVdbe ){
186655965619Sdrh     return pParse->pVdbe;
186755965619Sdrh   }
1868e0e261a4Sdrh   if( pParse->pToplevel==0
1869e0e261a4Sdrh    && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
1870e0e261a4Sdrh   ){
1871e0e261a4Sdrh     pParse->okConstFactor = 1;
1872949f9cd5Sdrh   }
187355965619Sdrh   return sqlite3VdbeCreate(pParse);
18746f077343Sdrh }
1875d8bc7086Sdrh 
187615007a99Sdrh 
1877d8bc7086Sdrh /*
18787b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
1879ec7429aeSdrh ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
18807b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
1881a2dc3b1aSdanielk1977 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1882a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute
1883a2dc3b1aSdanielk1977 ** the limit and offset.  If there is no limit and/or offset, then
1884a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative.
18857b58daeaSdrh **
1886d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if
1887ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset.  iLimit and
1888aa9ce707Sdrh ** iOffset should have been preset to appropriate default values (zero)
1889aa9ce707Sdrh ** prior to calling this routine.
1890aa9ce707Sdrh **
1891aa9ce707Sdrh ** The iOffset register (if it exists) is initialized to the value
1892aa9ce707Sdrh ** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
1893aa9ce707Sdrh ** iOffset+1 is initialized to LIMIT+OFFSET.
1894aa9ce707Sdrh **
1895ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
18967b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
18977b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
18987b58daeaSdrh ** SELECT statements.
18997b58daeaSdrh */
1900ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
190102afc861Sdrh   Vdbe *v = 0;
190202afc861Sdrh   int iLimit = 0;
190315007a99Sdrh   int iOffset;
19048b0cf38aSdrh   int n;
19050acb7e48Sdrh   if( p->iLimit ) return;
190615007a99Sdrh 
19077b58daeaSdrh   /*
19087b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
1909f7b5496eSdrh   ** controversy about what the correct behavior should be.
19107b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
19117b58daeaSdrh   ** no rows.
19127b58daeaSdrh   */
1913ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
1914373cc2ddSdrh   assert( p->pOffset==0 || p->pLimit!=0 );
1915a2dc3b1aSdanielk1977   if( p->pLimit ){
19160a07c107Sdrh     p->iLimit = iLimit = ++pParse->nMem;
191715007a99Sdrh     v = sqlite3GetVdbe(pParse);
1918aa9ce707Sdrh     assert( v!=0 );
19199b918ed1Sdrh     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
19209b918ed1Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
19219b918ed1Sdrh       VdbeComment((v, "LIMIT counter"));
1922456e4e4fSdrh       if( n==0 ){
1923076e85f5Sdrh         sqlite3VdbeGoto(v, iBreak);
1924c3489bbfSdrh       }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
1925c3489bbfSdrh         p->nSelectRow = sqlite3LogEst((u64)n);
1926c3489bbfSdrh         p->selFlags |= SF_FixedLimit;
19279b918ed1Sdrh       }
19289b918ed1Sdrh     }else{
1929b7654111Sdrh       sqlite3ExprCode(pParse, p->pLimit, iLimit);
1930688852abSdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
1931d4e70ebdSdrh       VdbeComment((v, "LIMIT counter"));
193216897072Sdrh       sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
19339b918ed1Sdrh     }
1934a2dc3b1aSdanielk1977     if( p->pOffset ){
19350a07c107Sdrh       p->iOffset = iOffset = ++pParse->nMem;
1936b7654111Sdrh       pParse->nMem++;   /* Allocate an extra register for limit+offset */
1937b7654111Sdrh       sqlite3ExprCode(pParse, p->pOffset, iOffset);
1938688852abSdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
1939d4e70ebdSdrh       VdbeComment((v, "OFFSET counter"));
1940cc2fa4cfSdrh       sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
1941d4e70ebdSdrh       VdbeComment((v, "LIMIT+OFFSET"));
1942b7654111Sdrh     }
1943d59ba6ceSdrh   }
19447b58daeaSdrh }
19457b58daeaSdrh 
1946b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1947fbc4ee7bSdrh /*
1948fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
1949fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
1950fbc4ee7bSdrh ** the column has no default collating sequence.
1951fbc4ee7bSdrh **
1952fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
1953fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
1954fbc4ee7bSdrh */
1955dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1956fbc4ee7bSdrh   CollSeq *pRet;
1957dc1bdc4fSdanielk1977   if( p->pPrior ){
1958dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1959fbc4ee7bSdrh   }else{
1960fbc4ee7bSdrh     pRet = 0;
1961dc1bdc4fSdanielk1977   }
196210c081adSdrh   assert( iCol>=0 );
19632ec18a3cSdrh   /* iCol must be less than p->pEList->nExpr.  Otherwise an error would
19642ec18a3cSdrh   ** have been thrown during name resolution and we would not have gotten
19652ec18a3cSdrh   ** this far */
19662ec18a3cSdrh   if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
1967dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1968dc1bdc4fSdanielk1977   }
1969dc1bdc4fSdanielk1977   return pRet;
1970d3d39e93Sdrh }
1971d3d39e93Sdrh 
197253bed45eSdan /*
197353bed45eSdan ** The select statement passed as the second parameter is a compound SELECT
197453bed45eSdan ** with an ORDER BY clause. This function allocates and returns a KeyInfo
197553bed45eSdan ** structure suitable for implementing the ORDER BY.
197653bed45eSdan **
197753bed45eSdan ** Space to hold the KeyInfo structure is obtained from malloc. The calling
197853bed45eSdan ** function is responsible for ensuring that this structure is eventually
197953bed45eSdan ** freed.
198053bed45eSdan */
198153bed45eSdan static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
198253bed45eSdan   ExprList *pOrderBy = p->pOrderBy;
198353bed45eSdan   int nOrderBy = p->pOrderBy->nExpr;
198453bed45eSdan   sqlite3 *db = pParse->db;
198553bed45eSdan   KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
198653bed45eSdan   if( pRet ){
198753bed45eSdan     int i;
198853bed45eSdan     for(i=0; i<nOrderBy; i++){
198953bed45eSdan       struct ExprList_item *pItem = &pOrderBy->a[i];
199053bed45eSdan       Expr *pTerm = pItem->pExpr;
199153bed45eSdan       CollSeq *pColl;
199253bed45eSdan 
199353bed45eSdan       if( pTerm->flags & EP_Collate ){
199453bed45eSdan         pColl = sqlite3ExprCollSeq(pParse, pTerm);
199553bed45eSdan       }else{
199653bed45eSdan         pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
199753bed45eSdan         if( pColl==0 ) pColl = db->pDfltColl;
199853bed45eSdan         pOrderBy->a[i].pExpr =
199953bed45eSdan           sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
200053bed45eSdan       }
200153bed45eSdan       assert( sqlite3KeyInfoIsWriteable(pRet) );
200253bed45eSdan       pRet->aColl[i] = pColl;
200353bed45eSdan       pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
200453bed45eSdan     }
200553bed45eSdan   }
200653bed45eSdan 
200753bed45eSdan   return pRet;
200853bed45eSdan }
2009d3d39e93Sdrh 
2010781def29Sdrh #ifndef SQLITE_OMIT_CTE
2011781def29Sdrh /*
2012781def29Sdrh ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
2013781def29Sdrh ** query of the form:
2014781def29Sdrh **
2015781def29Sdrh **   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
2016781def29Sdrh **                         \___________/             \_______________/
2017781def29Sdrh **                           p->pPrior                      p
2018781def29Sdrh **
2019781def29Sdrh **
2020781def29Sdrh ** There is exactly one reference to the recursive-table in the FROM clause
20218a48b9c0Sdrh ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
2022781def29Sdrh **
2023781def29Sdrh ** The setup-query runs once to generate an initial set of rows that go
2024781def29Sdrh ** into a Queue table.  Rows are extracted from the Queue table one by
2025fe1c6bb9Sdrh ** one.  Each row extracted from Queue is output to pDest.  Then the single
2026fe1c6bb9Sdrh ** extracted row (now in the iCurrent table) becomes the content of the
2027fe1c6bb9Sdrh ** recursive-table for a recursive-query run.  The output of the recursive-query
2028781def29Sdrh ** is added back into the Queue table.  Then another row is extracted from Queue
2029781def29Sdrh ** and the iteration continues until the Queue table is empty.
2030781def29Sdrh **
2031781def29Sdrh ** If the compound query operator is UNION then no duplicate rows are ever
2032781def29Sdrh ** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
2033781def29Sdrh ** that have ever been inserted into Queue and causes duplicates to be
2034781def29Sdrh ** discarded.  If the operator is UNION ALL, then duplicates are allowed.
2035781def29Sdrh **
2036781def29Sdrh ** If the query has an ORDER BY, then entries in the Queue table are kept in
2037781def29Sdrh ** ORDER BY order and the first entry is extracted for each cycle.  Without
2038781def29Sdrh ** an ORDER BY, the Queue table is just a FIFO.
2039781def29Sdrh **
2040781def29Sdrh ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
2041781def29Sdrh ** have been output to pDest.  A LIMIT of zero means to output no rows and a
2042781def29Sdrh ** negative LIMIT means to output all rows.  If there is also an OFFSET clause
2043781def29Sdrh ** with a positive value, then the first OFFSET outputs are discarded rather
2044781def29Sdrh ** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
2045781def29Sdrh ** rows have been skipped.
2046781def29Sdrh */
2047781def29Sdrh static void generateWithRecursiveQuery(
2048781def29Sdrh   Parse *pParse,        /* Parsing context */
2049781def29Sdrh   Select *p,            /* The recursive SELECT to be coded */
2050781def29Sdrh   SelectDest *pDest     /* What to do with query results */
2051781def29Sdrh ){
2052781def29Sdrh   SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
2053781def29Sdrh   int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
2054781def29Sdrh   Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
2055781def29Sdrh   Select *pSetup = p->pPrior;   /* The setup query */
2056781def29Sdrh   int addrTop;                  /* Top of the loop */
2057781def29Sdrh   int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
2058edf83d1eSdrh   int iCurrent = 0;             /* The Current table */
2059781def29Sdrh   int regCurrent;               /* Register holding Current table */
2060781def29Sdrh   int iQueue;                   /* The Queue table */
2061781def29Sdrh   int iDistinct = 0;            /* To ensure unique results if UNION */
20628e1ee88cSdrh   int eDest = SRT_Fifo;         /* How to write to Queue */
2063781def29Sdrh   SelectDest destQueue;         /* SelectDest targetting the Queue table */
2064781def29Sdrh   int i;                        /* Loop counter */
2065781def29Sdrh   int rc;                       /* Result code */
2066fe1c6bb9Sdrh   ExprList *pOrderBy;           /* The ORDER BY clause */
2067aa9ce707Sdrh   Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
2068aa9ce707Sdrh   int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
2069781def29Sdrh 
2070781def29Sdrh   /* Obtain authorization to do a recursive query */
2071781def29Sdrh   if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
2072781def29Sdrh 
2073aa9ce707Sdrh   /* Process the LIMIT and OFFSET clauses, if they exist */
2074aa9ce707Sdrh   addrBreak = sqlite3VdbeMakeLabel(v);
207569b9383eSdan   p->nSelectRow = 320;  /* 4 billion rows */
2076aa9ce707Sdrh   computeLimitRegisters(pParse, p, addrBreak);
2077aa9ce707Sdrh   pLimit = p->pLimit;
2078aa9ce707Sdrh   pOffset = p->pOffset;
2079aa9ce707Sdrh   regLimit = p->iLimit;
2080aa9ce707Sdrh   regOffset = p->iOffset;
2081aa9ce707Sdrh   p->pLimit = p->pOffset = 0;
2082aa9ce707Sdrh   p->iLimit = p->iOffset = 0;
208353bed45eSdan   pOrderBy = p->pOrderBy;
2084781def29Sdrh 
2085781def29Sdrh   /* Locate the cursor number of the Current table */
2086781def29Sdrh   for(i=0; ALWAYS(i<pSrc->nSrc); i++){
20878a48b9c0Sdrh     if( pSrc->a[i].fg.isRecursive ){
2088781def29Sdrh       iCurrent = pSrc->a[i].iCursor;
2089781def29Sdrh       break;
2090781def29Sdrh     }
2091781def29Sdrh   }
2092781def29Sdrh 
2093fe1c6bb9Sdrh   /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
2094781def29Sdrh   ** the Distinct table must be exactly one greater than Queue in order
20958e1ee88cSdrh   ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
2096781def29Sdrh   iQueue = pParse->nTab++;
2097781def29Sdrh   if( p->op==TK_UNION ){
20988e1ee88cSdrh     eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
2099781def29Sdrh     iDistinct = pParse->nTab++;
2100fe1c6bb9Sdrh   }else{
21018e1ee88cSdrh     eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
2102781def29Sdrh   }
2103781def29Sdrh   sqlite3SelectDestInit(&destQueue, eDest, iQueue);
2104781def29Sdrh 
2105781def29Sdrh   /* Allocate cursors for Current, Queue, and Distinct. */
2106781def29Sdrh   regCurrent = ++pParse->nMem;
2107781def29Sdrh   sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
2108fe1c6bb9Sdrh   if( pOrderBy ){
210953bed45eSdan     KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
2110fe1c6bb9Sdrh     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
2111fe1c6bb9Sdrh                       (char*)pKeyInfo, P4_KEYINFO);
2112fe1c6bb9Sdrh     destQueue.pOrderBy = pOrderBy;
2113fe1c6bb9Sdrh   }else{
2114781def29Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
2115fe1c6bb9Sdrh   }
2116fe1c6bb9Sdrh   VdbeComment((v, "Queue table"));
2117781def29Sdrh   if( iDistinct ){
2118781def29Sdrh     p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
2119781def29Sdrh     p->selFlags |= SF_UsesEphemeral;
2120781def29Sdrh   }
2121781def29Sdrh 
212253bed45eSdan   /* Detach the ORDER BY clause from the compound SELECT */
212353bed45eSdan   p->pOrderBy = 0;
212453bed45eSdan 
2125781def29Sdrh   /* Store the results of the setup-query in Queue. */
2126d227a291Sdrh   pSetup->pNext = 0;
2127781def29Sdrh   rc = sqlite3Select(pParse, pSetup, &destQueue);
2128d227a291Sdrh   pSetup->pNext = p;
2129fe1c6bb9Sdrh   if( rc ) goto end_of_recursive_query;
2130781def29Sdrh 
2131781def29Sdrh   /* Find the next row in the Queue and output that row */
2132688852abSdrh   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
2133781def29Sdrh 
2134781def29Sdrh   /* Transfer the next row in Queue over to Current */
2135781def29Sdrh   sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
2136fe1c6bb9Sdrh   if( pOrderBy ){
2137fe1c6bb9Sdrh     sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
2138fe1c6bb9Sdrh   }else{
2139781def29Sdrh     sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
2140fe1c6bb9Sdrh   }
2141781def29Sdrh   sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
2142781def29Sdrh 
2143fe1c6bb9Sdrh   /* Output the single row in Current */
2144fe1c6bb9Sdrh   addrCont = sqlite3VdbeMakeLabel(v);
2145aa9ce707Sdrh   codeOffset(v, regOffset, addrCont);
21462def2f7eSdrh   selectInnerLoop(pParse, p, iCurrent,
2147079a3072Sdrh       0, 0, pDest, addrCont, addrBreak);
2148688852abSdrh   if( regLimit ){
214916897072Sdrh     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
2150688852abSdrh     VdbeCoverage(v);
2151688852abSdrh   }
2152fe1c6bb9Sdrh   sqlite3VdbeResolveLabel(v, addrCont);
2153fe1c6bb9Sdrh 
2154781def29Sdrh   /* Execute the recursive SELECT taking the single row in Current as
2155781def29Sdrh   ** the value for the recursive-table. Store the results in the Queue.
2156781def29Sdrh   */
2157b63ce02fSdrh   if( p->selFlags & SF_Aggregate ){
2158b63ce02fSdrh     sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
2159b63ce02fSdrh   }else{
2160781def29Sdrh     p->pPrior = 0;
2161781def29Sdrh     sqlite3Select(pParse, p, &destQueue);
2162781def29Sdrh     assert( p->pPrior==0 );
2163781def29Sdrh     p->pPrior = pSetup;
2164b63ce02fSdrh   }
2165781def29Sdrh 
2166781def29Sdrh   /* Keep running the loop until the Queue is empty */
2167076e85f5Sdrh   sqlite3VdbeGoto(v, addrTop);
2168781def29Sdrh   sqlite3VdbeResolveLabel(v, addrBreak);
2169fe1c6bb9Sdrh 
2170fe1c6bb9Sdrh end_of_recursive_query:
21719afccba2Sdan   sqlite3ExprListDelete(pParse->db, p->pOrderBy);
2172fe1c6bb9Sdrh   p->pOrderBy = pOrderBy;
2173aa9ce707Sdrh   p->pLimit = pLimit;
2174aa9ce707Sdrh   p->pOffset = pOffset;
2175fe1c6bb9Sdrh   return;
2176781def29Sdrh }
2177b68b9778Sdan #endif /* SQLITE_OMIT_CTE */
2178781def29Sdrh 
2179781def29Sdrh /* Forward references */
2180b21e7c70Sdrh static int multiSelectOrderBy(
2181b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
2182b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
2183a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
2184b21e7c70Sdrh );
2185b21e7c70Sdrh 
218645f54a57Sdrh /*
218745f54a57Sdrh ** Handle the special case of a compound-select that originates from a
218845f54a57Sdrh ** VALUES clause.  By handling this as a special case, we avoid deep
218945f54a57Sdrh ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
219045f54a57Sdrh ** on a VALUES clause.
219145f54a57Sdrh **
219245f54a57Sdrh ** Because the Select object originates from a VALUES clause:
219345f54a57Sdrh **   (1) It has no LIMIT or OFFSET
219445f54a57Sdrh **   (2) All terms are UNION ALL
219545f54a57Sdrh **   (3) There is no ORDER BY clause
219645f54a57Sdrh */
219745f54a57Sdrh static int multiSelectValues(
219845f54a57Sdrh   Parse *pParse,        /* Parsing context */
219945f54a57Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
220045f54a57Sdrh   SelectDest *pDest     /* What to do with query results */
220145f54a57Sdrh ){
220245f54a57Sdrh   Select *pPrior;
220345f54a57Sdrh   int nRow = 1;
220445f54a57Sdrh   int rc = 0;
2205772460fdSdrh   assert( p->selFlags & SF_MultiValue );
220645f54a57Sdrh   do{
220745f54a57Sdrh     assert( p->selFlags & SF_Values );
220845f54a57Sdrh     assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
220945f54a57Sdrh     assert( p->pLimit==0 );
221045f54a57Sdrh     assert( p->pOffset==0 );
2211923cadb1Sdan     assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
221245f54a57Sdrh     if( p->pPrior==0 ) break;
221345f54a57Sdrh     assert( p->pPrior->pNext==p );
221445f54a57Sdrh     p = p->pPrior;
221545f54a57Sdrh     nRow++;
221645f54a57Sdrh   }while(1);
221745f54a57Sdrh   while( p ){
221845f54a57Sdrh     pPrior = p->pPrior;
221945f54a57Sdrh     p->pPrior = 0;
222045f54a57Sdrh     rc = sqlite3Select(pParse, p, pDest);
222145f54a57Sdrh     p->pPrior = pPrior;
222245f54a57Sdrh     if( rc ) break;
222345f54a57Sdrh     p->nSelectRow = nRow;
222445f54a57Sdrh     p = p->pNext;
222545f54a57Sdrh   }
222645f54a57Sdrh   return rc;
222745f54a57Sdrh }
2228b21e7c70Sdrh 
2229d3d39e93Sdrh /*
223016ee60ffSdrh ** This routine is called to process a compound query form from
223116ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
223216ee60ffSdrh ** INTERSECT
2233c926afbcSdrh **
2234e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
2235e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
2236e78e8284Sdrh ** in which case this routine will be called recursively.
2237e78e8284Sdrh **
2238e78e8284Sdrh ** The results of the total query are to be written into a destination
2239e78e8284Sdrh ** of type eDest with parameter iParm.
2240e78e8284Sdrh **
2241e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
2242e78e8284Sdrh **
2243e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
2244e78e8284Sdrh **
2245e78e8284Sdrh ** This statement is parsed up as follows:
2246e78e8284Sdrh **
2247e78e8284Sdrh **     SELECT c FROM t3
2248e78e8284Sdrh **      |
2249e78e8284Sdrh **      `----->  SELECT b FROM t2
2250e78e8284Sdrh **                |
22514b11c6d3Sjplyon **                `------>  SELECT a FROM t1
2252e78e8284Sdrh **
2253e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
2254e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
2255e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
2256e78e8284Sdrh **
2257e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
2258e78e8284Sdrh ** individual selects always group from left to right.
225982c3d636Sdrh */
226084ac9d02Sdanielk1977 static int multiSelect(
2261fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
2262fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
2263a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
226484ac9d02Sdanielk1977 ){
226584ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
226610e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
226710e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
22681013c932Sdrh   SelectDest dest;      /* Alternative data destination */
2269eca7e01aSdanielk1977   Select *pDelete = 0;  /* Chain of simple selects to delete */
2270633e6d57Sdrh   sqlite3 *db;          /* Database connection */
22717f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN
2272edf83d1eSdrh   int iSub1 = 0;        /* EQP id of left-hand query */
2273edf83d1eSdrh   int iSub2 = 0;        /* EQP id of right-hand query */
22747f61e92cSdan #endif
227582c3d636Sdrh 
22767b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
2277fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
227882c3d636Sdrh   */
2279701bb3b4Sdrh   assert( p && p->pPrior );  /* Calling function guarantees this much */
2280eae73fbfSdan   assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
2281633e6d57Sdrh   db = pParse->db;
2282d8bc7086Sdrh   pPrior = p->pPrior;
2283bc10377aSdrh   dest = *pDest;
228463347e7dSdrh   if( pPrior->pOrderBy || pPrior->pLimit ){
228563347e7dSdrh     sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
228663347e7dSdrh       pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
228784ac9d02Sdanielk1977     rc = 1;
228884ac9d02Sdanielk1977     goto multi_select_end;
22897b58daeaSdrh   }
229082c3d636Sdrh 
22914adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
2292701bb3b4Sdrh   assert( v!=0 );  /* The VDBE already created by calling function */
2293d8bc7086Sdrh 
22941cc3d75fSdrh   /* Create the destination temporary table if necessary
22951cc3d75fSdrh   */
22966c8c8ce0Sdanielk1977   if( dest.eDest==SRT_EphemTab ){
2297b4964b72Sdanielk1977     assert( p->pEList );
22982b596da8Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
22996c8c8ce0Sdanielk1977     dest.eDest = SRT_Table;
23001cc3d75fSdrh   }
23011cc3d75fSdrh 
230245f54a57Sdrh   /* Special handling for a compound-select that originates as a VALUES clause.
230345f54a57Sdrh   */
2304772460fdSdrh   if( p->selFlags & SF_MultiValue ){
230545f54a57Sdrh     rc = multiSelectValues(pParse, p, &dest);
230645f54a57Sdrh     goto multi_select_end;
230745f54a57Sdrh   }
230845f54a57Sdrh 
2309f6e369a1Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
2310f6e369a1Sdrh   ** in their result sets.
2311f6e369a1Sdrh   */
2312f6e369a1Sdrh   assert( p->pEList && pPrior->pEList );
2313923cadb1Sdan   assert( p->pEList->nExpr==pPrior->pEList->nExpr );
2314f6e369a1Sdrh 
2315eede6a53Sdan #ifndef SQLITE_OMIT_CTE
2316eae73fbfSdan   if( p->selFlags & SF_Recursive ){
2317781def29Sdrh     generateWithRecursiveQuery(pParse, p, &dest);
23188ce7184bSdan   }else
23198ce7184bSdan #endif
2320f6e369a1Sdrh 
2321a9671a22Sdrh   /* Compound SELECTs that have an ORDER BY clause are handled separately.
2322a9671a22Sdrh   */
2323f6e369a1Sdrh   if( p->pOrderBy ){
2324a9671a22Sdrh     return multiSelectOrderBy(pParse, p, pDest);
2325eede6a53Sdan   }else
2326f6e369a1Sdrh 
2327f46f905aSdrh   /* Generate code for the left and right SELECT statements.
2328d8bc7086Sdrh   */
232982c3d636Sdrh   switch( p->op ){
2330f46f905aSdrh     case TK_ALL: {
2331ec7429aeSdrh       int addr = 0;
233295aa47b1Sdrh       int nLimit;
2333a2dc3b1aSdanielk1977       assert( !pPrior->pLimit );
2334547180baSdrh       pPrior->iLimit = p->iLimit;
2335547180baSdrh       pPrior->iOffset = p->iOffset;
2336a2dc3b1aSdanielk1977       pPrior->pLimit = p->pLimit;
2337a2dc3b1aSdanielk1977       pPrior->pOffset = p->pOffset;
23387f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
23397d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &dest);
2340ad68cb6bSdanielk1977       p->pLimit = 0;
2341ad68cb6bSdanielk1977       p->pOffset = 0;
234284ac9d02Sdanielk1977       if( rc ){
234384ac9d02Sdanielk1977         goto multi_select_end;
234484ac9d02Sdanielk1977       }
2345f46f905aSdrh       p->pPrior = 0;
23467b58daeaSdrh       p->iLimit = pPrior->iLimit;
23477b58daeaSdrh       p->iOffset = pPrior->iOffset;
234892b01d53Sdrh       if( p->iLimit ){
234916897072Sdrh         addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
2350d4e70ebdSdrh         VdbeComment((v, "Jump ahead if LIMIT reached"));
23519f1ef45fSdrh         if( p->iOffset ){
2352cc2fa4cfSdrh           sqlite3VdbeAddOp3(v, OP_OffsetLimit,
2353cc2fa4cfSdrh                             p->iLimit, p->iOffset+1, p->iOffset);
23549f1ef45fSdrh         }
2355ec7429aeSdrh       }
23567f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
23577d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &dest);
2358373cc2ddSdrh       testcase( rc!=SQLITE_OK );
2359eca7e01aSdanielk1977       pDelete = p->pPrior;
2360f46f905aSdrh       p->pPrior = pPrior;
2361c3489bbfSdrh       p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
236295aa47b1Sdrh       if( pPrior->pLimit
236395aa47b1Sdrh        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
2364c3489bbfSdrh        && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
236595aa47b1Sdrh       ){
2366c3489bbfSdrh         p->nSelectRow = sqlite3LogEst((u64)nLimit);
236795aa47b1Sdrh       }
2368ec7429aeSdrh       if( addr ){
2369ec7429aeSdrh         sqlite3VdbeJumpHere(v, addr);
2370ec7429aeSdrh       }
2371f46f905aSdrh       break;
2372f46f905aSdrh     }
237382c3d636Sdrh     case TK_EXCEPT:
237482c3d636Sdrh     case TK_UNION: {
2375d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
2376ea678832Sdrh       u8 op = 0;       /* One of the SRT_ operations to apply to self */
2377d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
2378a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
2379dc1bdc4fSdanielk1977       int addr;
23806c8c8ce0Sdanielk1977       SelectDest uniondest;
238182c3d636Sdrh 
2382373cc2ddSdrh       testcase( p->op==TK_EXCEPT );
2383373cc2ddSdrh       testcase( p->op==TK_UNION );
238493a960a0Sdrh       priorOp = SRT_Union;
2385d227a291Sdrh       if( dest.eDest==priorOp ){
2386d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
2387c926afbcSdrh         ** right.
2388d8bc7086Sdrh         */
2389e2f02bacSdrh         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
2390e2f02bacSdrh         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
23912b596da8Sdrh         unionTab = dest.iSDParm;
239282c3d636Sdrh       }else{
2393d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
2394d8bc7086Sdrh         ** intermediate results.
2395d8bc7086Sdrh         */
239682c3d636Sdrh         unionTab = pParse->nTab++;
239793a960a0Sdrh         assert( p->pOrderBy==0 );
239866a5167bSdrh         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
2399b9bb7c18Sdrh         assert( p->addrOpenEphm[0] == -1 );
2400b9bb7c18Sdrh         p->addrOpenEphm[0] = addr;
2401d227a291Sdrh         findRightmost(p)->selFlags |= SF_UsesEphemeral;
240284ac9d02Sdanielk1977         assert( p->pEList );
2403d8bc7086Sdrh       }
2404d8bc7086Sdrh 
2405d8bc7086Sdrh       /* Code the SELECT statements to our left
2406d8bc7086Sdrh       */
2407b3bce662Sdanielk1977       assert( !pPrior->pOrderBy );
24081013c932Sdrh       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
24097f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
24107d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &uniondest);
241184ac9d02Sdanielk1977       if( rc ){
241284ac9d02Sdanielk1977         goto multi_select_end;
241384ac9d02Sdanielk1977       }
2414d8bc7086Sdrh 
2415d8bc7086Sdrh       /* Code the current SELECT statement
2416d8bc7086Sdrh       */
24174cfb22f7Sdrh       if( p->op==TK_EXCEPT ){
24184cfb22f7Sdrh         op = SRT_Except;
24194cfb22f7Sdrh       }else{
24204cfb22f7Sdrh         assert( p->op==TK_UNION );
24214cfb22f7Sdrh         op = SRT_Union;
2422d8bc7086Sdrh       }
242382c3d636Sdrh       p->pPrior = 0;
2424a2dc3b1aSdanielk1977       pLimit = p->pLimit;
2425a2dc3b1aSdanielk1977       p->pLimit = 0;
2426a2dc3b1aSdanielk1977       pOffset = p->pOffset;
2427a2dc3b1aSdanielk1977       p->pOffset = 0;
24286c8c8ce0Sdanielk1977       uniondest.eDest = op;
24297f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
24307d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &uniondest);
2431373cc2ddSdrh       testcase( rc!=SQLITE_OK );
24325bd1bf2eSdrh       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
24335bd1bf2eSdrh       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
2434633e6d57Sdrh       sqlite3ExprListDelete(db, p->pOrderBy);
2435eca7e01aSdanielk1977       pDelete = p->pPrior;
243682c3d636Sdrh       p->pPrior = pPrior;
2437a9671a22Sdrh       p->pOrderBy = 0;
2438c3489bbfSdrh       if( p->op==TK_UNION ){
2439c3489bbfSdrh         p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
2440c3489bbfSdrh       }
2441633e6d57Sdrh       sqlite3ExprDelete(db, p->pLimit);
2442a2dc3b1aSdanielk1977       p->pLimit = pLimit;
2443a2dc3b1aSdanielk1977       p->pOffset = pOffset;
244492b01d53Sdrh       p->iLimit = 0;
244592b01d53Sdrh       p->iOffset = 0;
2446d8bc7086Sdrh 
2447d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
2448d8bc7086Sdrh       ** it is that we currently need.
2449d8bc7086Sdrh       */
24502b596da8Sdrh       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
2451373cc2ddSdrh       if( dest.eDest!=priorOp ){
24526b56344dSdrh         int iCont, iBreak, iStart;
245382c3d636Sdrh         assert( p->pEList );
24544adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
24554adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
2456ec7429aeSdrh         computeLimitRegisters(pParse, p, iBreak);
2457688852abSdrh         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
24584adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
24592def2f7eSdrh         selectInnerLoop(pParse, p, unionTab,
2460e8e4af76Sdrh                         0, 0, &dest, iCont, iBreak);
24614adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
2462688852abSdrh         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
24634adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
246466a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
246582c3d636Sdrh       }
246682c3d636Sdrh       break;
246782c3d636Sdrh     }
2468373cc2ddSdrh     default: assert( p->op==TK_INTERSECT ); {
246982c3d636Sdrh       int tab1, tab2;
24706b56344dSdrh       int iCont, iBreak, iStart;
2471a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset;
2472dc1bdc4fSdanielk1977       int addr;
24731013c932Sdrh       SelectDest intersectdest;
24749cbf3425Sdrh       int r1;
247582c3d636Sdrh 
2476d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
24776206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
2478d8bc7086Sdrh       ** by allocating the tables we will need.
2479d8bc7086Sdrh       */
248082c3d636Sdrh       tab1 = pParse->nTab++;
248182c3d636Sdrh       tab2 = pParse->nTab++;
248293a960a0Sdrh       assert( p->pOrderBy==0 );
2483dc1bdc4fSdanielk1977 
248466a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
2485b9bb7c18Sdrh       assert( p->addrOpenEphm[0] == -1 );
2486b9bb7c18Sdrh       p->addrOpenEphm[0] = addr;
2487d227a291Sdrh       findRightmost(p)->selFlags |= SF_UsesEphemeral;
248884ac9d02Sdanielk1977       assert( p->pEList );
2489d8bc7086Sdrh 
2490d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
2491d8bc7086Sdrh       */
24921013c932Sdrh       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
24937f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
24947d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &intersectdest);
249584ac9d02Sdanielk1977       if( rc ){
249684ac9d02Sdanielk1977         goto multi_select_end;
249784ac9d02Sdanielk1977       }
2498d8bc7086Sdrh 
2499d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
2500d8bc7086Sdrh       */
250166a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
2502b9bb7c18Sdrh       assert( p->addrOpenEphm[1] == -1 );
2503b9bb7c18Sdrh       p->addrOpenEphm[1] = addr;
250482c3d636Sdrh       p->pPrior = 0;
2505a2dc3b1aSdanielk1977       pLimit = p->pLimit;
2506a2dc3b1aSdanielk1977       p->pLimit = 0;
2507a2dc3b1aSdanielk1977       pOffset = p->pOffset;
2508a2dc3b1aSdanielk1977       p->pOffset = 0;
25092b596da8Sdrh       intersectdest.iSDParm = tab2;
25107f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
25117d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &intersectdest);
2512373cc2ddSdrh       testcase( rc!=SQLITE_OK );
2513eca7e01aSdanielk1977       pDelete = p->pPrior;
251482c3d636Sdrh       p->pPrior = pPrior;
251595aa47b1Sdrh       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
2516633e6d57Sdrh       sqlite3ExprDelete(db, p->pLimit);
2517a2dc3b1aSdanielk1977       p->pLimit = pLimit;
2518a2dc3b1aSdanielk1977       p->pOffset = pOffset;
2519d8bc7086Sdrh 
2520d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
2521d8bc7086Sdrh       ** tables.
2522d8bc7086Sdrh       */
252382c3d636Sdrh       assert( p->pEList );
25244adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
25254adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
2526ec7429aeSdrh       computeLimitRegisters(pParse, p, iBreak);
2527688852abSdrh       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
25289cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
25299057fc7cSdrh       iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
2530688852abSdrh       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
25319cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
25322def2f7eSdrh       selectInnerLoop(pParse, p, tab1,
2533e8e4af76Sdrh                       0, 0, &dest, iCont, iBreak);
25344adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
2535688852abSdrh       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
25364adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
253766a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
253866a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
253982c3d636Sdrh       break;
254082c3d636Sdrh     }
254182c3d636Sdrh   }
25428cdbf836Sdrh 
25437f61e92cSdan   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
25447f61e92cSdan 
2545a9671a22Sdrh   /* Compute collating sequences used by
2546a9671a22Sdrh   ** temporary tables needed to implement the compound select.
2547a9671a22Sdrh   ** Attach the KeyInfo structure to all temporary tables.
25488cdbf836Sdrh   **
25498cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
25508cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
25518cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
25528cdbf836Sdrh   ** no temp tables are required.
2553fbc4ee7bSdrh   */
25547d10d5a6Sdrh   if( p->selFlags & SF_UsesEphemeral ){
2555fbc4ee7bSdrh     int i;                        /* Loop counter */
2556fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
25570342b1f5Sdrh     Select *pLoop;                /* For looping through SELECT statements */
2558f68d7d17Sdrh     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
255993a960a0Sdrh     int nCol;                     /* Number of columns in result set */
2560fbc4ee7bSdrh 
2561d227a291Sdrh     assert( p->pNext==0 );
256293a960a0Sdrh     nCol = p->pEList->nExpr;
2563ad124329Sdrh     pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
2564dc1bdc4fSdanielk1977     if( !pKeyInfo ){
2565fad3039cSmistachkin       rc = SQLITE_NOMEM_BKPT;
2566dc1bdc4fSdanielk1977       goto multi_select_end;
2567dc1bdc4fSdanielk1977     }
25680342b1f5Sdrh     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
25690342b1f5Sdrh       *apColl = multiSelectCollSeq(pParse, p, i);
25700342b1f5Sdrh       if( 0==*apColl ){
2571633e6d57Sdrh         *apColl = db->pDfltColl;
2572dc1bdc4fSdanielk1977       }
2573dc1bdc4fSdanielk1977     }
2574dc1bdc4fSdanielk1977 
25750342b1f5Sdrh     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
25760342b1f5Sdrh       for(i=0; i<2; i++){
2577b9bb7c18Sdrh         int addr = pLoop->addrOpenEphm[i];
25780342b1f5Sdrh         if( addr<0 ){
25790342b1f5Sdrh           /* If [0] is unused then [1] is also unused.  So we can
25800342b1f5Sdrh           ** always safely abort as soon as the first unused slot is found */
2581b9bb7c18Sdrh           assert( pLoop->addrOpenEphm[1]<0 );
25820342b1f5Sdrh           break;
25830342b1f5Sdrh         }
25840342b1f5Sdrh         sqlite3VdbeChangeP2(v, addr, nCol);
25852ec2fb22Sdrh         sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
25862ec2fb22Sdrh                             P4_KEYINFO);
25870ee5a1e7Sdrh         pLoop->addrOpenEphm[i] = -1;
25880342b1f5Sdrh       }
2589dc1bdc4fSdanielk1977     }
25902ec2fb22Sdrh     sqlite3KeyInfoUnref(pKeyInfo);
2591dc1bdc4fSdanielk1977   }
2592dc1bdc4fSdanielk1977 
2593dc1bdc4fSdanielk1977 multi_select_end:
25942b596da8Sdrh   pDest->iSdst = dest.iSdst;
25952b596da8Sdrh   pDest->nSdst = dest.nSdst;
2596633e6d57Sdrh   sqlite3SelectDelete(db, pDelete);
259784ac9d02Sdanielk1977   return rc;
25982282792aSdrh }
2599b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
26002282792aSdrh 
2601b21e7c70Sdrh /*
260289b31d73Smistachkin ** Error message for when two or more terms of a compound select have different
260389b31d73Smistachkin ** size result sets.
260489b31d73Smistachkin */
260589b31d73Smistachkin void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
260689b31d73Smistachkin   if( p->selFlags & SF_Values ){
260789b31d73Smistachkin     sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
260889b31d73Smistachkin   }else{
260989b31d73Smistachkin     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
261089b31d73Smistachkin       " do not have the same number of result columns", selectOpName(p->op));
261189b31d73Smistachkin   }
261289b31d73Smistachkin }
261389b31d73Smistachkin 
261489b31d73Smistachkin /*
2615b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a
2616b21e7c70Sdrh ** SELECT statment.
26170acb7e48Sdrh **
26182b596da8Sdrh ** The data to be output is contained in pIn->iSdst.  There are
26192b596da8Sdrh ** pIn->nSdst columns to be output.  pDest is where the output should
26200acb7e48Sdrh ** be sent.
26210acb7e48Sdrh **
26220acb7e48Sdrh ** regReturn is the number of the register holding the subroutine
26230acb7e48Sdrh ** return address.
26240acb7e48Sdrh **
2625f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that
26260acb7e48Sdrh ** records the previous output.  mem[regPrev] is a flag that is false
26270acb7e48Sdrh ** if there has been no previous output.  If regPrev>0 then code is
26280acb7e48Sdrh ** generated to suppress duplicates.  pKeyInfo is used for comparing
26290acb7e48Sdrh ** keys.
26300acb7e48Sdrh **
26310acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to
26320acb7e48Sdrh ** iBreak.
2633b21e7c70Sdrh */
26340acb7e48Sdrh static int generateOutputSubroutine(
263592b01d53Sdrh   Parse *pParse,          /* Parsing context */
263692b01d53Sdrh   Select *p,              /* The SELECT statement */
263792b01d53Sdrh   SelectDest *pIn,        /* Coroutine supplying data */
263892b01d53Sdrh   SelectDest *pDest,      /* Where to send the data */
263992b01d53Sdrh   int regReturn,          /* The return address register */
26400acb7e48Sdrh   int regPrev,            /* Previous result register.  No uniqueness if 0 */
26410acb7e48Sdrh   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
264292b01d53Sdrh   int iBreak              /* Jump here if we hit the LIMIT */
2643b21e7c70Sdrh ){
2644b21e7c70Sdrh   Vdbe *v = pParse->pVdbe;
264592b01d53Sdrh   int iContinue;
264692b01d53Sdrh   int addr;
2647b21e7c70Sdrh 
264892b01d53Sdrh   addr = sqlite3VdbeCurrentAddr(v);
264992b01d53Sdrh   iContinue = sqlite3VdbeMakeLabel(v);
26500acb7e48Sdrh 
26510acb7e48Sdrh   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
26520acb7e48Sdrh   */
26530acb7e48Sdrh   if( regPrev ){
2654728e0f91Sdrh     int addr1, addr2;
2655728e0f91Sdrh     addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
2656728e0f91Sdrh     addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
26572ec2fb22Sdrh                               (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
2658728e0f91Sdrh     sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
2659728e0f91Sdrh     sqlite3VdbeJumpHere(v, addr1);
2660e8e4af76Sdrh     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
2661ec86c724Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
26620acb7e48Sdrh   }
26631f9caa41Sdanielk1977   if( pParse->db->mallocFailed ) return 0;
26640acb7e48Sdrh 
2665d5578433Smistachkin   /* Suppress the first OFFSET entries if there is an OFFSET clause
26660acb7e48Sdrh   */
2667aa9ce707Sdrh   codeOffset(v, p->iOffset, iContinue);
2668b21e7c70Sdrh 
2669e2248cfdSdrh   assert( pDest->eDest!=SRT_Exists );
2670e2248cfdSdrh   assert( pDest->eDest!=SRT_Table );
2671b21e7c70Sdrh   switch( pDest->eDest ){
2672b21e7c70Sdrh     /* Store the result as data using a unique key.
2673b21e7c70Sdrh     */
2674b21e7c70Sdrh     case SRT_EphemTab: {
2675b21e7c70Sdrh       int r1 = sqlite3GetTempReg(pParse);
2676b21e7c70Sdrh       int r2 = sqlite3GetTempReg(pParse);
26772b596da8Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
26782b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
26792b596da8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
2680b21e7c70Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
2681b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r2);
2682b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
2683b21e7c70Sdrh       break;
2684b21e7c70Sdrh     }
2685b21e7c70Sdrh 
2686b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY
26871431807aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)".
2688b21e7c70Sdrh     */
2689b21e7c70Sdrh     case SRT_Set: {
26906fccc35aSdrh       int r1;
269163cecc41Sdrh       testcase( pIn->nSdst>1 );
2692b21e7c70Sdrh       r1 = sqlite3GetTempReg(pParse);
269371c57db0Sdan       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
26941431807aSdrh           r1, pDest->zAffSdst, pIn->nSdst);
26951431807aSdrh       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
26969b4eaebcSdrh       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
26979b4eaebcSdrh                            pIn->iSdst, pIn->nSdst);
2698b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
2699b21e7c70Sdrh       break;
2700b21e7c70Sdrh     }
2701b21e7c70Sdrh 
2702b21e7c70Sdrh     /* If this is a scalar select that is part of an expression, then
2703b21e7c70Sdrh     ** store the results in the appropriate memory cell and break out
2704b21e7c70Sdrh     ** of the scan loop.
2705b21e7c70Sdrh     */
2706b21e7c70Sdrh     case SRT_Mem: {
2707a276e3fdSdrh       assert( pIn->nSdst==1 || pParse->nErr>0 );  testcase( pIn->nSdst!=1 );
27082b596da8Sdrh       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
2709b21e7c70Sdrh       /* The LIMIT clause will jump out of the loop for us */
2710b21e7c70Sdrh       break;
2711b21e7c70Sdrh     }
2712b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
2713b21e7c70Sdrh 
27147d10d5a6Sdrh     /* The results are stored in a sequence of registers
27152b596da8Sdrh     ** starting at pDest->iSdst.  Then the co-routine yields.
2716b21e7c70Sdrh     */
271792b01d53Sdrh     case SRT_Coroutine: {
27182b596da8Sdrh       if( pDest->iSdst==0 ){
27192b596da8Sdrh         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
27202b596da8Sdrh         pDest->nSdst = pIn->nSdst;
2721b21e7c70Sdrh       }
27224b79bde7Sdan       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
27232b596da8Sdrh       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
272492b01d53Sdrh       break;
272592b01d53Sdrh     }
272692b01d53Sdrh 
2727ccfcbceaSdrh     /* If none of the above, then the result destination must be
2728ccfcbceaSdrh     ** SRT_Output.  This routine is never called with any other
2729ccfcbceaSdrh     ** destination other than the ones handled above or SRT_Output.
2730ccfcbceaSdrh     **
2731ccfcbceaSdrh     ** For SRT_Output, results are stored in a sequence of registers.
2732ccfcbceaSdrh     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
2733ccfcbceaSdrh     ** return the next row of result.
27347d10d5a6Sdrh     */
2735ccfcbceaSdrh     default: {
2736ccfcbceaSdrh       assert( pDest->eDest==SRT_Output );
27372b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
27382b596da8Sdrh       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
2739b21e7c70Sdrh       break;
2740b21e7c70Sdrh     }
2741b21e7c70Sdrh   }
274292b01d53Sdrh 
274392b01d53Sdrh   /* Jump to the end of the loop if the LIMIT is reached.
274492b01d53Sdrh   */
274592b01d53Sdrh   if( p->iLimit ){
274616897072Sdrh     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
274792b01d53Sdrh   }
274892b01d53Sdrh 
274992b01d53Sdrh   /* Generate the subroutine return
275092b01d53Sdrh   */
27510acb7e48Sdrh   sqlite3VdbeResolveLabel(v, iContinue);
275292b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
275392b01d53Sdrh 
275492b01d53Sdrh   return addr;
2755b21e7c70Sdrh }
2756b21e7c70Sdrh 
2757b21e7c70Sdrh /*
2758b21e7c70Sdrh ** Alternative compound select code generator for cases when there
2759b21e7c70Sdrh ** is an ORDER BY clause.
2760b21e7c70Sdrh **
2761b21e7c70Sdrh ** We assume a query of the following form:
2762b21e7c70Sdrh **
2763b21e7c70Sdrh **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
2764b21e7c70Sdrh **
2765b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
2766b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as
2767b21e7c70Sdrh ** co-routines.  Then run the co-routines in parallel and merge the results
2768b21e7c70Sdrh ** into the output.  In addition to the two coroutines (called selectA and
2769b21e7c70Sdrh ** selectB) there are 7 subroutines:
2770b21e7c70Sdrh **
2771b21e7c70Sdrh **    outA:    Move the output of the selectA coroutine into the output
2772b21e7c70Sdrh **             of the compound query.
2773b21e7c70Sdrh **
2774b21e7c70Sdrh **    outB:    Move the output of the selectB coroutine into the output
2775b21e7c70Sdrh **             of the compound query.  (Only generated for UNION and
2776b21e7c70Sdrh **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
2777b21e7c70Sdrh **             appears only in B.)
2778b21e7c70Sdrh **
2779b21e7c70Sdrh **    AltB:    Called when there is data from both coroutines and A<B.
2780b21e7c70Sdrh **
2781b21e7c70Sdrh **    AeqB:    Called when there is data from both coroutines and A==B.
2782b21e7c70Sdrh **
2783b21e7c70Sdrh **    AgtB:    Called when there is data from both coroutines and A>B.
2784b21e7c70Sdrh **
2785b21e7c70Sdrh **    EofA:    Called when data is exhausted from selectA.
2786b21e7c70Sdrh **
2787b21e7c70Sdrh **    EofB:    Called when data is exhausted from selectB.
2788b21e7c70Sdrh **
2789b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which
2790b21e7c70Sdrh ** <operator> is used:
2791b21e7c70Sdrh **
2792b21e7c70Sdrh **
2793b21e7c70Sdrh **             UNION ALL         UNION            EXCEPT          INTERSECT
2794b21e7c70Sdrh **          -------------  -----------------  --------------  -----------------
2795b21e7c70Sdrh **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
2796b21e7c70Sdrh **
27970acb7e48Sdrh **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
2798b21e7c70Sdrh **
2799b21e7c70Sdrh **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
2800b21e7c70Sdrh **
28010acb7e48Sdrh **   EofA:   outB, nextB      outB, nextB          halt             halt
2802b21e7c70Sdrh **
28030acb7e48Sdrh **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
28040acb7e48Sdrh **
28050acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
28060acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes
28070acb7e48Sdrh ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
28080acb7e48Sdrh ** following nextX causes a jump to the end of the select processing.
28090acb7e48Sdrh **
28100acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
28110acb7e48Sdrh ** within the output subroutine.  The regPrev register set holds the previously
28120acb7e48Sdrh ** output value.  A comparison is made against this value and the output
28130acb7e48Sdrh ** is skipped if the next results would be the same as the previous.
2814b21e7c70Sdrh **
2815b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven
2816b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom.  Like this:
2817b21e7c70Sdrh **
2818b21e7c70Sdrh **          goto Init
2819b21e7c70Sdrh **     coA: coroutine for left query (A)
2820b21e7c70Sdrh **     coB: coroutine for right query (B)
2821b21e7c70Sdrh **    outA: output one row of A
2822b21e7c70Sdrh **    outB: output one row of B (UNION and UNION ALL only)
2823b21e7c70Sdrh **    EofA: ...
2824b21e7c70Sdrh **    EofB: ...
2825b21e7c70Sdrh **    AltB: ...
2826b21e7c70Sdrh **    AeqB: ...
2827b21e7c70Sdrh **    AgtB: ...
2828b21e7c70Sdrh **    Init: initialize coroutine registers
2829b21e7c70Sdrh **          yield coA
2830b21e7c70Sdrh **          if eof(A) goto EofA
2831b21e7c70Sdrh **          yield coB
2832b21e7c70Sdrh **          if eof(B) goto EofB
2833b21e7c70Sdrh **    Cmpr: Compare A, B
2834b21e7c70Sdrh **          Jump AltB, AeqB, AgtB
2835b21e7c70Sdrh **     End: ...
2836b21e7c70Sdrh **
2837b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
2838b21e7c70Sdrh ** actually called using Gosub and they do not Return.  EofA and EofB loop
2839b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
2840b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB.
2841b21e7c70Sdrh */
2842de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
2843b21e7c70Sdrh static int multiSelectOrderBy(
2844b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
2845b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
2846a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
2847b21e7c70Sdrh ){
28480acb7e48Sdrh   int i, j;             /* Loop counters */
2849b21e7c70Sdrh   Select *pPrior;       /* Another SELECT immediately to our left */
2850b21e7c70Sdrh   Vdbe *v;              /* Generate code to this VDBE */
2851b21e7c70Sdrh   SelectDest destA;     /* Destination for coroutine A */
2852b21e7c70Sdrh   SelectDest destB;     /* Destination for coroutine B */
285392b01d53Sdrh   int regAddrA;         /* Address register for select-A coroutine */
285492b01d53Sdrh   int regAddrB;         /* Address register for select-B coroutine */
285592b01d53Sdrh   int addrSelectA;      /* Address of the select-A coroutine */
285692b01d53Sdrh   int addrSelectB;      /* Address of the select-B coroutine */
285792b01d53Sdrh   int regOutA;          /* Address register for the output-A subroutine */
285892b01d53Sdrh   int regOutB;          /* Address register for the output-B subroutine */
285992b01d53Sdrh   int addrOutA;         /* Address of the output-A subroutine */
2860b27b7f5dSdrh   int addrOutB = 0;     /* Address of the output-B subroutine */
286192b01d53Sdrh   int addrEofA;         /* Address of the select-A-exhausted subroutine */
286281cf13ecSdrh   int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
286392b01d53Sdrh   int addrEofB;         /* Address of the select-B-exhausted subroutine */
286492b01d53Sdrh   int addrAltB;         /* Address of the A<B subroutine */
286592b01d53Sdrh   int addrAeqB;         /* Address of the A==B subroutine */
286692b01d53Sdrh   int addrAgtB;         /* Address of the A>B subroutine */
286792b01d53Sdrh   int regLimitA;        /* Limit register for select-A */
286892b01d53Sdrh   int regLimitB;        /* Limit register for select-A */
28690acb7e48Sdrh   int regPrev;          /* A range of registers to hold previous output */
287092b01d53Sdrh   int savedLimit;       /* Saved value of p->iLimit */
287192b01d53Sdrh   int savedOffset;      /* Saved value of p->iOffset */
287292b01d53Sdrh   int labelCmpr;        /* Label for the start of the merge algorithm */
287392b01d53Sdrh   int labelEnd;         /* Label for the end of the overall SELECT stmt */
2874728e0f91Sdrh   int addr1;            /* Jump instructions that get retargetted */
287592b01d53Sdrh   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
287696067816Sdrh   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
28770acb7e48Sdrh   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
28780acb7e48Sdrh   sqlite3 *db;          /* Database connection */
28790acb7e48Sdrh   ExprList *pOrderBy;   /* The ORDER BY clause */
28800acb7e48Sdrh   int nOrderBy;         /* Number of terms in the ORDER BY clause */
28810acb7e48Sdrh   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
28827f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN
28837f61e92cSdan   int iSub1;            /* EQP id of left-hand query */
28847f61e92cSdan   int iSub2;            /* EQP id of right-hand query */
28857f61e92cSdan #endif
2886b21e7c70Sdrh 
288792b01d53Sdrh   assert( p->pOrderBy!=0 );
288896067816Sdrh   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
28890acb7e48Sdrh   db = pParse->db;
289092b01d53Sdrh   v = pParse->pVdbe;
2891ccfcbceaSdrh   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
289292b01d53Sdrh   labelEnd = sqlite3VdbeMakeLabel(v);
289392b01d53Sdrh   labelCmpr = sqlite3VdbeMakeLabel(v);
28940acb7e48Sdrh 
2895b21e7c70Sdrh 
289692b01d53Sdrh   /* Patch up the ORDER BY clause
289792b01d53Sdrh   */
289892b01d53Sdrh   op = p->op;
2899b21e7c70Sdrh   pPrior = p->pPrior;
290092b01d53Sdrh   assert( pPrior->pOrderBy==0 );
29010acb7e48Sdrh   pOrderBy = p->pOrderBy;
290293a960a0Sdrh   assert( pOrderBy );
29030acb7e48Sdrh   nOrderBy = pOrderBy->nExpr;
290493a960a0Sdrh 
29050acb7e48Sdrh   /* For operators other than UNION ALL we have to make sure that
29060acb7e48Sdrh   ** the ORDER BY clause covers every term of the result set.  Add
29070acb7e48Sdrh   ** terms to the ORDER BY clause as necessary.
29080acb7e48Sdrh   */
29090acb7e48Sdrh   if( op!=TK_ALL ){
29100acb7e48Sdrh     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
29117d10d5a6Sdrh       struct ExprList_item *pItem;
29127d10d5a6Sdrh       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
2913c2acc4e4Sdrh         assert( pItem->u.x.iOrderByCol>0 );
2914c2acc4e4Sdrh         if( pItem->u.x.iOrderByCol==i ) break;
29150acb7e48Sdrh       }
29160acb7e48Sdrh       if( j==nOrderBy ){
2917b7916a78Sdrh         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
2918fad3039cSmistachkin         if( pNew==0 ) return SQLITE_NOMEM_BKPT;
29190acb7e48Sdrh         pNew->flags |= EP_IntValue;
292033e619fcSdrh         pNew->u.iValue = i;
292143606175Sdrh         p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
2922c2acc4e4Sdrh         if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
29230acb7e48Sdrh       }
29240acb7e48Sdrh     }
29250acb7e48Sdrh   }
29260acb7e48Sdrh 
29270acb7e48Sdrh   /* Compute the comparison permutation and keyinfo that is used with
292810c081adSdrh   ** the permutation used to determine if the next
29290acb7e48Sdrh   ** row of results comes from selectA or selectB.  Also add explicit
29300acb7e48Sdrh   ** collations to the ORDER BY clause terms so that when the subqueries
29310acb7e48Sdrh   ** to the right and the left are evaluated, they use the correct
29320acb7e48Sdrh   ** collation.
29330acb7e48Sdrh   */
2934575fad65Sdrh   aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
29350acb7e48Sdrh   if( aPermute ){
29367d10d5a6Sdrh     struct ExprList_item *pItem;
2937b1702026Sdrh     aPermute[0] = nOrderBy;
2938b1702026Sdrh     for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
29396736618aSdrh       assert( pItem->u.x.iOrderByCol>0 );
29402ec18a3cSdrh       assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
2941c2acc4e4Sdrh       aPermute[i] = pItem->u.x.iOrderByCol - 1;
29420acb7e48Sdrh     }
294353bed45eSdan     pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
29440acb7e48Sdrh   }else{
29450acb7e48Sdrh     pKeyMerge = 0;
29460acb7e48Sdrh   }
29470acb7e48Sdrh 
29480acb7e48Sdrh   /* Reattach the ORDER BY clause to the query.
29490acb7e48Sdrh   */
29500acb7e48Sdrh   p->pOrderBy = pOrderBy;
29516ab3a2ecSdanielk1977   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
29520acb7e48Sdrh 
29530acb7e48Sdrh   /* Allocate a range of temporary registers and the KeyInfo needed
29540acb7e48Sdrh   ** for the logic that removes duplicate result rows when the
29550acb7e48Sdrh   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
29560acb7e48Sdrh   */
29570acb7e48Sdrh   if( op==TK_ALL ){
29580acb7e48Sdrh     regPrev = 0;
29590acb7e48Sdrh   }else{
29600acb7e48Sdrh     int nExpr = p->pEList->nExpr;
29611c0dc825Sdrh     assert( nOrderBy>=nExpr || db->mallocFailed );
2962c8ac0d16Sdrh     regPrev = pParse->nMem+1;
2963c8ac0d16Sdrh     pParse->nMem += nExpr+1;
29640acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
2965ad124329Sdrh     pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
29660acb7e48Sdrh     if( pKeyDup ){
29672ec2fb22Sdrh       assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
29680acb7e48Sdrh       for(i=0; i<nExpr; i++){
29690acb7e48Sdrh         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
29700acb7e48Sdrh         pKeyDup->aSortOrder[i] = 0;
29710acb7e48Sdrh       }
29720acb7e48Sdrh     }
29730acb7e48Sdrh   }
297492b01d53Sdrh 
297592b01d53Sdrh   /* Separate the left and the right query from one another
297692b01d53Sdrh   */
297792b01d53Sdrh   p->pPrior = 0;
2978d227a291Sdrh   pPrior->pNext = 0;
29797d10d5a6Sdrh   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
29800acb7e48Sdrh   if( pPrior->pPrior==0 ){
29817d10d5a6Sdrh     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
29820acb7e48Sdrh   }
298392b01d53Sdrh 
298492b01d53Sdrh   /* Compute the limit registers */
298592b01d53Sdrh   computeLimitRegisters(pParse, p, labelEnd);
29860acb7e48Sdrh   if( p->iLimit && op==TK_ALL ){
298792b01d53Sdrh     regLimitA = ++pParse->nMem;
298892b01d53Sdrh     regLimitB = ++pParse->nMem;
298992b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
299092b01d53Sdrh                                   regLimitA);
299192b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
299292b01d53Sdrh   }else{
299392b01d53Sdrh     regLimitA = regLimitB = 0;
299492b01d53Sdrh   }
2995633e6d57Sdrh   sqlite3ExprDelete(db, p->pLimit);
29960acb7e48Sdrh   p->pLimit = 0;
2997633e6d57Sdrh   sqlite3ExprDelete(db, p->pOffset);
29980acb7e48Sdrh   p->pOffset = 0;
299992b01d53Sdrh 
3000b21e7c70Sdrh   regAddrA = ++pParse->nMem;
3001b21e7c70Sdrh   regAddrB = ++pParse->nMem;
3002b21e7c70Sdrh   regOutA = ++pParse->nMem;
3003b21e7c70Sdrh   regOutB = ++pParse->nMem;
3004b21e7c70Sdrh   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
3005b21e7c70Sdrh   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
3006b21e7c70Sdrh 
300792b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement to the
30080acb7e48Sdrh   ** left of the compound operator - the "A" select.
30090acb7e48Sdrh   */
3010ed71a839Sdrh   addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
3011728e0f91Sdrh   addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
3012ed71a839Sdrh   VdbeComment((v, "left SELECT"));
301392b01d53Sdrh   pPrior->iLimit = regLimitA;
30147f61e92cSdan   explainSetInteger(iSub1, pParse->iNextSelectId);
30157d10d5a6Sdrh   sqlite3Select(pParse, pPrior, &destA);
30162fade2f7Sdrh   sqlite3VdbeEndCoroutine(v, regAddrA);
3017728e0f91Sdrh   sqlite3VdbeJumpHere(v, addr1);
3018b21e7c70Sdrh 
301992b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement on
302092b01d53Sdrh   ** the right - the "B" select
302192b01d53Sdrh   */
3022ed71a839Sdrh   addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
3023728e0f91Sdrh   addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
3024ed71a839Sdrh   VdbeComment((v, "right SELECT"));
302592b01d53Sdrh   savedLimit = p->iLimit;
302692b01d53Sdrh   savedOffset = p->iOffset;
302792b01d53Sdrh   p->iLimit = regLimitB;
302892b01d53Sdrh   p->iOffset = 0;
30297f61e92cSdan   explainSetInteger(iSub2, pParse->iNextSelectId);
30307d10d5a6Sdrh   sqlite3Select(pParse, p, &destB);
303192b01d53Sdrh   p->iLimit = savedLimit;
303292b01d53Sdrh   p->iOffset = savedOffset;
30332fade2f7Sdrh   sqlite3VdbeEndCoroutine(v, regAddrB);
3034b21e7c70Sdrh 
303592b01d53Sdrh   /* Generate a subroutine that outputs the current row of the A
30360acb7e48Sdrh   ** select as the next output row of the compound select.
303792b01d53Sdrh   */
3038b21e7c70Sdrh   VdbeNoopComment((v, "Output routine for A"));
30390acb7e48Sdrh   addrOutA = generateOutputSubroutine(pParse,
30400acb7e48Sdrh                  p, &destA, pDest, regOutA,
30412ec2fb22Sdrh                  regPrev, pKeyDup, labelEnd);
3042b21e7c70Sdrh 
304392b01d53Sdrh   /* Generate a subroutine that outputs the current row of the B
30440acb7e48Sdrh   ** select as the next output row of the compound select.
304592b01d53Sdrh   */
30460acb7e48Sdrh   if( op==TK_ALL || op==TK_UNION ){
3047b21e7c70Sdrh     VdbeNoopComment((v, "Output routine for B"));
30480acb7e48Sdrh     addrOutB = generateOutputSubroutine(pParse,
30490acb7e48Sdrh                  p, &destB, pDest, regOutB,
30502ec2fb22Sdrh                  regPrev, pKeyDup, labelEnd);
30510acb7e48Sdrh   }
30522ec2fb22Sdrh   sqlite3KeyInfoUnref(pKeyDup);
3053b21e7c70Sdrh 
305492b01d53Sdrh   /* Generate a subroutine to run when the results from select A
305592b01d53Sdrh   ** are exhausted and only data in select B remains.
305692b01d53Sdrh   */
305792b01d53Sdrh   if( op==TK_EXCEPT || op==TK_INTERSECT ){
305881cf13ecSdrh     addrEofA_noB = addrEofA = labelEnd;
305992b01d53Sdrh   }else{
306081cf13ecSdrh     VdbeNoopComment((v, "eof-A subroutine"));
306181cf13ecSdrh     addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
306281cf13ecSdrh     addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
3063688852abSdrh                                      VdbeCoverage(v);
3064076e85f5Sdrh     sqlite3VdbeGoto(v, addrEofA);
3065c3489bbfSdrh     p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
3066b21e7c70Sdrh   }
3067b21e7c70Sdrh 
306892b01d53Sdrh   /* Generate a subroutine to run when the results from select B
306992b01d53Sdrh   ** are exhausted and only data in select A remains.
307092b01d53Sdrh   */
3071b21e7c70Sdrh   if( op==TK_INTERSECT ){
307292b01d53Sdrh     addrEofB = addrEofA;
307395aa47b1Sdrh     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
3074b21e7c70Sdrh   }else{
307592b01d53Sdrh     VdbeNoopComment((v, "eof-B subroutine"));
307681cf13ecSdrh     addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
3077688852abSdrh     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
3078076e85f5Sdrh     sqlite3VdbeGoto(v, addrEofB);
3079b21e7c70Sdrh   }
3080b21e7c70Sdrh 
308192b01d53Sdrh   /* Generate code to handle the case of A<B
308292b01d53Sdrh   */
3083b21e7c70Sdrh   VdbeNoopComment((v, "A-lt-B subroutine"));
30840acb7e48Sdrh   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
3085688852abSdrh   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
3086076e85f5Sdrh   sqlite3VdbeGoto(v, labelCmpr);
3087b21e7c70Sdrh 
308892b01d53Sdrh   /* Generate code to handle the case of A==B
308992b01d53Sdrh   */
3090b21e7c70Sdrh   if( op==TK_ALL ){
3091b21e7c70Sdrh     addrAeqB = addrAltB;
30920acb7e48Sdrh   }else if( op==TK_INTERSECT ){
30930acb7e48Sdrh     addrAeqB = addrAltB;
30940acb7e48Sdrh     addrAltB++;
309592b01d53Sdrh   }else{
3096b21e7c70Sdrh     VdbeNoopComment((v, "A-eq-B subroutine"));
30970acb7e48Sdrh     addrAeqB =
3098688852abSdrh     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
3099076e85f5Sdrh     sqlite3VdbeGoto(v, labelCmpr);
310092b01d53Sdrh   }
3101b21e7c70Sdrh 
310292b01d53Sdrh   /* Generate code to handle the case of A>B
310392b01d53Sdrh   */
3104b21e7c70Sdrh   VdbeNoopComment((v, "A-gt-B subroutine"));
3105b21e7c70Sdrh   addrAgtB = sqlite3VdbeCurrentAddr(v);
3106b21e7c70Sdrh   if( op==TK_ALL || op==TK_UNION ){
3107b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
310892b01d53Sdrh   }
3109688852abSdrh   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
3110076e85f5Sdrh   sqlite3VdbeGoto(v, labelCmpr);
3111b21e7c70Sdrh 
311292b01d53Sdrh   /* This code runs once to initialize everything.
311392b01d53Sdrh   */
3114728e0f91Sdrh   sqlite3VdbeJumpHere(v, addr1);
3115688852abSdrh   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
3116688852abSdrh   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
311792b01d53Sdrh 
311892b01d53Sdrh   /* Implement the main merge loop
311992b01d53Sdrh   */
312092b01d53Sdrh   sqlite3VdbeResolveLabel(v, labelCmpr);
31210acb7e48Sdrh   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
31222b596da8Sdrh   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
31232ec2fb22Sdrh                          (char*)pKeyMerge, P4_KEYINFO);
3124953f7611Sdrh   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
3125688852abSdrh   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
312692b01d53Sdrh 
312792b01d53Sdrh   /* Jump to the this point in order to terminate the query.
312892b01d53Sdrh   */
3129b21e7c70Sdrh   sqlite3VdbeResolveLabel(v, labelEnd);
3130b21e7c70Sdrh 
31310acb7e48Sdrh   /* Reassembly the compound query so that it will be freed correctly
31320acb7e48Sdrh   ** by the calling function */
31335e7ad508Sdanielk1977   if( p->pPrior ){
3134633e6d57Sdrh     sqlite3SelectDelete(db, p->pPrior);
31355e7ad508Sdanielk1977   }
31360acb7e48Sdrh   p->pPrior = pPrior;
3137d227a291Sdrh   pPrior->pNext = p;
313892b01d53Sdrh 
313992b01d53Sdrh   /*** TBD:  Insert subroutine calls to close cursors on incomplete
314092b01d53Sdrh   **** subqueries ****/
31417f61e92cSdan   explainComposite(pParse, p->op, iSub1, iSub2, 0);
31423dc4cc66Sdrh   return pParse->nErr!=0;
314392b01d53Sdrh }
3144de3e41e3Sdanielk1977 #endif
3145b21e7c70Sdrh 
31463514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
314746967de2Sdrh 
314846967de2Sdrh /* An instance of the SubstContext object describes an substitution edit
314946967de2Sdrh ** to be performed on a parse tree.
315046967de2Sdrh **
315146967de2Sdrh ** All references to columns in table iTable are to be replaced by corresponding
315246967de2Sdrh ** expressions in pEList.
315346967de2Sdrh */
315446967de2Sdrh typedef struct SubstContext {
315546967de2Sdrh   Parse *pParse;            /* The parsing context */
315646967de2Sdrh   int iTable;               /* Replace references to this table */
315731d6fd55Sdrh   int iNewTable;            /* New table number */
315831d6fd55Sdrh   int isLeftJoin;           /* Add TK_IF_NULL_ROW opcodes on each replacement */
315946967de2Sdrh   ExprList *pEList;         /* Replacement expressions */
316046967de2Sdrh } SubstContext;
316146967de2Sdrh 
316217435752Sdrh /* Forward Declarations */
316346967de2Sdrh static void substExprList(SubstContext*, ExprList*);
316446967de2Sdrh static void substSelect(SubstContext*, Select*, int);
316517435752Sdrh 
31662282792aSdrh /*
3167832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
31686a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
316984e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
31706a3ea0e6Sdrh ** unchanged.)
3171832508b7Sdrh **
3172832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
3173832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
3174832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
3175aca19e19Sdrh ** FORM clause entry is iTable.  This routine makes the necessary
3176832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
3177832508b7Sdrh ** of the subquery rather the result set of the subquery.
3178832508b7Sdrh */
3179b7916a78Sdrh static Expr *substExpr(
318046967de2Sdrh   SubstContext *pSubst,  /* Description of the substitution */
318146967de2Sdrh   Expr *pExpr            /* Expr in which substitution occurs */
318217435752Sdrh ){
3183b7916a78Sdrh   if( pExpr==0 ) return 0;
31843d240d21Sdrh   if( ExprHasProperty(pExpr, EP_FromJoin)
31853d240d21Sdrh    && pExpr->iRightJoinTable==pSubst->iTable
31863d240d21Sdrh   ){
3187399c7e21Sdrh     pExpr->iRightJoinTable = pSubst->iNewTable;
3188399c7e21Sdrh   }
318946967de2Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){
319050350a15Sdrh     if( pExpr->iColumn<0 ){
319150350a15Sdrh       pExpr->op = TK_NULL;
319250350a15Sdrh     }else{
3193832508b7Sdrh       Expr *pNew;
319446967de2Sdrh       Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
319531d6fd55Sdrh       Expr ifNullRow;
319646967de2Sdrh       assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
31976ab3a2ecSdanielk1977       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
319844c5604cSdan       if( sqlite3ExprIsVector(pCopy) ){
319946967de2Sdrh         sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
320044c5604cSdan       }else{
320146967de2Sdrh         sqlite3 *db = pSubst->pParse->db;
320231d6fd55Sdrh         if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
320331d6fd55Sdrh           memset(&ifNullRow, 0, sizeof(ifNullRow));
320431d6fd55Sdrh           ifNullRow.op = TK_IF_NULL_ROW;
320531d6fd55Sdrh           ifNullRow.pLeft = pCopy;
320631d6fd55Sdrh           ifNullRow.iTable = pSubst->iNewTable;
320731d6fd55Sdrh           pCopy = &ifNullRow;
320831d6fd55Sdrh         }
320944c5604cSdan         pNew = sqlite3ExprDup(db, pCopy, 0);
3210bd11a2acSdan         if( pNew && pSubst->isLeftJoin ){
3211bd11a2acSdan           ExprSetProperty(pNew, EP_CanBeNull);
3212bd11a2acSdan         }
3213bd11a2acSdan         if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
321492ddb3bdSdan           pNew->iRightJoinTable = pExpr->iRightJoinTable;
3215bd11a2acSdan           ExprSetProperty(pNew, EP_FromJoin);
321692ddb3bdSdan         }
3217b7916a78Sdrh         sqlite3ExprDelete(db, pExpr);
3218b7916a78Sdrh         pExpr = pNew;
321950350a15Sdrh       }
322044c5604cSdan     }
3221832508b7Sdrh   }else{
32227c1544e0Sdrh     if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
32237c1544e0Sdrh       pExpr->iTable = pSubst->iNewTable;
32247c1544e0Sdrh     }
322546967de2Sdrh     pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
322646967de2Sdrh     pExpr->pRight = substExpr(pSubst, pExpr->pRight);
32276ab3a2ecSdanielk1977     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
322846967de2Sdrh       substSelect(pSubst, pExpr->x.pSelect, 1);
32296ab3a2ecSdanielk1977     }else{
323046967de2Sdrh       substExprList(pSubst, pExpr->x.pList);
32316ab3a2ecSdanielk1977     }
3232832508b7Sdrh   }
3233b7916a78Sdrh   return pExpr;
3234832508b7Sdrh }
323517435752Sdrh static void substExprList(
323646967de2Sdrh   SubstContext *pSubst, /* Description of the substitution */
323746967de2Sdrh   ExprList *pList       /* List to scan and in which to make substitutes */
323817435752Sdrh ){
3239832508b7Sdrh   int i;
3240832508b7Sdrh   if( pList==0 ) return;
3241832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
324246967de2Sdrh     pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
3243832508b7Sdrh   }
3244832508b7Sdrh }
324517435752Sdrh static void substSelect(
324646967de2Sdrh   SubstContext *pSubst, /* Description of the substitution */
324717435752Sdrh   Select *p,            /* SELECT statement in which to make substitutions */
3248d12b6363Sdrh   int doPrior           /* Do substitutes on p->pPrior too */
324917435752Sdrh ){
3250588a9a1aSdrh   SrcList *pSrc;
3251588a9a1aSdrh   struct SrcList_item *pItem;
3252588a9a1aSdrh   int i;
3253b3bce662Sdanielk1977   if( !p ) return;
3254d12b6363Sdrh   do{
325546967de2Sdrh     substExprList(pSubst, p->pEList);
325646967de2Sdrh     substExprList(pSubst, p->pGroupBy);
325746967de2Sdrh     substExprList(pSubst, p->pOrderBy);
325846967de2Sdrh     p->pHaving = substExpr(pSubst, p->pHaving);
325946967de2Sdrh     p->pWhere = substExpr(pSubst, p->pWhere);
3260588a9a1aSdrh     pSrc = p->pSrc;
32612906490bSdrh     assert( pSrc!=0 );
3262588a9a1aSdrh     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
326346967de2Sdrh       substSelect(pSubst, pItem->pSelect, 1);
3264d12b6363Sdrh       if( pItem->fg.isTabFunc ){
326546967de2Sdrh         substExprList(pSubst, pItem->u1.pFuncArg);
3266588a9a1aSdrh       }
3267588a9a1aSdrh     }
3268d12b6363Sdrh   }while( doPrior && (p = p->pPrior)!=0 );
3269b3bce662Sdanielk1977 }
32703514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
3271832508b7Sdrh 
32723514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3273832508b7Sdrh /*
3274630d296cSdrh ** This routine attempts to flatten subqueries as a performance optimization.
3275630d296cSdrh ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
32761350b030Sdrh **
32771350b030Sdrh ** To understand the concept of flattening, consider the following
32781350b030Sdrh ** query:
32791350b030Sdrh **
32801350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
32811350b030Sdrh **
32821350b030Sdrh ** The default way of implementing this query is to execute the
32831350b030Sdrh ** subquery first and store the results in a temporary table, then
32841350b030Sdrh ** run the outer query on that temporary table.  This requires two
32851350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
32861350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
3287832508b7Sdrh ** optimized.
32881350b030Sdrh **
3289832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
32901350b030Sdrh ** a single flat select, like this:
32911350b030Sdrh **
32921350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
32931350b030Sdrh **
329460ec914cSpeter.d.reid ** The code generated for this simplification gives the same result
3295832508b7Sdrh ** but only has to scan the data once.  And because indices might
3296832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
3297832508b7Sdrh ** avoided.
32981350b030Sdrh **
3299832508b7Sdrh ** Flattening is only attempted if all of the following are true:
33001350b030Sdrh **
3301832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
33021350b030Sdrh **
3303885a5b03Sdrh **   (2)  The subquery is not an aggregate or (2a) the outer query is not a join
3304885a5b03Sdrh **        and (2b) the outer query does not use subqueries other than the one
3305885a5b03Sdrh **        FROM-clause subquery that is a candidate for flattening.  (2b is
3306885a5b03Sdrh **        due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
3307832508b7Sdrh **
330831d6fd55Sdrh **   (3)  The subquery is not the right operand of a LEFT JOIN
330946133d98Sdan **        or (a) the subquery is not itself a join and (b) the FROM clause
331046133d98Sdan **        of the subquery does not contain a virtual table and (c) the
331146133d98Sdan **        outer query is not an aggregate.
3312832508b7Sdrh **
331349ad330dSdan **   (4)  The subquery is not DISTINCT.
3314832508b7Sdrh **
331549ad330dSdan **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
331649ad330dSdan **        sub-queries that were excluded from this optimization. Restriction
331749ad330dSdan **        (4) has since been expanded to exclude all DISTINCT subqueries.
3318832508b7Sdrh **
3319832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
3320832508b7Sdrh **        DISTINCT.
3321832508b7Sdrh **
3322630d296cSdrh **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
332331d6fd55Sdrh **        A FROM clause, consider adding a FROM clause with the special
3324630d296cSdrh **        table sqlite_once that consists of a single row containing a
3325630d296cSdrh **        single NULL.
332608192d5fSdrh **
3327df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
3328df199a25Sdrh **
3329df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
3330df199a25Sdrh **        aggregates.
3331df199a25Sdrh **
33326092d2bcSdrh **  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
33336092d2bcSdrh **        accidently carried the comment forward until 2014-09-15.  Original
333438b4149cSdrh **        text: "The subquery does not use aggregates or the outer query
333538b4149cSdrh **        does not use LIMIT."
3336df199a25Sdrh **
3337174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
3338174b6195Sdrh **
33397b688edeSdrh **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
33402b300d5dSdrh **        a separate restriction deriving from ticket #350.
33413fc673e6Sdrh **
334249ad330dSdan **  (13)  The subquery and outer query do not both use LIMIT.
3343ac83963aSdrh **
334449ad330dSdan **  (14)  The subquery does not use OFFSET.
3345ac83963aSdrh **
3346ad91c6cdSdrh **  (15)  The outer query is not part of a compound select or the
3347f3913278Sdrh **        subquery does not have a LIMIT clause.
3348f3913278Sdrh **        (See ticket #2339 and ticket [02a8e81d44]).
3349ad91c6cdSdrh **
3350c52e355dSdrh **  (16)  The outer query is not an aggregate or the subquery does
3351c52e355dSdrh **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
3352c52e355dSdrh **        until we introduced the group_concat() function.
3353c52e355dSdrh **
3354f23329a2Sdanielk1977 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
33554914cf92Sdanielk1977 **        compound clause made up entirely of non-aggregate queries, and
3356f23329a2Sdanielk1977 **        the parent query:
3357f23329a2Sdanielk1977 **
3358f23329a2Sdanielk1977 **          * is not itself part of a compound select,
3359f23329a2Sdanielk1977 **          * is not an aggregate or DISTINCT query, and
3360630d296cSdrh **          * is not a join
3361f23329a2Sdanielk1977 **
33624914cf92Sdanielk1977 **        The parent and sub-query may contain WHERE clauses. Subject to
33634914cf92Sdanielk1977 **        rules (11), (13) and (14), they may also contain ORDER BY,
3364630d296cSdrh **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
3365630d296cSdrh **        operator other than UNION ALL because all the other compound
3366630d296cSdrh **        operators have an implied DISTINCT which is disallowed by
3367630d296cSdrh **        restriction (4).
3368f23329a2Sdanielk1977 **
336967c70142Sdan **        Also, each component of the sub-query must return the same number
337067c70142Sdan **        of result columns. This is actually a requirement for any compound
337167c70142Sdan **        SELECT statement, but all the code here does is make sure that no
337267c70142Sdan **        such (illegal) sub-query is flattened. The caller will detect the
337367c70142Sdan **        syntax error and return a detailed message.
337467c70142Sdan **
337549fc1f60Sdanielk1977 **  (18)  If the sub-query is a compound select, then all terms of the
337649fc1f60Sdanielk1977 **        ORDER by clause of the parent must be simple references to
337749fc1f60Sdanielk1977 **        columns of the sub-query.
337849fc1f60Sdanielk1977 **
3379229cf702Sdrh **  (19)  The subquery does not use LIMIT or the outer query does not
3380229cf702Sdrh **        have a WHERE clause.
3381229cf702Sdrh **
3382e8902a70Sdrh **  (20)  If the sub-query is a compound select, then it must not use
3383e8902a70Sdrh **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
3384e8902a70Sdrh **        somewhat by saying that the terms of the ORDER BY clause must
3385630d296cSdrh **        appear as unmodified result columns in the outer query.  But we
3386e8902a70Sdrh **        have other optimizations in mind to deal with that case.
3387e8902a70Sdrh **
3388a91491e5Sshaneh **  (21)  The subquery does not use LIMIT or the outer query is not
3389a91491e5Sshaneh **        DISTINCT.  (See ticket [752e1646fc]).
3390a91491e5Sshaneh **
33918290c2adSdan **  (22)  The subquery is not a recursive CTE.
33928290c2adSdan **
33938290c2adSdan **  (23)  The parent is not a recursive CTE, or the sub-query is not a
33948290c2adSdan **        compound query. This restriction is because transforming the
33958290c2adSdan **        parent to a compound query confuses the code that handles
33968290c2adSdan **        recursive queries in multiSelect().
33978290c2adSdan **
33989588ad95Sdrh **  (24)  The subquery is not an aggregate that uses the built-in min() or
33999588ad95Sdrh **        or max() functions.  (Without this restriction, a query like:
34009588ad95Sdrh **        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
34019588ad95Sdrh **        return the value X for which Y was maximal.)
34029588ad95Sdrh **
34038290c2adSdan **
3404832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
3405832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
3406832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
3407832508b7Sdrh **
3408665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
3409832508b7Sdrh ** If flattening is attempted this routine returns 1.
3410832508b7Sdrh **
3411832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
3412832508b7Sdrh ** the subquery before this routine runs.
34131350b030Sdrh */
34148c74a8caSdrh static int flattenSubquery(
3415524cc21eSdanielk1977   Parse *pParse,       /* Parsing context */
34168c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
34178c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
34188c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
34198c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
34208c74a8caSdrh ){
3421524cc21eSdanielk1977   const char *zSavedAuthContext = pParse->zAuthContext;
3422d12b6363Sdrh   Select *pParent;    /* Current UNION ALL term of the other query */
34230bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
3424f23329a2Sdanielk1977   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
3425ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
3426ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
34276a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
3428399c7e21Sdrh   int iNewParent = -1;/* Replacement table for iParent */
3429399c7e21Sdrh   int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
343091bb0eedSdrh   int i;              /* Loop counter */
343191bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
343291bb0eedSdrh   struct SrcList_item *pSubitem;   /* The subquery */
3433524cc21eSdanielk1977   sqlite3 *db = pParse->db;
34341350b030Sdrh 
3435832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
3436832508b7Sdrh   */
3437a78c22c4Sdrh   assert( p!=0 );
3438a78c22c4Sdrh   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
34397e5418e4Sdrh   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
3440832508b7Sdrh   pSrc = p->pSrc;
3441ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
344291bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
344349fc1f60Sdanielk1977   iParent = pSubitem->iCursor;
344491bb0eedSdrh   pSub = pSubitem->pSelect;
3445832508b7Sdrh   assert( pSub!=0 );
3446885a5b03Sdrh   if( subqueryIsAgg ){
3447885a5b03Sdrh     if( isAgg ) return 0;                                /* Restriction (1)   */
3448885a5b03Sdrh     if( pSrc->nSrc>1 ) return 0;                         /* Restriction (2a)  */
3449885a5b03Sdrh     if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
34502308ed38Sdrh      || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
34512308ed38Sdrh      || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
3452885a5b03Sdrh     ){
3453885a5b03Sdrh       return 0;                                          /* Restriction (2b)  */
3454885a5b03Sdrh     }
3455885a5b03Sdrh   }
3456885a5b03Sdrh 
3457832508b7Sdrh   pSubSrc = pSub->pSrc;
3458832508b7Sdrh   assert( pSubSrc );
3459ac83963aSdrh   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
346060ec914cSpeter.d.reid   ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
3461ac83963aSdrh   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
3462ac83963aSdrh   ** became arbitrary expressions, we were forced to add restrictions (13)
3463ac83963aSdrh   ** and (14). */
3464ac83963aSdrh   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
3465ac83963aSdrh   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
3466d227a291Sdrh   if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
3467ad91c6cdSdrh     return 0;                                            /* Restriction (15) */
3468ad91c6cdSdrh   }
3469ac83963aSdrh   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
347049ad330dSdan   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
347149ad330dSdan   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
347249ad330dSdan      return 0;         /* Restrictions (8)(9) */
3473df199a25Sdrh   }
34747d10d5a6Sdrh   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
34757d10d5a6Sdrh      return 0;         /* Restriction (6)  */
34767d10d5a6Sdrh   }
34777d10d5a6Sdrh   if( p->pOrderBy && pSub->pOrderBy ){
3478ac83963aSdrh      return 0;                                           /* Restriction (11) */
3479ac83963aSdrh   }
3480c52e355dSdrh   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
3481229cf702Sdrh   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
3482a91491e5Sshaneh   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
3483a91491e5Sshaneh      return 0;         /* Restriction (21) */
3484a91491e5Sshaneh   }
34859588ad95Sdrh   testcase( pSub->selFlags & SF_Recursive );
34869588ad95Sdrh   testcase( pSub->selFlags & SF_MinMaxAgg );
34879588ad95Sdrh   if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
34889588ad95Sdrh     return 0; /* Restrictions (22) and (24) */
34899588ad95Sdrh   }
34909588ad95Sdrh   if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
34919588ad95Sdrh     return 0; /* Restriction (23) */
34929588ad95Sdrh   }
3493832508b7Sdrh 
3494399c7e21Sdrh   /*
3495399c7e21Sdrh   ** If the subquery is the right operand of a LEFT JOIN, then the
3496399c7e21Sdrh   ** subquery may not be a join itself.  Example of why this is not allowed:
34978af4d3acSdrh   **
34988af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
34998af4d3acSdrh   **
35008af4d3acSdrh   ** If we flatten the above, we would get
35018af4d3acSdrh   **
35028af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
35038af4d3acSdrh   **
35048af4d3acSdrh   ** which is not at all the same thing.
35052b300d5dSdrh   **
35063c790f2aSdrh   ** If the subquery is the right operand of a LEFT JOIN, then the outer
35073c790f2aSdrh   ** query cannot be an aggregate.  This is an artifact of the way aggregates
3508bd11a2acSdan   ** are processed - there is no mechanism to determine if the LEFT JOIN
35093c790f2aSdrh   ** table should be all-NULL.
35103c790f2aSdrh   **
351131d6fd55Sdrh   ** See also tickets #306, #350, and #3300.
35123fc673e6Sdrh   */
35138a48b9c0Sdrh   if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
3514399c7e21Sdrh     isLeftJoin = 1;
351546133d98Sdan     if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){
351631d6fd55Sdrh       return 0; /* Restriction (3) */
3517399c7e21Sdrh     }
35183fc673e6Sdrh   }
3519dc6de479Sdrh #ifdef SQLITE_EXTRA_IFNULLROW
3520dc6de479Sdrh   else if( iFrom>0 && !isAgg ){
3521dc6de479Sdrh     /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
35223d240d21Sdrh     ** every reference to any result column from subquery in a join, even
35233d240d21Sdrh     ** though they are not necessary.  This will stress-test the OP_IfNullRow
35243d240d21Sdrh     ** opcode. */
3525dc6de479Sdrh     isLeftJoin = -1;
3526dc6de479Sdrh   }
3527dc6de479Sdrh #endif
35283fc673e6Sdrh 
3529f23329a2Sdanielk1977   /* Restriction 17: If the sub-query is a compound SELECT, then it must
3530f23329a2Sdanielk1977   ** use only the UNION ALL operator. And none of the simple select queries
3531f23329a2Sdanielk1977   ** that make up the compound SELECT are allowed to be aggregate or distinct
3532f23329a2Sdanielk1977   ** queries.
3533f23329a2Sdanielk1977   */
3534f23329a2Sdanielk1977   if( pSub->pPrior ){
3535e8902a70Sdrh     if( pSub->pOrderBy ){
3536e8902a70Sdrh       return 0;  /* Restriction 20 */
3537e8902a70Sdrh     }
3538e2f02bacSdrh     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
3539f23329a2Sdanielk1977       return 0;
3540f23329a2Sdanielk1977     }
3541f23329a2Sdanielk1977     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
3542ccfcbceaSdrh       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
3543ccfcbceaSdrh       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
35444b3ac73cSdrh       assert( pSub->pSrc!=0 );
35452ec18a3cSdrh       assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
35467d10d5a6Sdrh       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
354780b3c548Sdanielk1977        || (pSub1->pPrior && pSub1->op!=TK_ALL)
35484b3ac73cSdrh        || pSub1->pSrc->nSrc<1
354980b3c548Sdanielk1977       ){
3550f23329a2Sdanielk1977         return 0;
3551f23329a2Sdanielk1977       }
35524b3ac73cSdrh       testcase( pSub1->pSrc->nSrc>1 );
3553f23329a2Sdanielk1977     }
355449fc1f60Sdanielk1977 
355549fc1f60Sdanielk1977     /* Restriction 18. */
355649fc1f60Sdanielk1977     if( p->pOrderBy ){
355749fc1f60Sdanielk1977       int ii;
355849fc1f60Sdanielk1977       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
3559c2acc4e4Sdrh         if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
356049fc1f60Sdanielk1977       }
356149fc1f60Sdanielk1977     }
3562f23329a2Sdanielk1977   }
3563f23329a2Sdanielk1977 
35647d10d5a6Sdrh   /***** If we reach this point, flattening is permitted. *****/
3565eb9b884cSdrh   SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
3566eb9b884cSdrh                    pSub->zSelName, pSub, iFrom));
35677d10d5a6Sdrh 
35687d10d5a6Sdrh   /* Authorize the subquery */
3569524cc21eSdanielk1977   pParse->zAuthContext = pSubitem->zName;
3570a2acb0d7Sdrh   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
3571a2acb0d7Sdrh   testcase( i==SQLITE_DENY );
3572524cc21eSdanielk1977   pParse->zAuthContext = zSavedAuthContext;
3573524cc21eSdanielk1977 
35747d10d5a6Sdrh   /* If the sub-query is a compound SELECT statement, then (by restrictions
35757d10d5a6Sdrh   ** 17 and 18 above) it must be a UNION ALL and the parent query must
35767d10d5a6Sdrh   ** be of the form:
3577f23329a2Sdanielk1977   **
3578f23329a2Sdanielk1977   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
3579f23329a2Sdanielk1977   **
3580f23329a2Sdanielk1977   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
3581a78c22c4Sdrh   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
3582f23329a2Sdanielk1977   ** OFFSET clauses and joins them to the left-hand-side of the original
3583f23329a2Sdanielk1977   ** using UNION ALL operators. In this case N is the number of simple
3584f23329a2Sdanielk1977   ** select statements in the compound sub-query.
3585a78c22c4Sdrh   **
3586a78c22c4Sdrh   ** Example:
3587a78c22c4Sdrh   **
3588a78c22c4Sdrh   **     SELECT a+1 FROM (
3589a78c22c4Sdrh   **        SELECT x FROM tab
3590a78c22c4Sdrh   **        UNION ALL
3591a78c22c4Sdrh   **        SELECT y FROM tab
3592a78c22c4Sdrh   **        UNION ALL
3593a78c22c4Sdrh   **        SELECT abs(z*2) FROM tab2
3594a78c22c4Sdrh   **     ) WHERE a!=5 ORDER BY 1
3595a78c22c4Sdrh   **
3596a78c22c4Sdrh   ** Transformed into:
3597a78c22c4Sdrh   **
3598a78c22c4Sdrh   **     SELECT x+1 FROM tab WHERE x+1!=5
3599a78c22c4Sdrh   **     UNION ALL
3600a78c22c4Sdrh   **     SELECT y+1 FROM tab WHERE y+1!=5
3601a78c22c4Sdrh   **     UNION ALL
3602a78c22c4Sdrh   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
3603a78c22c4Sdrh   **     ORDER BY 1
3604a78c22c4Sdrh   **
3605a78c22c4Sdrh   ** We call this the "compound-subquery flattening".
3606f23329a2Sdanielk1977   */
3607f23329a2Sdanielk1977   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
3608f23329a2Sdanielk1977     Select *pNew;
3609f23329a2Sdanielk1977     ExprList *pOrderBy = p->pOrderBy;
36104b86ef1dSdanielk1977     Expr *pLimit = p->pLimit;
3611547180baSdrh     Expr *pOffset = p->pOffset;
3612f23329a2Sdanielk1977     Select *pPrior = p->pPrior;
3613f23329a2Sdanielk1977     p->pOrderBy = 0;
3614f23329a2Sdanielk1977     p->pSrc = 0;
3615f23329a2Sdanielk1977     p->pPrior = 0;
36164b86ef1dSdanielk1977     p->pLimit = 0;
3617547180baSdrh     p->pOffset = 0;
36186ab3a2ecSdanielk1977     pNew = sqlite3SelectDup(db, p, 0);
3619eb9b884cSdrh     sqlite3SelectSetName(pNew, pSub->zSelName);
3620547180baSdrh     p->pOffset = pOffset;
36214b86ef1dSdanielk1977     p->pLimit = pLimit;
3622a78c22c4Sdrh     p->pOrderBy = pOrderBy;
3623a78c22c4Sdrh     p->pSrc = pSrc;
3624a78c22c4Sdrh     p->op = TK_ALL;
3625a78c22c4Sdrh     if( pNew==0 ){
3626d227a291Sdrh       p->pPrior = pPrior;
3627a78c22c4Sdrh     }else{
3628a78c22c4Sdrh       pNew->pPrior = pPrior;
3629d227a291Sdrh       if( pPrior ) pPrior->pNext = pNew;
3630d227a291Sdrh       pNew->pNext = p;
3631a78c22c4Sdrh       p->pPrior = pNew;
3632eb9b884cSdrh       SELECTTRACE(2,pParse,p,
3633eb9b884cSdrh          ("compound-subquery flattener creates %s.%p as peer\n",
3634eb9b884cSdrh          pNew->zSelName, pNew));
3635d227a291Sdrh     }
3636a78c22c4Sdrh     if( db->mallocFailed ) return 1;
3637a78c22c4Sdrh   }
3638f23329a2Sdanielk1977 
36397d10d5a6Sdrh   /* Begin flattening the iFrom-th entry of the FROM clause
36407d10d5a6Sdrh   ** in the outer query.
3641832508b7Sdrh   */
3642f23329a2Sdanielk1977   pSub = pSub1 = pSubitem->pSelect;
3643c31c2eb8Sdrh 
3644a78c22c4Sdrh   /* Delete the transient table structure associated with the
3645a78c22c4Sdrh   ** subquery
3646a78c22c4Sdrh   */
3647a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zDatabase);
3648a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zName);
3649a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zAlias);
3650a78c22c4Sdrh   pSubitem->zDatabase = 0;
3651a78c22c4Sdrh   pSubitem->zName = 0;
3652a78c22c4Sdrh   pSubitem->zAlias = 0;
3653a78c22c4Sdrh   pSubitem->pSelect = 0;
3654a78c22c4Sdrh 
3655a78c22c4Sdrh   /* Defer deleting the Table object associated with the
3656a78c22c4Sdrh   ** subquery until code generation is
3657a78c22c4Sdrh   ** complete, since there may still exist Expr.pTab entries that
3658a78c22c4Sdrh   ** refer to the subquery even after flattening.  Ticket #3346.
3659ccfcbceaSdrh   **
3660ccfcbceaSdrh   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
3661a78c22c4Sdrh   */
3662ccfcbceaSdrh   if( ALWAYS(pSubitem->pTab!=0) ){
3663a78c22c4Sdrh     Table *pTabToDel = pSubitem->pTab;
366479df7782Sdrh     if( pTabToDel->nTabRef==1 ){
366565a7cd16Sdan       Parse *pToplevel = sqlite3ParseToplevel(pParse);
366665a7cd16Sdan       pTabToDel->pNextZombie = pToplevel->pZombieTab;
366765a7cd16Sdan       pToplevel->pZombieTab = pTabToDel;
3668a78c22c4Sdrh     }else{
366979df7782Sdrh       pTabToDel->nTabRef--;
3670a78c22c4Sdrh     }
3671a78c22c4Sdrh     pSubitem->pTab = 0;
3672a78c22c4Sdrh   }
3673a78c22c4Sdrh 
3674a78c22c4Sdrh   /* The following loop runs once for each term in a compound-subquery
3675a78c22c4Sdrh   ** flattening (as described above).  If we are doing a different kind
3676a78c22c4Sdrh   ** of flattening - a flattening other than a compound-subquery flattening -
3677a78c22c4Sdrh   ** then this loop only runs once.
3678a78c22c4Sdrh   **
3679a78c22c4Sdrh   ** This loop moves all of the FROM elements of the subquery into the
3680c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
3681c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
3682c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
3683c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
3684c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
3685c31c2eb8Sdrh   ** elements we are now copying in.
3686c31c2eb8Sdrh   */
3687a78c22c4Sdrh   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
3688a78c22c4Sdrh     int nSubSrc;
3689ea678832Sdrh     u8 jointype = 0;
3690a78c22c4Sdrh     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
3691a78c22c4Sdrh     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
3692a78c22c4Sdrh     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
3693588a9a1aSdrh 
3694a78c22c4Sdrh     if( pSrc ){
3695a78c22c4Sdrh       assert( pParent==p );  /* First time through the loop */
36968a48b9c0Sdrh       jointype = pSubitem->fg.jointype;
3697588a9a1aSdrh     }else{
3698a78c22c4Sdrh       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
3699a78c22c4Sdrh       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
3700cfa063b3Sdrh       if( pSrc==0 ){
3701a78c22c4Sdrh         assert( db->mallocFailed );
3702a78c22c4Sdrh         break;
3703cfa063b3Sdrh       }
3704c31c2eb8Sdrh     }
3705a78c22c4Sdrh 
3706a78c22c4Sdrh     /* The subquery uses a single slot of the FROM clause of the outer
3707a78c22c4Sdrh     ** query.  If the subquery has more than one element in its FROM clause,
3708a78c22c4Sdrh     ** then expand the outer query to make space for it to hold all elements
3709a78c22c4Sdrh     ** of the subquery.
3710a78c22c4Sdrh     **
3711a78c22c4Sdrh     ** Example:
3712a78c22c4Sdrh     **
3713a78c22c4Sdrh     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
3714a78c22c4Sdrh     **
3715a78c22c4Sdrh     ** The outer query has 3 slots in its FROM clause.  One slot of the
3716a78c22c4Sdrh     ** outer query (the middle slot) is used by the subquery.  The next
3717d12b6363Sdrh     ** block of code will expand the outer query FROM clause to 4 slots.
3718d12b6363Sdrh     ** The middle slot is expanded to two slots in order to make space
3719d12b6363Sdrh     ** for the two elements in the FROM clause of the subquery.
3720a78c22c4Sdrh     */
3721a78c22c4Sdrh     if( nSubSrc>1 ){
3722a78c22c4Sdrh       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
3723a78c22c4Sdrh       if( db->mallocFailed ){
3724a78c22c4Sdrh         break;
3725c31c2eb8Sdrh       }
3726c31c2eb8Sdrh     }
3727a78c22c4Sdrh 
3728a78c22c4Sdrh     /* Transfer the FROM clause terms from the subquery into the
3729a78c22c4Sdrh     ** outer query.
3730a78c22c4Sdrh     */
3731c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
3732c3a8402aSdrh       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
373320292310Sdrh       assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
3734c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
3735399c7e21Sdrh       iNewParent = pSubSrc->a[i].iCursor;
3736c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
3737c31c2eb8Sdrh     }
37388a48b9c0Sdrh     pSrc->a[iFrom].fg.jointype = jointype;
3739c31c2eb8Sdrh 
3740c31c2eb8Sdrh     /* Now begin substituting subquery result set expressions for
3741c31c2eb8Sdrh     ** references to the iParent in the outer query.
3742c31c2eb8Sdrh     **
3743c31c2eb8Sdrh     ** Example:
3744c31c2eb8Sdrh     **
3745c31c2eb8Sdrh     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
3746c31c2eb8Sdrh     **   \                     \_____________ subquery __________/          /
3747c31c2eb8Sdrh     **    \_____________________ outer query ______________________________/
3748c31c2eb8Sdrh     **
3749c31c2eb8Sdrh     ** We look at every expression in the outer query and every place we see
3750c31c2eb8Sdrh     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
3751c31c2eb8Sdrh     */
3752174b6195Sdrh     if( pSub->pOrderBy ){
37537c0a4720Sdan       /* At this point, any non-zero iOrderByCol values indicate that the
37547c0a4720Sdan       ** ORDER BY column expression is identical to the iOrderByCol'th
37557c0a4720Sdan       ** expression returned by SELECT statement pSub. Since these values
37567c0a4720Sdan       ** do not necessarily correspond to columns in SELECT statement pParent,
37577c0a4720Sdan       ** zero them before transfering the ORDER BY clause.
37587c0a4720Sdan       **
37597c0a4720Sdan       ** Not doing this may cause an error if a subsequent call to this
37607c0a4720Sdan       ** function attempts to flatten a compound sub-query into pParent
37617c0a4720Sdan       ** (the only way this can happen is if the compound sub-query is
37627c0a4720Sdan       ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
37637c0a4720Sdan       ExprList *pOrderBy = pSub->pOrderBy;
37647c0a4720Sdan       for(i=0; i<pOrderBy->nExpr; i++){
37657c0a4720Sdan         pOrderBy->a[i].u.x.iOrderByCol = 0;
37667c0a4720Sdan       }
3767f23329a2Sdanielk1977       assert( pParent->pOrderBy==0 );
37687c0a4720Sdan       assert( pSub->pPrior==0 );
37697c0a4720Sdan       pParent->pOrderBy = pOrderBy;
3770174b6195Sdrh       pSub->pOrderBy = 0;
3771174b6195Sdrh     }
37726ab3a2ecSdanielk1977     pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
3773dc6de479Sdrh     if( isLeftJoin>0 ){
3774399c7e21Sdrh       setJoinExpr(pWhere, iNewParent);
3775399c7e21Sdrh     }
3776832508b7Sdrh     if( subqueryIsAgg ){
3777f23329a2Sdanielk1977       assert( pParent->pHaving==0 );
3778f23329a2Sdanielk1977       pParent->pHaving = pParent->pWhere;
3779f23329a2Sdanielk1977       pParent->pWhere = pWhere;
37804c5ebee0Sdan       pParent->pHaving = sqlite3ExprAnd(db,
37814c5ebee0Sdan           sqlite3ExprDup(db, pSub->pHaving, 0), pParent->pHaving
37824c5ebee0Sdan       );
3783f23329a2Sdanielk1977       assert( pParent->pGroupBy==0 );
37846ab3a2ecSdanielk1977       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
3785832508b7Sdrh     }else{
37864c5ebee0Sdan       pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere);
3787832508b7Sdrh     }
3788c3becddbSdan     if( db->mallocFailed==0 ){
378946967de2Sdrh       SubstContext x;
379046967de2Sdrh       x.pParse = pParse;
379146967de2Sdrh       x.iTable = iParent;
3792399c7e21Sdrh       x.iNewTable = iNewParent;
379331d6fd55Sdrh       x.isLeftJoin = isLeftJoin;
379446967de2Sdrh       x.pEList = pSub->pEList;
379546967de2Sdrh       substSelect(&x, pParent, 0);
3796c3becddbSdan     }
3797c31c2eb8Sdrh 
3798c31c2eb8Sdrh     /* The flattened query is distinct if either the inner or the
3799c31c2eb8Sdrh     ** outer query is distinct.
3800c31c2eb8Sdrh     */
38017d10d5a6Sdrh     pParent->selFlags |= pSub->selFlags & SF_Distinct;
38028c74a8caSdrh 
3803a58fdfb1Sdanielk1977     /*
3804a58fdfb1Sdanielk1977     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
3805ac83963aSdrh     **
3806ac83963aSdrh     ** One is tempted to try to add a and b to combine the limits.  But this
3807ac83963aSdrh     ** does not work if either limit is negative.
3808a58fdfb1Sdanielk1977     */
3809a2dc3b1aSdanielk1977     if( pSub->pLimit ){
3810f23329a2Sdanielk1977       pParent->pLimit = pSub->pLimit;
3811a2dc3b1aSdanielk1977       pSub->pLimit = 0;
3812df199a25Sdrh     }
3813f23329a2Sdanielk1977   }
38148c74a8caSdrh 
3815c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
3816c31c2eb8Sdrh   ** success.
3817c31c2eb8Sdrh   */
3818633e6d57Sdrh   sqlite3SelectDelete(db, pSub1);
3819f23329a2Sdanielk1977 
3820c90713d3Sdrh #if SELECTTRACE_ENABLED
3821c90713d3Sdrh   if( sqlite3SelectTrace & 0x100 ){
3822bc8edba1Sdrh     SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
3823c90713d3Sdrh     sqlite3TreeViewSelect(0, p, 0);
3824c90713d3Sdrh   }
3825c90713d3Sdrh #endif
3826c90713d3Sdrh 
3827832508b7Sdrh   return 1;
38281350b030Sdrh }
38293514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
38301350b030Sdrh 
383169b72d5aSdrh 
383269b72d5aSdrh 
383369b72d5aSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
383469b72d5aSdrh /*
383569b72d5aSdrh ** Make copies of relevant WHERE clause terms of the outer query into
383669b72d5aSdrh ** the WHERE clause of subquery.  Example:
383769b72d5aSdrh **
383869b72d5aSdrh **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
383969b72d5aSdrh **
384069b72d5aSdrh ** Transformed into:
384169b72d5aSdrh **
384269b72d5aSdrh **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
384369b72d5aSdrh **     WHERE x=5 AND y=10;
384469b72d5aSdrh **
384569b72d5aSdrh ** The hope is that the terms added to the inner query will make it more
384669b72d5aSdrh ** efficient.
384769b72d5aSdrh **
384869b72d5aSdrh ** Do not attempt this optimization if:
384969b72d5aSdrh **
385069b72d5aSdrh **   (1) The inner query is an aggregate.  (In that case, we'd really want
385169b72d5aSdrh **       to copy the outer WHERE-clause terms onto the HAVING clause of the
385269b72d5aSdrh **       inner query.  But they probably won't help there so do not bother.)
385369b72d5aSdrh **
385469b72d5aSdrh **   (2) The inner query is the recursive part of a common table expression.
385569b72d5aSdrh **
385669b72d5aSdrh **   (3) The inner query has a LIMIT clause (since the changes to the WHERE
385769b72d5aSdrh **       close would change the meaning of the LIMIT).
385869b72d5aSdrh **
385969b72d5aSdrh **   (4) The inner query is the right operand of a LEFT JOIN.  (The caller
386069b72d5aSdrh **       enforces this restriction since this routine does not have enough
386169b72d5aSdrh **       information to know.)
386269b72d5aSdrh **
386338978dd4Sdrh **   (5) The WHERE clause expression originates in the ON or USING clause
386438978dd4Sdrh **       of a LEFT JOIN.
386538978dd4Sdrh **
386669b72d5aSdrh ** Return 0 if no changes are made and non-zero if one or more WHERE clause
386769b72d5aSdrh ** terms are duplicated into the subquery.
386869b72d5aSdrh */
386969b72d5aSdrh static int pushDownWhereTerms(
387044c5604cSdan   Parse *pParse,        /* Parse context (for malloc() and error reporting) */
387169b72d5aSdrh   Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
387269b72d5aSdrh   Expr *pWhere,         /* The WHERE clause of the outer query */
387369b72d5aSdrh   int iCursor           /* Cursor number of the subquery */
387469b72d5aSdrh ){
387569b72d5aSdrh   Expr *pNew;
387669b72d5aSdrh   int nChng = 0;
3877b1ec87afSdrh   Select *pX;           /* For looping over compound SELECTs in pSubq */
387869b72d5aSdrh   if( pWhere==0 ) return 0;
3879b1ec87afSdrh   for(pX=pSubq; pX; pX=pX->pPrior){
3880b1ec87afSdrh     if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
3881b1ec87afSdrh       testcase( pX->selFlags & SF_Aggregate );
3882b1ec87afSdrh       testcase( pX->selFlags & SF_Recursive );
3883b1ec87afSdrh       testcase( pX!=pSubq );
388469b72d5aSdrh       return 0; /* restrictions (1) and (2) */
388569b72d5aSdrh     }
3886b1ec87afSdrh   }
388769b72d5aSdrh   if( pSubq->pLimit!=0 ){
388869b72d5aSdrh     return 0; /* restriction (3) */
388969b72d5aSdrh   }
389069b72d5aSdrh   while( pWhere->op==TK_AND ){
389144c5604cSdan     nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, iCursor);
389269b72d5aSdrh     pWhere = pWhere->pLeft;
389369b72d5aSdrh   }
389438978dd4Sdrh   if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
389569b72d5aSdrh   if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
389669b72d5aSdrh     nChng++;
389769b72d5aSdrh     while( pSubq ){
389846967de2Sdrh       SubstContext x;
389944c5604cSdan       pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
390046967de2Sdrh       x.pParse = pParse;
390146967de2Sdrh       x.iTable = iCursor;
3902399c7e21Sdrh       x.iNewTable = iCursor;
390331d6fd55Sdrh       x.isLeftJoin = 0;
390446967de2Sdrh       x.pEList = pSubq->pEList;
390546967de2Sdrh       pNew = substExpr(&x, pNew);
390644c5604cSdan       pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew);
390769b72d5aSdrh       pSubq = pSubq->pPrior;
390869b72d5aSdrh     }
390969b72d5aSdrh   }
391069b72d5aSdrh   return nChng;
391169b72d5aSdrh }
391269b72d5aSdrh #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
391369b72d5aSdrh 
39141350b030Sdrh /*
39154ac391fcSdan ** Based on the contents of the AggInfo structure indicated by the first
39164ac391fcSdan ** argument, this function checks if the following are true:
3917a9d1ccb9Sdanielk1977 **
39184ac391fcSdan **    * the query contains just a single aggregate function,
39194ac391fcSdan **    * the aggregate function is either min() or max(), and
39204ac391fcSdan **    * the argument to the aggregate function is a column value.
3921738bdcfbSdanielk1977 **
39224ac391fcSdan ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
39234ac391fcSdan ** is returned as appropriate. Also, *ppMinMax is set to point to the
39244ac391fcSdan ** list of arguments passed to the aggregate before returning.
39254ac391fcSdan **
39264ac391fcSdan ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
39274ac391fcSdan ** WHERE_ORDERBY_NORMAL is returned.
3928a9d1ccb9Sdanielk1977 */
39294ac391fcSdan static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
39304ac391fcSdan   int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
3931a9d1ccb9Sdanielk1977 
39324ac391fcSdan   *ppMinMax = 0;
39334ac391fcSdan   if( pAggInfo->nFunc==1 ){
39344ac391fcSdan     Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
39354ac391fcSdan     ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
39364ac391fcSdan 
39374ac391fcSdan     assert( pExpr->op==TK_AGG_FUNCTION );
39384ac391fcSdan     if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
39394ac391fcSdan       const char *zFunc = pExpr->u.zToken;
39404ac391fcSdan       if( sqlite3StrICmp(zFunc, "min")==0 ){
39414ac391fcSdan         eRet = WHERE_ORDERBY_MIN;
39424ac391fcSdan         *ppMinMax = pEList;
39434ac391fcSdan       }else if( sqlite3StrICmp(zFunc, "max")==0 ){
39444ac391fcSdan         eRet = WHERE_ORDERBY_MAX;
39454ac391fcSdan         *ppMinMax = pEList;
3946a9d1ccb9Sdanielk1977       }
39474ac391fcSdan     }
39484ac391fcSdan   }
39494ac391fcSdan 
39504ac391fcSdan   assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
39514ac391fcSdan   return eRet;
3952a9d1ccb9Sdanielk1977 }
3953a9d1ccb9Sdanielk1977 
3954a9d1ccb9Sdanielk1977 /*
3955a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query.
395660ec914cSpeter.d.reid ** The second argument is the associated aggregate-info object. This
3957a5533162Sdanielk1977 ** function tests if the SELECT is of the form:
3958a5533162Sdanielk1977 **
3959a5533162Sdanielk1977 **   SELECT count(*) FROM <tbl>
3960a5533162Sdanielk1977 **
3961a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query
3962a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing
3963a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned.
3964a5533162Sdanielk1977 */
3965a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
3966a5533162Sdanielk1977   Table *pTab;
3967a5533162Sdanielk1977   Expr *pExpr;
3968a5533162Sdanielk1977 
3969a5533162Sdanielk1977   assert( !p->pGroupBy );
3970a5533162Sdanielk1977 
39717a895a80Sdanielk1977   if( p->pWhere || p->pEList->nExpr!=1
3972a5533162Sdanielk1977    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
3973a5533162Sdanielk1977   ){
3974a5533162Sdanielk1977     return 0;
3975a5533162Sdanielk1977   }
3976a5533162Sdanielk1977   pTab = p->pSrc->a[0].pTab;
3977a5533162Sdanielk1977   pExpr = p->pEList->a[0].pExpr;
397802f33725Sdanielk1977   assert( pTab && !pTab->pSelect && pExpr );
397902f33725Sdanielk1977 
398002f33725Sdanielk1977   if( IsVirtual(pTab) ) return 0;
3981a5533162Sdanielk1977   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
3982fb0a6081Sdrh   if( NEVER(pAggInfo->nFunc==0) ) return 0;
3983d36e1041Sdrh   if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
3984a5533162Sdanielk1977   if( pExpr->flags&EP_Distinct ) return 0;
3985a5533162Sdanielk1977 
3986a5533162Sdanielk1977   return pTab;
3987a5533162Sdanielk1977 }
3988a5533162Sdanielk1977 
3989a5533162Sdanielk1977 /*
3990b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an
3991b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there
3992b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return
3993b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
3994b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK.
3995b1c685b0Sdanielk1977 */
3996b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
39978a48b9c0Sdrh   if( pFrom->pTab && pFrom->fg.isIndexedBy ){
3998b1c685b0Sdanielk1977     Table *pTab = pFrom->pTab;
39998a48b9c0Sdrh     char *zIndexedBy = pFrom->u1.zIndexedBy;
4000b1c685b0Sdanielk1977     Index *pIdx;
4001b1c685b0Sdanielk1977     for(pIdx=pTab->pIndex;
4002d62fbb50Sdrh         pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
4003b1c685b0Sdanielk1977         pIdx=pIdx->pNext
4004b1c685b0Sdanielk1977     );
4005b1c685b0Sdanielk1977     if( !pIdx ){
4006d62fbb50Sdrh       sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
40071db95106Sdan       pParse->checkSchema = 1;
4008b1c685b0Sdanielk1977       return SQLITE_ERROR;
4009b1c685b0Sdanielk1977     }
40108a48b9c0Sdrh     pFrom->pIBIndex = pIdx;
4011b1c685b0Sdanielk1977   }
4012b1c685b0Sdanielk1977   return SQLITE_OK;
4013b1c685b0Sdanielk1977 }
4014c01b7306Sdrh /*
4015c01b7306Sdrh ** Detect compound SELECT statements that use an ORDER BY clause with
4016c01b7306Sdrh ** an alternative collating sequence.
4017c01b7306Sdrh **
4018c01b7306Sdrh **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
4019c01b7306Sdrh **
4020c01b7306Sdrh ** These are rewritten as a subquery:
4021c01b7306Sdrh **
4022c01b7306Sdrh **    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
4023c01b7306Sdrh **     ORDER BY ... COLLATE ...
4024c01b7306Sdrh **
4025c01b7306Sdrh ** This transformation is necessary because the multiSelectOrderBy() routine
4026c01b7306Sdrh ** above that generates the code for a compound SELECT with an ORDER BY clause
4027c01b7306Sdrh ** uses a merge algorithm that requires the same collating sequence on the
4028c01b7306Sdrh ** result columns as on the ORDER BY clause.  See ticket
4029c01b7306Sdrh ** http://www.sqlite.org/src/info/6709574d2a
4030c01b7306Sdrh **
4031c01b7306Sdrh ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
4032c01b7306Sdrh ** The UNION ALL operator works fine with multiSelectOrderBy() even when
4033c01b7306Sdrh ** there are COLLATE terms in the ORDER BY.
4034c01b7306Sdrh */
4035c01b7306Sdrh static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
4036c01b7306Sdrh   int i;
4037c01b7306Sdrh   Select *pNew;
4038c01b7306Sdrh   Select *pX;
4039c01b7306Sdrh   sqlite3 *db;
4040c01b7306Sdrh   struct ExprList_item *a;
4041c01b7306Sdrh   SrcList *pNewSrc;
4042c01b7306Sdrh   Parse *pParse;
4043c01b7306Sdrh   Token dummy;
4044c01b7306Sdrh 
4045c01b7306Sdrh   if( p->pPrior==0 ) return WRC_Continue;
4046c01b7306Sdrh   if( p->pOrderBy==0 ) return WRC_Continue;
4047c01b7306Sdrh   for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
4048c01b7306Sdrh   if( pX==0 ) return WRC_Continue;
4049c01b7306Sdrh   a = p->pOrderBy->a;
4050c01b7306Sdrh   for(i=p->pOrderBy->nExpr-1; i>=0; i--){
4051c01b7306Sdrh     if( a[i].pExpr->flags & EP_Collate ) break;
4052c01b7306Sdrh   }
4053c01b7306Sdrh   if( i<0 ) return WRC_Continue;
4054c01b7306Sdrh 
4055c01b7306Sdrh   /* If we reach this point, that means the transformation is required. */
4056c01b7306Sdrh 
4057c01b7306Sdrh   pParse = pWalker->pParse;
4058c01b7306Sdrh   db = pParse->db;
4059c01b7306Sdrh   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
4060c01b7306Sdrh   if( pNew==0 ) return WRC_Abort;
4061c01b7306Sdrh   memset(&dummy, 0, sizeof(dummy));
4062c01b7306Sdrh   pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
4063c01b7306Sdrh   if( pNewSrc==0 ) return WRC_Abort;
4064c01b7306Sdrh   *pNew = *p;
4065c01b7306Sdrh   p->pSrc = pNewSrc;
40661a1d3cd2Sdrh   p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
4067c01b7306Sdrh   p->op = TK_SELECT;
4068c01b7306Sdrh   p->pWhere = 0;
4069c01b7306Sdrh   pNew->pGroupBy = 0;
4070c01b7306Sdrh   pNew->pHaving = 0;
4071c01b7306Sdrh   pNew->pOrderBy = 0;
4072c01b7306Sdrh   p->pPrior = 0;
40738af9ad95Sdrh   p->pNext = 0;
4074f932f714Sdrh   p->pWith = 0;
40758af9ad95Sdrh   p->selFlags &= ~SF_Compound;
4076b33c50f2Sdan   assert( (p->selFlags & SF_Converted)==0 );
4077b33c50f2Sdan   p->selFlags |= SF_Converted;
4078a6e3a8c9Sdrh   assert( pNew->pPrior!=0 );
4079a6e3a8c9Sdrh   pNew->pPrior->pNext = pNew;
4080c01b7306Sdrh   pNew->pLimit = 0;
4081c01b7306Sdrh   pNew->pOffset = 0;
4082c01b7306Sdrh   return WRC_Continue;
4083c01b7306Sdrh }
4084b1c685b0Sdanielk1977 
408520292310Sdrh /*
408620292310Sdrh ** Check to see if the FROM clause term pFrom has table-valued function
408720292310Sdrh ** arguments.  If it does, leave an error message in pParse and return
408820292310Sdrh ** non-zero, since pFrom is not allowed to be a table-valued function.
408920292310Sdrh */
409020292310Sdrh static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
409120292310Sdrh   if( pFrom->fg.isTabFunc ){
409220292310Sdrh     sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
409320292310Sdrh     return 1;
409420292310Sdrh   }
409520292310Sdrh   return 0;
409620292310Sdrh }
409720292310Sdrh 
4098eede6a53Sdan #ifndef SQLITE_OMIT_CTE
4099eede6a53Sdan /*
4100eede6a53Sdan ** Argument pWith (which may be NULL) points to a linked list of nested
4101eede6a53Sdan ** WITH contexts, from inner to outermost. If the table identified by
4102eede6a53Sdan ** FROM clause element pItem is really a common-table-expression (CTE)
4103eede6a53Sdan ** then return a pointer to the CTE definition for that table. Otherwise
4104eede6a53Sdan ** return NULL.
410598f45e53Sdan **
410698f45e53Sdan ** If a non-NULL value is returned, set *ppContext to point to the With
410798f45e53Sdan ** object that the returned CTE belongs to.
410860c1a2f0Sdrh */
410998f45e53Sdan static struct Cte *searchWith(
41102476a6f2Sdrh   With *pWith,                    /* Current innermost WITH clause */
411198f45e53Sdan   struct SrcList_item *pItem,     /* FROM clause element to resolve */
411298f45e53Sdan   With **ppContext                /* OUT: WITH clause return value belongs to */
411398f45e53Sdan ){
41147b19f252Sdrh   const char *zName;
41157b19f252Sdrh   if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
4116eede6a53Sdan     With *p;
4117eede6a53Sdan     for(p=pWith; p; p=p->pOuter){
41184e9119d9Sdan       int i;
4119eede6a53Sdan       for(i=0; i<p->nCte; i++){
4120eede6a53Sdan         if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
412198f45e53Sdan           *ppContext = p;
4122eede6a53Sdan           return &p->a[i];
41234e9119d9Sdan         }
41244e9119d9Sdan       }
41254e9119d9Sdan     }
41264e9119d9Sdan   }
41274e9119d9Sdan   return 0;
41284e9119d9Sdan }
41294e9119d9Sdan 
4130c49832c2Sdrh /* The code generator maintains a stack of active WITH clauses
4131c49832c2Sdrh ** with the inner-most WITH clause being at the top of the stack.
4132c49832c2Sdrh **
4133b290f117Sdan ** This routine pushes the WITH clause passed as the second argument
4134b290f117Sdan ** onto the top of the stack. If argument bFree is true, then this
4135b290f117Sdan ** WITH clause will never be popped from the stack. In this case it
4136b290f117Sdan ** should be freed along with the Parse object. In other cases, when
4137b290f117Sdan ** bFree==0, the With object will be freed along with the SELECT
4138b290f117Sdan ** statement with which it is associated.
4139c49832c2Sdrh */
4140b290f117Sdan void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
41416e772266Sdrh   assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
41424e9119d9Sdan   if( pWith ){
41432476a6f2Sdrh     assert( pParse->pWith!=pWith );
41444e9119d9Sdan     pWith->pOuter = pParse->pWith;
41454e9119d9Sdan     pParse->pWith = pWith;
41466e772266Sdrh     if( bFree ) pParse->pWithToFree = pWith;
41474e9119d9Sdan   }
41484e9119d9Sdan }
41494e9119d9Sdan 
4150eede6a53Sdan /*
4151eede6a53Sdan ** This function checks if argument pFrom refers to a CTE declared by
4152eede6a53Sdan ** a WITH clause on the stack currently maintained by the parser. And,
4153eede6a53Sdan ** if currently processing a CTE expression, if it is a recursive
4154eede6a53Sdan ** reference to the current CTE.
4155eede6a53Sdan **
4156eede6a53Sdan ** If pFrom falls into either of the two categories above, pFrom->pTab
4157eede6a53Sdan ** and other fields are populated accordingly. The caller should check
4158eede6a53Sdan ** (pFrom->pTab!=0) to determine whether or not a successful match
4159eede6a53Sdan ** was found.
4160eede6a53Sdan **
4161eede6a53Sdan ** Whether or not a match is found, SQLITE_OK is returned if no error
4162eede6a53Sdan ** occurs. If an error does occur, an error message is stored in the
4163eede6a53Sdan ** parser and some error code other than SQLITE_OK returned.
4164eede6a53Sdan */
41658ce7184bSdan static int withExpand(
41668ce7184bSdan   Walker *pWalker,
4167eede6a53Sdan   struct SrcList_item *pFrom
41688ce7184bSdan ){
41698ce7184bSdan   Parse *pParse = pWalker->pParse;
41708ce7184bSdan   sqlite3 *db = pParse->db;
417198f45e53Sdan   struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
417298f45e53Sdan   With *pWith;                    /* WITH clause that pCte belongs to */
41738ce7184bSdan 
41748ce7184bSdan   assert( pFrom->pTab==0 );
41758ce7184bSdan 
417698f45e53Sdan   pCte = searchWith(pParse->pWith, pFrom, &pWith);
4177eae73fbfSdan   if( pCte ){
417898f45e53Sdan     Table *pTab;
41798ce7184bSdan     ExprList *pEList;
41808ce7184bSdan     Select *pSel;
418160e7068dSdan     Select *pLeft;                /* Left-most SELECT statement */
4182f2655fe8Sdan     int bMayRecursive;            /* True if compound joined by UNION [ALL] */
418398f45e53Sdan     With *pSavedWith;             /* Initial value of pParse->pWith */
4184f2655fe8Sdan 
41850576bc59Sdrh     /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
4186f2655fe8Sdan     ** recursive reference to CTE pCte. Leave an error in pParse and return
41870576bc59Sdrh     ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
4188f2655fe8Sdan     ** In this case, proceed.  */
41890576bc59Sdrh     if( pCte->zCteErr ){
41900576bc59Sdrh       sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
419198f45e53Sdan       return SQLITE_ERROR;
4192f2655fe8Sdan     }
419320292310Sdrh     if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
41948ce7184bSdan 
4195c25e2ebcSdrh     assert( pFrom->pTab==0 );
41968ce7184bSdan     pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
41978ce7184bSdan     if( pTab==0 ) return WRC_Abort;
419879df7782Sdrh     pTab->nTabRef = 1;
41992d4dc5fcSdan     pTab->zName = sqlite3DbStrDup(db, pCte->zName);
42008ce7184bSdan     pTab->iPKey = -1;
4201cfc9df76Sdan     pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
4202fccda8a1Sdrh     pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
42038ce7184bSdan     pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
4204fad3039cSmistachkin     if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
42058ce7184bSdan     assert( pFrom->pSelect );
42068ce7184bSdan 
4207eae73fbfSdan     /* Check if this is a recursive CTE. */
42088ce7184bSdan     pSel = pFrom->pSelect;
4209f2655fe8Sdan     bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
4210f2655fe8Sdan     if( bMayRecursive ){
4211eae73fbfSdan       int i;
4212eae73fbfSdan       SrcList *pSrc = pFrom->pSelect->pSrc;
4213eae73fbfSdan       for(i=0; i<pSrc->nSrc; i++){
4214eae73fbfSdan         struct SrcList_item *pItem = &pSrc->a[i];
4215eae73fbfSdan         if( pItem->zDatabase==0
4216eae73fbfSdan          && pItem->zName!=0
4217eae73fbfSdan          && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
4218eae73fbfSdan           ){
4219eae73fbfSdan           pItem->pTab = pTab;
42208a48b9c0Sdrh           pItem->fg.isRecursive = 1;
422179df7782Sdrh           pTab->nTabRef++;
4222eae73fbfSdan           pSel->selFlags |= SF_Recursive;
42238ce7184bSdan         }
4224eae73fbfSdan       }
4225eae73fbfSdan     }
4226eae73fbfSdan 
4227eae73fbfSdan     /* Only one recursive reference is permitted. */
422879df7782Sdrh     if( pTab->nTabRef>2 ){
4229eae73fbfSdan       sqlite3ErrorMsg(
4230727a99f1Sdrh           pParse, "multiple references to recursive table: %s", pCte->zName
4231eae73fbfSdan       );
423298f45e53Sdan       return SQLITE_ERROR;
4233eae73fbfSdan     }
42343d240d21Sdrh     assert( pTab->nTabRef==1 ||
42353d240d21Sdrh             ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
4236eae73fbfSdan 
42370576bc59Sdrh     pCte->zCteErr = "circular reference: %s";
423898f45e53Sdan     pSavedWith = pParse->pWith;
423998f45e53Sdan     pParse->pWith = pWith;
4240067cd837Sdan     if( bMayRecursive ){
4241067cd837Sdan       Select *pPrior = pSel->pPrior;
4242067cd837Sdan       assert( pPrior->pWith==0 );
4243067cd837Sdan       pPrior->pWith = pSel->pWith;
4244067cd837Sdan       sqlite3WalkSelect(pWalker, pPrior);
4245067cd837Sdan       pPrior->pWith = 0;
4246067cd837Sdan     }else{
4247067cd837Sdan       sqlite3WalkSelect(pWalker, pSel);
4248067cd837Sdan     }
42496e772266Sdrh     pParse->pWith = pWith;
42508ce7184bSdan 
42518ce7184bSdan     for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
42528ce7184bSdan     pEList = pLeft->pEList;
425360e7068dSdan     if( pCte->pCols ){
42548f9d0b2bSdrh       if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
4255727a99f1Sdrh         sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
425660e7068dSdan             pCte->zName, pEList->nExpr, pCte->pCols->nExpr
425760e7068dSdan         );
425898f45e53Sdan         pParse->pWith = pSavedWith;
425998f45e53Sdan         return SQLITE_ERROR;
42608ce7184bSdan       }
426160e7068dSdan       pEList = pCte->pCols;
426260e7068dSdan     }
42638ce7184bSdan 
42648981b904Sdrh     sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
4265f2655fe8Sdan     if( bMayRecursive ){
4266f2655fe8Sdan       if( pSel->selFlags & SF_Recursive ){
42670576bc59Sdrh         pCte->zCteErr = "multiple recursive references: %s";
4268f2655fe8Sdan       }else{
42690576bc59Sdrh         pCte->zCteErr = "recursive reference in a subquery: %s";
4270f2655fe8Sdan       }
4271f2655fe8Sdan       sqlite3WalkSelect(pWalker, pSel);
4272f2655fe8Sdan     }
42730576bc59Sdrh     pCte->zCteErr = 0;
427498f45e53Sdan     pParse->pWith = pSavedWith;
42758ce7184bSdan   }
42768ce7184bSdan 
42778ce7184bSdan   return SQLITE_OK;
42788ce7184bSdan }
4279eede6a53Sdan #endif
42804e9119d9Sdan 
4281b290f117Sdan #ifndef SQLITE_OMIT_CTE
428271856944Sdan /*
428371856944Sdan ** If the SELECT passed as the second argument has an associated WITH
428471856944Sdan ** clause, pop it from the stack stored as part of the Parse object.
428571856944Sdan **
428671856944Sdan ** This function is used as the xSelectCallback2() callback by
428771856944Sdan ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
428871856944Sdan ** names and other FROM clause elements.
428971856944Sdan */
4290b290f117Sdan static void selectPopWith(Walker *pWalker, Select *p){
4291b290f117Sdan   Parse *pParse = pWalker->pParse;
4292067cd837Sdan   if( pParse->pWith && p->pPrior==0 ){
4293d227a291Sdrh     With *pWith = findRightmost(p)->pWith;
4294d227a291Sdrh     if( pWith!=0 ){
4295d227a291Sdrh       assert( pParse->pWith==pWith );
4296d227a291Sdrh       pParse->pWith = pWith->pOuter;
4297b290f117Sdan     }
4298b290f117Sdan   }
4299067cd837Sdan }
4300b290f117Sdan #else
4301b290f117Sdan #define selectPopWith 0
4302b290f117Sdan #endif
4303b290f117Sdan 
4304b1c685b0Sdanielk1977 /*
43057d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement.
43067d10d5a6Sdrh ** "Expanding" means to do the following:
43077d10d5a6Sdrh **
43087d10d5a6Sdrh **    (1)  Make sure VDBE cursor numbers have been assigned to every
43097d10d5a6Sdrh **         element of the FROM clause.
43107d10d5a6Sdrh **
43117d10d5a6Sdrh **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
43127d10d5a6Sdrh **         defines FROM clause.  When views appear in the FROM clause,
43137d10d5a6Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
43147d10d5a6Sdrh **         that implements the view.  A copy is made of the view's SELECT
43157d10d5a6Sdrh **         statement so that we can freely modify or delete that statement
431660ec914cSpeter.d.reid **         without worrying about messing up the persistent representation
43177d10d5a6Sdrh **         of the view.
43187d10d5a6Sdrh **
431960ec914cSpeter.d.reid **    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
43207d10d5a6Sdrh **         on joins and the ON and USING clause of joins.
43217d10d5a6Sdrh **
43227d10d5a6Sdrh **    (4)  Scan the list of columns in the result set (pEList) looking
43237d10d5a6Sdrh **         for instances of the "*" operator or the TABLE.* operator.
43247d10d5a6Sdrh **         If found, expand each "*" to be every column in every table
43257d10d5a6Sdrh **         and TABLE.* to be every column in TABLE.
43267d10d5a6Sdrh **
4327b3bce662Sdanielk1977 */
43287d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){
43297d10d5a6Sdrh   Parse *pParse = pWalker->pParse;
43307d10d5a6Sdrh   int i, j, k;
43317d10d5a6Sdrh   SrcList *pTabList;
43327d10d5a6Sdrh   ExprList *pEList;
43337d10d5a6Sdrh   struct SrcList_item *pFrom;
43347d10d5a6Sdrh   sqlite3 *db = pParse->db;
43353e3f1a5bSdrh   Expr *pE, *pRight, *pExpr;
4336785097daSdrh   u16 selFlags = p->selFlags;
43377d10d5a6Sdrh 
4338785097daSdrh   p->selFlags |= SF_Expanded;
43397d10d5a6Sdrh   if( db->mallocFailed  ){
43407d10d5a6Sdrh     return WRC_Abort;
43417d10d5a6Sdrh   }
4342785097daSdrh   if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
43437d10d5a6Sdrh     return WRC_Prune;
43447d10d5a6Sdrh   }
43457d10d5a6Sdrh   pTabList = p->pSrc;
43467d10d5a6Sdrh   pEList = p->pEList;
4347067cd837Sdan   if( p->pWith ){
4348067cd837Sdan     sqlite3WithPush(pParse, p->pWith, 0);
43493afd2b4dSdrh   }
43507d10d5a6Sdrh 
43517d10d5a6Sdrh   /* Make sure cursor numbers have been assigned to all entries in
43527d10d5a6Sdrh   ** the FROM clause of the SELECT statement.
43537d10d5a6Sdrh   */
43547d10d5a6Sdrh   sqlite3SrcListAssignCursors(pParse, pTabList);
43557d10d5a6Sdrh 
43567d10d5a6Sdrh   /* Look up every table named in the FROM clause of the select.  If
43577d10d5a6Sdrh   ** an entry of the FROM clause is a subquery instead of a table or view,
43587d10d5a6Sdrh   ** then create a transient table structure to describe the subquery.
43597d10d5a6Sdrh   */
43607d10d5a6Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
43617d10d5a6Sdrh     Table *pTab;
4362e2b7d7a0Sdrh     assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
43638a48b9c0Sdrh     if( pFrom->fg.isRecursive ) continue;
4364e2b7d7a0Sdrh     assert( pFrom->pTab==0 );
43654e9119d9Sdan #ifndef SQLITE_OMIT_CTE
4366eede6a53Sdan     if( withExpand(pWalker, pFrom) ) return WRC_Abort;
4367eede6a53Sdan     if( pFrom->pTab ) {} else
43684e9119d9Sdan #endif
43697d10d5a6Sdrh     if( pFrom->zName==0 ){
43707d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
43717d10d5a6Sdrh       Select *pSel = pFrom->pSelect;
43727d10d5a6Sdrh       /* A sub-query in the FROM clause of a SELECT */
43737d10d5a6Sdrh       assert( pSel!=0 );
43747d10d5a6Sdrh       assert( pFrom->pTab==0 );
43752b8c5a00Sdrh       if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
43767d10d5a6Sdrh       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
43777d10d5a6Sdrh       if( pTab==0 ) return WRC_Abort;
437879df7782Sdrh       pTab->nTabRef = 1;
4379*23768298Sdrh       if( pFrom->zAlias ){
4380*23768298Sdrh         pTab->zName = sqlite3DbStrDup(db, pFrom->zAlias);
4381*23768298Sdrh       }else{
4382*23768298Sdrh         pTab->zName = sqlite3MPrintf(db, "subquery_%p", (void*)pTab);
4383*23768298Sdrh       }
43847d10d5a6Sdrh       while( pSel->pPrior ){ pSel = pSel->pPrior; }
43858981b904Sdrh       sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
43867d10d5a6Sdrh       pTab->iPKey = -1;
4387cfc9df76Sdan       pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
43887d10d5a6Sdrh       pTab->tabFlags |= TF_Ephemeral;
43897d10d5a6Sdrh #endif
43907d10d5a6Sdrh     }else{
43917d10d5a6Sdrh       /* An ordinary table or view name in the FROM clause */
43927d10d5a6Sdrh       assert( pFrom->pTab==0 );
439341fb5cd1Sdan       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
43947d10d5a6Sdrh       if( pTab==0 ) return WRC_Abort;
439579df7782Sdrh       if( pTab->nTabRef>=0xffff ){
4396d2a56238Sdrh         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
4397d2a56238Sdrh            pTab->zName);
4398d2a56238Sdrh         pFrom->pTab = 0;
4399d2a56238Sdrh         return WRC_Abort;
4400d2a56238Sdrh       }
440179df7782Sdrh       pTab->nTabRef++;
440220292310Sdrh       if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
440320292310Sdrh         return WRC_Abort;
440420292310Sdrh       }
44057d10d5a6Sdrh #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
440620292310Sdrh       if( IsVirtual(pTab) || pTab->pSelect ){
4407bfad7be7Sdrh         i16 nCol;
44087d10d5a6Sdrh         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
440943152cf8Sdrh         assert( pFrom->pSelect==0 );
44106ab3a2ecSdanielk1977         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
4411eb9b884cSdrh         sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
4412bfad7be7Sdrh         nCol = pTab->nCol;
4413bfad7be7Sdrh         pTab->nCol = -1;
44147d10d5a6Sdrh         sqlite3WalkSelect(pWalker, pFrom->pSelect);
4415bfad7be7Sdrh         pTab->nCol = nCol;
44167d10d5a6Sdrh       }
44177d10d5a6Sdrh #endif
44187d10d5a6Sdrh     }
441985574e31Sdanielk1977 
442085574e31Sdanielk1977     /* Locate the index named by the INDEXED BY clause, if any. */
4421b1c685b0Sdanielk1977     if( sqlite3IndexedByLookup(pParse, pFrom) ){
442285574e31Sdanielk1977       return WRC_Abort;
442385574e31Sdanielk1977     }
44247d10d5a6Sdrh   }
44257d10d5a6Sdrh 
44267d10d5a6Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
44277d10d5a6Sdrh   */
44287d10d5a6Sdrh   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
44297d10d5a6Sdrh     return WRC_Abort;
44307d10d5a6Sdrh   }
44317d10d5a6Sdrh 
44327d10d5a6Sdrh   /* For every "*" that occurs in the column list, insert the names of
44337d10d5a6Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
44347d10d5a6Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
44351a1d3cd2Sdrh   ** with the TK_ASTERISK operator for each "*" that it found in the column
44361a1d3cd2Sdrh   ** list.  The following code just has to locate the TK_ASTERISK
44371a1d3cd2Sdrh   ** expressions and expand each one to the list of all columns in
44381a1d3cd2Sdrh   ** all tables.
44397d10d5a6Sdrh   **
44407d10d5a6Sdrh   ** The first loop just checks to see if there are any "*" operators
44417d10d5a6Sdrh   ** that need expanding.
44427d10d5a6Sdrh   */
44437d10d5a6Sdrh   for(k=0; k<pEList->nExpr; k++){
44443e3f1a5bSdrh     pE = pEList->a[k].pExpr;
44451a1d3cd2Sdrh     if( pE->op==TK_ASTERISK ) break;
444643152cf8Sdrh     assert( pE->op!=TK_DOT || pE->pRight!=0 );
444743152cf8Sdrh     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
44481a1d3cd2Sdrh     if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
44497d10d5a6Sdrh   }
44507d10d5a6Sdrh   if( k<pEList->nExpr ){
44517d10d5a6Sdrh     /*
44527d10d5a6Sdrh     ** If we get here it means the result set contains one or more "*"
44537d10d5a6Sdrh     ** operators that need to be expanded.  Loop through each expression
44547d10d5a6Sdrh     ** in the result set and expand them one by one.
44557d10d5a6Sdrh     */
44567d10d5a6Sdrh     struct ExprList_item *a = pEList->a;
44577d10d5a6Sdrh     ExprList *pNew = 0;
44587d10d5a6Sdrh     int flags = pParse->db->flags;
44597d10d5a6Sdrh     int longNames = (flags & SQLITE_FullColNames)!=0
446038b384a0Sdrh                       && (flags & SQLITE_ShortColNames)==0;
446138b384a0Sdrh 
44627d10d5a6Sdrh     for(k=0; k<pEList->nExpr; k++){
44633e3f1a5bSdrh       pE = a[k].pExpr;
44643e3f1a5bSdrh       pRight = pE->pRight;
44653e3f1a5bSdrh       assert( pE->op!=TK_DOT || pRight!=0 );
44661a1d3cd2Sdrh       if( pE->op!=TK_ASTERISK
44671a1d3cd2Sdrh        && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
44681a1d3cd2Sdrh       ){
44697d10d5a6Sdrh         /* This particular expression does not need to be expanded.
44707d10d5a6Sdrh         */
4471b7916a78Sdrh         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
44727d10d5a6Sdrh         if( pNew ){
44737d10d5a6Sdrh           pNew->a[pNew->nExpr-1].zName = a[k].zName;
4474b7916a78Sdrh           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
4475b7916a78Sdrh           a[k].zName = 0;
4476b7916a78Sdrh           a[k].zSpan = 0;
44777d10d5a6Sdrh         }
44787d10d5a6Sdrh         a[k].pExpr = 0;
44797d10d5a6Sdrh       }else{
44807d10d5a6Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
44817d10d5a6Sdrh         ** expanded. */
44827d10d5a6Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
44833e3f1a5bSdrh         char *zTName = 0;       /* text of name of TABLE */
448443152cf8Sdrh         if( pE->op==TK_DOT ){
448543152cf8Sdrh           assert( pE->pLeft!=0 );
448633e619fcSdrh           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
448733e619fcSdrh           zTName = pE->pLeft->u.zToken;
44887d10d5a6Sdrh         }
44897d10d5a6Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
44907d10d5a6Sdrh           Table *pTab = pFrom->pTab;
44913e3f1a5bSdrh           Select *pSub = pFrom->pSelect;
44927d10d5a6Sdrh           char *zTabName = pFrom->zAlias;
44933e3f1a5bSdrh           const char *zSchemaName = 0;
4494c75e09c7Sdrh           int iDb;
449543152cf8Sdrh           if( zTabName==0 ){
44967d10d5a6Sdrh             zTabName = pTab->zName;
44977d10d5a6Sdrh           }
44987d10d5a6Sdrh           if( db->mallocFailed ) break;
44993e3f1a5bSdrh           if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
45003e3f1a5bSdrh             pSub = 0;
45017d10d5a6Sdrh             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
45027d10d5a6Sdrh               continue;
45037d10d5a6Sdrh             }
45043e3f1a5bSdrh             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
450569c33826Sdrh             zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
45063e3f1a5bSdrh           }
45077d10d5a6Sdrh           for(j=0; j<pTab->nCol; j++){
45087d10d5a6Sdrh             char *zName = pTab->aCol[j].zName;
4509b7916a78Sdrh             char *zColname;  /* The computed column name */
4510b7916a78Sdrh             char *zToFree;   /* Malloced string that needs to be freed */
4511b7916a78Sdrh             Token sColname;  /* Computed column name as a token */
45127d10d5a6Sdrh 
4513c75e09c7Sdrh             assert( zName );
45143e3f1a5bSdrh             if( zTName && pSub
45153e3f1a5bSdrh              && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
45163e3f1a5bSdrh             ){
45173e3f1a5bSdrh               continue;
45183e3f1a5bSdrh             }
45193e3f1a5bSdrh 
452080090f92Sdrh             /* If a column is marked as 'hidden', omit it from the expanded
452180090f92Sdrh             ** result-set list unless the SELECT has the SF_IncludeHidden
452280090f92Sdrh             ** bit set.
45237d10d5a6Sdrh             */
452480090f92Sdrh             if( (p->selFlags & SF_IncludeHidden)==0
452580090f92Sdrh              && IsHiddenColumn(&pTab->aCol[j])
452680090f92Sdrh             ){
45277d10d5a6Sdrh               continue;
45287d10d5a6Sdrh             }
45293e3f1a5bSdrh             tableSeen = 1;
45307d10d5a6Sdrh 
4531da55c48aSdrh             if( i>0 && zTName==0 ){
45328a48b9c0Sdrh               if( (pFrom->fg.jointype & JT_NATURAL)!=0
45332179b434Sdrh                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
45342179b434Sdrh               ){
45357d10d5a6Sdrh                 /* In a NATURAL join, omit the join columns from the
45362179b434Sdrh                 ** table to the right of the join */
45377d10d5a6Sdrh                 continue;
45387d10d5a6Sdrh               }
45392179b434Sdrh               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
45407d10d5a6Sdrh                 /* In a join with a USING clause, omit columns in the
45417d10d5a6Sdrh                 ** using clause from the table on the right. */
45427d10d5a6Sdrh                 continue;
45437d10d5a6Sdrh               }
45447d10d5a6Sdrh             }
4545b7916a78Sdrh             pRight = sqlite3Expr(db, TK_ID, zName);
4546b7916a78Sdrh             zColname = zName;
4547b7916a78Sdrh             zToFree = 0;
45487d10d5a6Sdrh             if( longNames || pTabList->nSrc>1 ){
4549b7916a78Sdrh               Expr *pLeft;
4550b7916a78Sdrh               pLeft = sqlite3Expr(db, TK_ID, zTabName);
4551abfd35eaSdrh               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
455238b384a0Sdrh               if( zSchemaName ){
4553c75e09c7Sdrh                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
4554abfd35eaSdrh                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
4555c75e09c7Sdrh               }
4556b7916a78Sdrh               if( longNames ){
4557b7916a78Sdrh                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
4558b7916a78Sdrh                 zToFree = zColname;
4559b7916a78Sdrh               }
45607d10d5a6Sdrh             }else{
45617d10d5a6Sdrh               pExpr = pRight;
45627d10d5a6Sdrh             }
4563b7916a78Sdrh             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
456440aced5cSdrh             sqlite3TokenInit(&sColname, zColname);
4565b7916a78Sdrh             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
45668f25d18bSdrh             if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
45673e3f1a5bSdrh               struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
45683e3f1a5bSdrh               if( pSub ){
45693e3f1a5bSdrh                 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
4570c75e09c7Sdrh                 testcase( pX->zSpan==0 );
45713e3f1a5bSdrh               }else{
45723e3f1a5bSdrh                 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
45733e3f1a5bSdrh                                            zSchemaName, zTabName, zColname);
4574c75e09c7Sdrh                 testcase( pX->zSpan==0 );
45753e3f1a5bSdrh               }
45763e3f1a5bSdrh               pX->bSpanIsTab = 1;
45778f25d18bSdrh             }
4578b7916a78Sdrh             sqlite3DbFree(db, zToFree);
45797d10d5a6Sdrh           }
45807d10d5a6Sdrh         }
45817d10d5a6Sdrh         if( !tableSeen ){
45827d10d5a6Sdrh           if( zTName ){
45837d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
45847d10d5a6Sdrh           }else{
45857d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no tables specified");
45867d10d5a6Sdrh           }
45877d10d5a6Sdrh         }
45887d10d5a6Sdrh       }
45897d10d5a6Sdrh     }
45907d10d5a6Sdrh     sqlite3ExprListDelete(db, pEList);
45917d10d5a6Sdrh     p->pEList = pNew;
45927d10d5a6Sdrh   }
45937d10d5a6Sdrh #if SQLITE_MAX_COLUMN
45947d10d5a6Sdrh   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
45957d10d5a6Sdrh     sqlite3ErrorMsg(pParse, "too many columns in result set");
45968836cbbcSdan     return WRC_Abort;
45977d10d5a6Sdrh   }
45987d10d5a6Sdrh #endif
45997d10d5a6Sdrh   return WRC_Continue;
46007d10d5a6Sdrh }
46017d10d5a6Sdrh 
46027d10d5a6Sdrh /*
46037d10d5a6Sdrh ** No-op routine for the parse-tree walker.
46047d10d5a6Sdrh **
46057d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees
46067d10d5a6Sdrh ** are walked without any actions being taken at each node.  Presumably,
46077d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then
46087d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every
46097d10d5a6Sdrh ** subquery in the parser tree.
46107d10d5a6Sdrh */
46115b88bc4bSdrh int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
461262c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
46137d10d5a6Sdrh   return WRC_Continue;
46147d10d5a6Sdrh }
46157d10d5a6Sdrh 
46167d10d5a6Sdrh /*
4617979dd1beSdrh ** No-op routine for the parse-tree walker for SELECT statements.
4618979dd1beSdrh ** subquery in the parser tree.
4619979dd1beSdrh */
4620979dd1beSdrh int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
4621979dd1beSdrh   UNUSED_PARAMETER2(NotUsed, NotUsed2);
4622979dd1beSdrh   return WRC_Continue;
4623979dd1beSdrh }
4624979dd1beSdrh 
4625979dd1beSdrh #if SQLITE_DEBUG
4626979dd1beSdrh /*
4627979dd1beSdrh ** Always assert.  This xSelectCallback2 implementation proves that the
4628979dd1beSdrh ** xSelectCallback2 is never invoked.
4629979dd1beSdrh */
4630979dd1beSdrh void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
4631979dd1beSdrh   UNUSED_PARAMETER2(NotUsed, NotUsed2);
4632979dd1beSdrh   assert( 0 );
4633979dd1beSdrh }
4634979dd1beSdrh #endif
4635979dd1beSdrh /*
46367d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries.
46377d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT
46387d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above.
46397d10d5a6Sdrh **
46407d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a
46417d10d5a6Sdrh ** SELECT statement.  The SELECT statement must be expanded before
46427d10d5a6Sdrh ** name resolution is performed.
46437d10d5a6Sdrh **
46447d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse.
46457d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr
46467d10d5a6Sdrh ** and/or pParse->db->mallocFailed.
46477d10d5a6Sdrh */
46487d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
46497d10d5a6Sdrh   Walker w;
46505b88bc4bSdrh   w.xExprCallback = sqlite3ExprWalkNoop;
46517d10d5a6Sdrh   w.pParse = pParse;
4652d58d3278Sdrh   if( pParse->hasCompound ){
4653d58d3278Sdrh     w.xSelectCallback = convertCompoundSelectToSubquery;
4654979dd1beSdrh     w.xSelectCallback2 = 0;
46557d10d5a6Sdrh     sqlite3WalkSelect(&w, pSelect);
4656d58d3278Sdrh   }
4657c01b7306Sdrh   w.xSelectCallback = selectExpander;
4658b290f117Sdan   w.xSelectCallback2 = selectPopWith;
4659c01b7306Sdrh   sqlite3WalkSelect(&w, pSelect);
46607d10d5a6Sdrh }
46617d10d5a6Sdrh 
46627d10d5a6Sdrh 
46637d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
46647d10d5a6Sdrh /*
46657d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
46667d10d5a6Sdrh ** interface.
46677d10d5a6Sdrh **
46687d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl
46697d10d5a6Sdrh ** information to the Table structure that represents the result set
46707d10d5a6Sdrh ** of that subquery.
46717d10d5a6Sdrh **
46727d10d5a6Sdrh ** The Table structure that represents the result set was constructed
46737d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted
46747d10d5a6Sdrh ** at that point because identifiers had not yet been resolved.  This
46757d10d5a6Sdrh ** routine is called after identifier resolution.
46767d10d5a6Sdrh */
4677b290f117Sdan static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
46787d10d5a6Sdrh   Parse *pParse;
46797d10d5a6Sdrh   int i;
46807d10d5a6Sdrh   SrcList *pTabList;
46817d10d5a6Sdrh   struct SrcList_item *pFrom;
46827d10d5a6Sdrh 
46839d8b3072Sdrh   assert( p->selFlags & SF_Resolved );
4684e2b7d7a0Sdrh   assert( (p->selFlags & SF_HasTypeInfo)==0 );
46857d10d5a6Sdrh   p->selFlags |= SF_HasTypeInfo;
46867d10d5a6Sdrh   pParse = pWalker->pParse;
46877d10d5a6Sdrh   pTabList = p->pSrc;
46887d10d5a6Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
46897d10d5a6Sdrh     Table *pTab = pFrom->pTab;
4690e2b7d7a0Sdrh     assert( pTab!=0 );
4691e2b7d7a0Sdrh     if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
46927d10d5a6Sdrh       /* A sub-query in the FROM clause of a SELECT */
46937d10d5a6Sdrh       Select *pSel = pFrom->pSelect;
46948ce7184bSdan       if( pSel ){
46957d10d5a6Sdrh         while( pSel->pPrior ) pSel = pSel->pPrior;
4696ed06a131Sdrh         sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
46977d10d5a6Sdrh       }
46987d10d5a6Sdrh     }
46995a29d9cbSdrh   }
47008ce7184bSdan }
47017d10d5a6Sdrh #endif
47027d10d5a6Sdrh 
47037d10d5a6Sdrh 
47047d10d5a6Sdrh /*
47057d10d5a6Sdrh ** This routine adds datatype and collating sequence information to
47067d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a
47077d10d5a6Sdrh ** SELECT statement.
47087d10d5a6Sdrh **
47097d10d5a6Sdrh ** Use this routine after name resolution.
47107d10d5a6Sdrh */
47117d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
47127d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
47137d10d5a6Sdrh   Walker w;
4714979dd1beSdrh   w.xSelectCallback = sqlite3SelectWalkNoop;
4715b290f117Sdan   w.xSelectCallback2 = selectAddSubqueryTypeInfo;
47165b88bc4bSdrh   w.xExprCallback = sqlite3ExprWalkNoop;
47177d10d5a6Sdrh   w.pParse = pParse;
47187d10d5a6Sdrh   sqlite3WalkSelect(&w, pSelect);
47197d10d5a6Sdrh #endif
47207d10d5a6Sdrh }
47217d10d5a6Sdrh 
47227d10d5a6Sdrh 
47237d10d5a6Sdrh /*
4724030796dfSdrh ** This routine sets up a SELECT statement for processing.  The
47257d10d5a6Sdrh ** following is accomplished:
47267d10d5a6Sdrh **
47277d10d5a6Sdrh **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
47287d10d5a6Sdrh **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
47297d10d5a6Sdrh **     *  ON and USING clauses are shifted into WHERE statements
47307d10d5a6Sdrh **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
47317d10d5a6Sdrh **     *  Identifiers in expression are matched to tables.
47327d10d5a6Sdrh **
47337d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT.
47347d10d5a6Sdrh */
47357d10d5a6Sdrh void sqlite3SelectPrep(
4736b3bce662Sdanielk1977   Parse *pParse,         /* The parser context */
4737b3bce662Sdanielk1977   Select *p,             /* The SELECT statement being coded. */
47387d10d5a6Sdrh   NameContext *pOuterNC  /* Name context for container */
4739b3bce662Sdanielk1977 ){
47407d10d5a6Sdrh   sqlite3 *db;
474143152cf8Sdrh   if( NEVER(p==0) ) return;
47427d10d5a6Sdrh   db = pParse->db;
4743785097daSdrh   if( db->mallocFailed ) return;
47447d10d5a6Sdrh   if( p->selFlags & SF_HasTypeInfo ) return;
47457d10d5a6Sdrh   sqlite3SelectExpand(pParse, p);
47467d10d5a6Sdrh   if( pParse->nErr || db->mallocFailed ) return;
47477d10d5a6Sdrh   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
47487d10d5a6Sdrh   if( pParse->nErr || db->mallocFailed ) return;
47497d10d5a6Sdrh   sqlite3SelectAddTypeInfo(pParse, p);
4750f6bbe022Sdrh }
4751b3bce662Sdanielk1977 
4752b3bce662Sdanielk1977 /*
475313449892Sdrh ** Reset the aggregate accumulator.
475413449892Sdrh **
475513449892Sdrh ** The aggregate accumulator is a set of memory cells that hold
475613449892Sdrh ** intermediate results while calculating an aggregate.  This
4757030796dfSdrh ** routine generates code that stores NULLs in all of those memory
4758030796dfSdrh ** cells.
4759b3bce662Sdanielk1977 */
476013449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
476113449892Sdrh   Vdbe *v = pParse->pVdbe;
476213449892Sdrh   int i;
4763c99130fdSdrh   struct AggInfo_func *pFunc;
47647e61d18eSdrh   int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
47657e61d18eSdrh   if( nReg==0 ) return;
47667e61d18eSdrh #ifdef SQLITE_DEBUG
47677e61d18eSdrh   /* Verify that all AggInfo registers are within the range specified by
47687e61d18eSdrh   ** AggInfo.mnReg..AggInfo.mxReg */
47697e61d18eSdrh   assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
477013449892Sdrh   for(i=0; i<pAggInfo->nColumn; i++){
47717e61d18eSdrh     assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
47727e61d18eSdrh          && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
477313449892Sdrh   }
47747e61d18eSdrh   for(i=0; i<pAggInfo->nFunc; i++){
47757e61d18eSdrh     assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
47767e61d18eSdrh          && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
47777e61d18eSdrh   }
47787e61d18eSdrh #endif
47797e61d18eSdrh   sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
4780c99130fdSdrh   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
4781c99130fdSdrh     if( pFunc->iDistinct>=0 ){
4782c99130fdSdrh       Expr *pE = pFunc->pExpr;
47836ab3a2ecSdanielk1977       assert( !ExprHasProperty(pE, EP_xIsSelect) );
47846ab3a2ecSdanielk1977       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
47850daa002cSdrh         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
47860daa002cSdrh            "argument");
4787c99130fdSdrh         pFunc->iDistinct = -1;
4788c99130fdSdrh       }else{
4789079a3072Sdrh         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
479066a5167bSdrh         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
47912ec2fb22Sdrh                           (char*)pKeyInfo, P4_KEYINFO);
4792c99130fdSdrh       }
4793c99130fdSdrh     }
479413449892Sdrh   }
4795b3bce662Sdanielk1977 }
4796b3bce662Sdanielk1977 
4797b3bce662Sdanielk1977 /*
479813449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function
479913449892Sdrh ** in the AggInfo structure.
4800b3bce662Sdanielk1977 */
480113449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
480213449892Sdrh   Vdbe *v = pParse->pVdbe;
480313449892Sdrh   int i;
480413449892Sdrh   struct AggInfo_func *pF;
480513449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
48066ab3a2ecSdanielk1977     ExprList *pList = pF->pExpr->x.pList;
48076ab3a2ecSdanielk1977     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
48082700acaaSdrh     sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
48092700acaaSdrh     sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
4810b3bce662Sdanielk1977   }
481113449892Sdrh }
481213449892Sdrh 
481313449892Sdrh /*
481413449892Sdrh ** Update the accumulator memory cells for an aggregate based on
481513449892Sdrh ** the current cursor position.
481613449892Sdrh */
481713449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
481813449892Sdrh   Vdbe *v = pParse->pVdbe;
481913449892Sdrh   int i;
48207a95789cSdrh   int regHit = 0;
48217a95789cSdrh   int addrHitTest = 0;
482213449892Sdrh   struct AggInfo_func *pF;
482313449892Sdrh   struct AggInfo_col *pC;
482413449892Sdrh 
482513449892Sdrh   pAggInfo->directMode = 1;
482613449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
482713449892Sdrh     int nArg;
4828c99130fdSdrh     int addrNext = 0;
482998757157Sdrh     int regAgg;
48306ab3a2ecSdanielk1977     ExprList *pList = pF->pExpr->x.pList;
48316ab3a2ecSdanielk1977     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
483213449892Sdrh     if( pList ){
483313449892Sdrh       nArg = pList->nExpr;
4834892d3179Sdrh       regAgg = sqlite3GetTempRange(pParse, nArg);
48355579d59fSdrh       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
483613449892Sdrh     }else{
483713449892Sdrh       nArg = 0;
483898757157Sdrh       regAgg = 0;
483913449892Sdrh     }
4840c99130fdSdrh     if( pF->iDistinct>=0 ){
4841c99130fdSdrh       addrNext = sqlite3VdbeMakeLabel(v);
48427c052da5Sdrh       testcase( nArg==0 );  /* Error condition */
48437c052da5Sdrh       testcase( nArg>1 );   /* Also an error */
48442dcef11bSdrh       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
4845c99130fdSdrh     }
4846d36e1041Sdrh     if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
484713449892Sdrh       CollSeq *pColl = 0;
484813449892Sdrh       struct ExprList_item *pItem;
484913449892Sdrh       int j;
4850e82f5d04Sdrh       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
485143617e9aSdrh       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
485213449892Sdrh         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
485313449892Sdrh       }
485413449892Sdrh       if( !pColl ){
485513449892Sdrh         pColl = pParse->db->pDfltColl;
485613449892Sdrh       }
48577a95789cSdrh       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
48587a95789cSdrh       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
485913449892Sdrh     }
48602700acaaSdrh     sqlite3VdbeAddOp3(v, OP_AggStep0, 0, regAgg, pF->iMem);
48612700acaaSdrh     sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
4862ea678832Sdrh     sqlite3VdbeChangeP5(v, (u8)nArg);
4863da250ea5Sdrh     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
4864f49f3523Sdrh     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
4865c99130fdSdrh     if( addrNext ){
4866c99130fdSdrh       sqlite3VdbeResolveLabel(v, addrNext);
4867ceea3321Sdrh       sqlite3ExprCacheClear(pParse);
4868c99130fdSdrh     }
486913449892Sdrh   }
487067a6a40cSdan 
487167a6a40cSdan   /* Before populating the accumulator registers, clear the column cache.
487267a6a40cSdan   ** Otherwise, if any of the required column values are already present
487367a6a40cSdan   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
487467a6a40cSdan   ** to pC->iMem. But by the time the value is used, the original register
487567a6a40cSdan   ** may have been used, invalidating the underlying buffer holding the
487667a6a40cSdan   ** text or blob value. See ticket [883034dcb5].
487767a6a40cSdan   **
487867a6a40cSdan   ** Another solution would be to change the OP_SCopy used to copy cached
487967a6a40cSdan   ** values to an OP_Copy.
488067a6a40cSdan   */
48817a95789cSdrh   if( regHit ){
4882688852abSdrh     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
48837a95789cSdrh   }
488467a6a40cSdan   sqlite3ExprCacheClear(pParse);
488513449892Sdrh   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
4886389a1adbSdrh     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
488713449892Sdrh   }
488813449892Sdrh   pAggInfo->directMode = 0;
4889ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
48907a95789cSdrh   if( addrHitTest ){
48917a95789cSdrh     sqlite3VdbeJumpHere(v, addrHitTest);
48927a95789cSdrh   }
489313449892Sdrh }
489413449892Sdrh 
4895b3bce662Sdanielk1977 /*
4896ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple
4897ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab").
4898ef7075deSdan */
4899ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN
4900ef7075deSdan static void explainSimpleCount(
4901ef7075deSdan   Parse *pParse,                  /* Parse context */
4902ef7075deSdan   Table *pTab,                    /* Table being queried */
4903ef7075deSdan   Index *pIdx                     /* Index used to optimize scan, or NULL */
4904ef7075deSdan ){
4905ef7075deSdan   if( pParse->explain==2 ){
490648dd1d8eSdrh     int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
49078a4380d7Sdrh     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
4908ef7075deSdan         pTab->zName,
4909e96f2df3Sdan         bCover ? " USING COVERING INDEX " : "",
4910e96f2df3Sdan         bCover ? pIdx->zName : ""
4911ef7075deSdan     );
4912ef7075deSdan     sqlite3VdbeAddOp4(
4913ef7075deSdan         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
4914ef7075deSdan     );
4915ef7075deSdan   }
4916ef7075deSdan }
4917ef7075deSdan #else
4918ef7075deSdan # define explainSimpleCount(a,b,c)
4919ef7075deSdan #endif
4920ef7075deSdan 
4921ef7075deSdan /*
4922ab31a845Sdan ** Context object for havingToWhereExprCb().
4923ab31a845Sdan */
4924ab31a845Sdan struct HavingToWhereCtx {
4925ab31a845Sdan   Expr **ppWhere;
4926ab31a845Sdan   ExprList *pGroupBy;
4927ab31a845Sdan };
4928ab31a845Sdan 
4929ab31a845Sdan /*
4930ab31a845Sdan ** sqlite3WalkExpr() callback used by havingToWhere().
4931ab31a845Sdan **
4932ab31a845Sdan ** If the node passed to the callback is a TK_AND node, return
4933ab31a845Sdan ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
4934ab31a845Sdan **
4935ab31a845Sdan ** Otherwise, return WRC_Prune. In this case, also check if the
4936ab31a845Sdan ** sub-expression matches the criteria for being moved to the WHERE
4937ab31a845Sdan ** clause. If so, add it to the WHERE clause and replace the sub-expression
4938ab31a845Sdan ** within the HAVING expression with a constant "1".
4939ab31a845Sdan */
4940ab31a845Sdan static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
4941ab31a845Sdan   if( pExpr->op!=TK_AND ){
4942ab31a845Sdan     struct HavingToWhereCtx *p = pWalker->u.pHavingCtx;
4943ab31a845Sdan     if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, p->pGroupBy) ){
4944ab31a845Sdan       sqlite3 *db = pWalker->pParse->db;
4945ab31a845Sdan       Expr *pNew = sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[1], 0);
4946ab31a845Sdan       if( pNew ){
4947ab31a845Sdan         Expr *pWhere = *(p->ppWhere);
4948ab31a845Sdan         SWAP(Expr, *pNew, *pExpr);
4949ab31a845Sdan         pNew = sqlite3ExprAnd(db, pWhere, pNew);
4950ab31a845Sdan         *(p->ppWhere) = pNew;
4951ab31a845Sdan       }
4952ab31a845Sdan     }
4953ab31a845Sdan     return WRC_Prune;
4954ab31a845Sdan   }
4955ab31a845Sdan   return WRC_Continue;
4956ab31a845Sdan }
4957ab31a845Sdan 
4958ab31a845Sdan /*
4959ab31a845Sdan ** Transfer eligible terms from the HAVING clause of a query, which is
4960ab31a845Sdan ** processed after grouping, to the WHERE clause, which is processed before
4961ab31a845Sdan ** grouping. For example, the query:
4962ab31a845Sdan **
4963ab31a845Sdan **   SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
4964ab31a845Sdan **
4965ab31a845Sdan ** can be rewritten as:
4966ab31a845Sdan **
4967ab31a845Sdan **   SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
4968ab31a845Sdan **
4969ab31a845Sdan ** A term of the HAVING expression is eligible for transfer if it consists
4970ab31a845Sdan ** entirely of constants and expressions that are also GROUP BY terms that
4971ab31a845Sdan ** use the "BINARY" collation sequence.
4972ab31a845Sdan */
4973ab31a845Sdan static void havingToWhere(
4974ab31a845Sdan   Parse *pParse,
4975ab31a845Sdan   ExprList *pGroupBy,
4976ab31a845Sdan   Expr *pHaving,
4977ab31a845Sdan   Expr **ppWhere
4978ab31a845Sdan ){
4979ab31a845Sdan   struct HavingToWhereCtx sCtx;
4980ab31a845Sdan   Walker sWalker;
4981ab31a845Sdan 
4982ab31a845Sdan   sCtx.ppWhere = ppWhere;
4983ab31a845Sdan   sCtx.pGroupBy = pGroupBy;
4984ab31a845Sdan 
4985ab31a845Sdan   memset(&sWalker, 0, sizeof(sWalker));
4986ab31a845Sdan   sWalker.pParse = pParse;
4987ab31a845Sdan   sWalker.xExprCallback = havingToWhereExprCb;
4988ab31a845Sdan   sWalker.u.pHavingCtx = &sCtx;
4989ab31a845Sdan   sqlite3WalkExpr(&sWalker, pHaving);
4990ab31a845Sdan }
4991ab31a845Sdan 
4992ab31a845Sdan /*
4993e08e8d6bSdrh ** Check to see if the pThis entry of pTabList is a self-join of a prior view.
4994e08e8d6bSdrh ** If it is, then return the SrcList_item for the prior view.  If it is not,
4995e08e8d6bSdrh ** then return 0.
4996e08e8d6bSdrh */
4997e08e8d6bSdrh static struct SrcList_item *isSelfJoinView(
4998e08e8d6bSdrh   SrcList *pTabList,           /* Search for self-joins in this FROM clause */
4999e08e8d6bSdrh   struct SrcList_item *pThis   /* Search for prior reference to this subquery */
5000e08e8d6bSdrh ){
5001e08e8d6bSdrh   struct SrcList_item *pItem;
5002e08e8d6bSdrh   for(pItem = pTabList->a; pItem<pThis; pItem++){
5003e08e8d6bSdrh     if( pItem->pSelect==0 ) continue;
5004e08e8d6bSdrh     if( pItem->fg.viaCoroutine ) continue;
500533543c23Sdrh     if( pItem->zName==0 ) continue;
500633543c23Sdrh     if( sqlite3_stricmp(pItem->zDatabase, pThis->zDatabase)!=0 ) continue;
5007ed712980Sdrh     if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
50085aa550cfSdan     if( sqlite3ExprCompare(0,
50095aa550cfSdan           pThis->pSelect->pWhere, pItem->pSelect->pWhere, -1)
50105aa550cfSdan     ){
5011ed712980Sdrh       /* The view was modified by some other optimization such as
5012ed712980Sdrh       ** pushDownWhereTerms() */
5013ed712980Sdrh       continue;
5014ed712980Sdrh     }
5015ed712980Sdrh     return pItem;
5016e08e8d6bSdrh   }
5017e08e8d6bSdrh   return 0;
5018e08e8d6bSdrh }
5019e08e8d6bSdrh 
5020269ba804Sdrh #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
5021269ba804Sdrh /*
5022269ba804Sdrh ** Attempt to transform a query of the form
5023269ba804Sdrh **
5024269ba804Sdrh **    SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
5025269ba804Sdrh **
5026269ba804Sdrh ** Into this:
5027269ba804Sdrh **
5028269ba804Sdrh **    SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
5029269ba804Sdrh **
5030269ba804Sdrh ** The transformation only works if all of the following are true:
5031269ba804Sdrh **
5032269ba804Sdrh **   *  The subquery is a UNION ALL of two or more terms
5033269ba804Sdrh **   *  There is no WHERE or GROUP BY or HAVING clauses on the subqueries
5034269ba804Sdrh **   *  The outer query is a simple count(*)
5035269ba804Sdrh **
5036269ba804Sdrh ** Return TRUE if the optimization is undertaken.
5037269ba804Sdrh */
5038269ba804Sdrh static int countOfViewOptimization(Parse *pParse, Select *p){
5039269ba804Sdrh   Select *pSub, *pPrior;
5040269ba804Sdrh   Expr *pExpr;
5041269ba804Sdrh   Expr *pCount;
5042269ba804Sdrh   sqlite3 *db;
50433d240d21Sdrh   if( (p->selFlags & SF_Aggregate)==0 ) return 0;   /* This is an aggregate */
5044269ba804Sdrh   if( p->pEList->nExpr!=1 ) return 0;               /* Single result column */
5045269ba804Sdrh   pExpr = p->pEList->a[0].pExpr;
5046269ba804Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;        /* Result is an aggregate */
50473d240d21Sdrh   if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0;  /* Is count() */
5048269ba804Sdrh   if( pExpr->x.pList!=0 ) return 0;                 /* Must be count(*) */
50493d240d21Sdrh   if( p->pSrc->nSrc!=1 ) return 0;                  /* One table in FROM  */
5050269ba804Sdrh   pSub = p->pSrc->a[0].pSelect;
5051269ba804Sdrh   if( pSub==0 ) return 0;                           /* The FROM is a subquery */
50523d240d21Sdrh   if( pSub->pPrior==0 ) return 0;                   /* Must be a compound ry */
5053269ba804Sdrh   do{
5054269ba804Sdrh     if( pSub->op!=TK_ALL && pSub->pPrior ) return 0;  /* Must be UNION ALL */
5055269ba804Sdrh     if( pSub->pWhere ) return 0;                      /* No WHERE clause */
5056269ba804Sdrh     if( pSub->selFlags & SF_Aggregate ) return 0;     /* Not an aggregate */
50573d240d21Sdrh     pSub = pSub->pPrior;                              /* Repeat over compound */
5058269ba804Sdrh   }while( pSub );
5059269ba804Sdrh 
50603d240d21Sdrh   /* If we reach this point then it is OK to perform the transformation */
5061269ba804Sdrh 
5062269ba804Sdrh   db = pParse->db;
5063269ba804Sdrh   pCount = pExpr;
5064269ba804Sdrh   pExpr = 0;
5065269ba804Sdrh   pSub = p->pSrc->a[0].pSelect;
5066269ba804Sdrh   p->pSrc->a[0].pSelect = 0;
5067269ba804Sdrh   sqlite3SrcListDelete(db, p->pSrc);
5068269ba804Sdrh   p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
5069269ba804Sdrh   while( pSub ){
5070269ba804Sdrh     Expr *pTerm;
5071269ba804Sdrh     pPrior = pSub->pPrior;
5072269ba804Sdrh     pSub->pPrior = 0;
5073269ba804Sdrh     pSub->pNext = 0;
5074269ba804Sdrh     pSub->selFlags |= SF_Aggregate;
5075269ba804Sdrh     pSub->selFlags &= ~SF_Compound;
5076269ba804Sdrh     pSub->nSelectRow = 0;
5077269ba804Sdrh     sqlite3ExprListDelete(db, pSub->pEList);
5078269ba804Sdrh     pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
5079269ba804Sdrh     pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
5080269ba804Sdrh     pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
5081269ba804Sdrh     sqlite3PExprAddSelect(pParse, pTerm, pSub);
5082269ba804Sdrh     if( pExpr==0 ){
5083269ba804Sdrh       pExpr = pTerm;
5084269ba804Sdrh     }else{
5085269ba804Sdrh       pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
5086269ba804Sdrh     }
5087269ba804Sdrh     pSub = pPrior;
5088269ba804Sdrh   }
5089269ba804Sdrh   p->pEList->a[0].pExpr = pExpr;
5090269ba804Sdrh   p->selFlags &= ~SF_Aggregate;
5091269ba804Sdrh 
5092269ba804Sdrh #if SELECTTRACE_ENABLED
5093269ba804Sdrh   if( sqlite3SelectTrace & 0x400 ){
5094269ba804Sdrh     SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
5095269ba804Sdrh     sqlite3TreeViewSelect(0, p, 0);
5096269ba804Sdrh   }
5097269ba804Sdrh #endif
5098269ba804Sdrh   return 1;
5099269ba804Sdrh }
5100269ba804Sdrh #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
5101269ba804Sdrh 
5102e08e8d6bSdrh /*
51037d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument.
51049bb61fe7Sdrh **
5105340309fdSdrh ** The results are returned according to the SelectDest structure.
5106340309fdSdrh ** See comments in sqliteInt.h for further information.
5107e78e8284Sdrh **
51089bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
51099bb61fe7Sdrh ** encountered, then an appropriate error message is left in
51109bb61fe7Sdrh ** pParse->zErrMsg.
51119bb61fe7Sdrh **
51129bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
51139bb61fe7Sdrh ** calling function needs to do that.
51149bb61fe7Sdrh */
51154adee20fSdanielk1977 int sqlite3Select(
5116cce7d176Sdrh   Parse *pParse,         /* The parser context */
51179bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
51187d10d5a6Sdrh   SelectDest *pDest      /* What to do with the query results */
5119cce7d176Sdrh ){
512013449892Sdrh   int i, j;              /* Loop counters */
512113449892Sdrh   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
512213449892Sdrh   Vdbe *v;               /* The virtual machine under construction */
5123b3bce662Sdanielk1977   int isAgg;             /* True for select lists like "count(*)" */
5124c29cbb0bSmistachkin   ExprList *pEList = 0;  /* List of columns to extract. */
5125ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
51269bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
51272282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
51282282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
51291d83f052Sdrh   int rc = 1;            /* Value to return from this function */
5130e8e4af76Sdrh   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
5131079a3072Sdrh   SortCtx sSort;         /* Info on how to code the ORDER BY clause */
513213449892Sdrh   AggInfo sAggInfo;      /* Information used by aggregate queries */
5133ec7429aeSdrh   int iEnd;              /* Address of the end of the query */
513417435752Sdrh   sqlite3 *db;           /* The database connection */
51359bb61fe7Sdrh 
51362ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN
51372ce22453Sdan   int iRestoreSelectId = pParse->iSelectId;
51382ce22453Sdan   pParse->iSelectId = pParse->iNextSelectId++;
51392ce22453Sdan #endif
51402ce22453Sdan 
514117435752Sdrh   db = pParse->db;
514217435752Sdrh   if( p==0 || db->mallocFailed || pParse->nErr ){
51436f7adc8aSdrh     return 1;
51446f7adc8aSdrh   }
51454adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
514613449892Sdrh   memset(&sAggInfo, 0, sizeof(sAggInfo));
5147eb9b884cSdrh #if SELECTTRACE_ENABLED
5148eb9b884cSdrh   pParse->nSelectIndent++;
5149c90713d3Sdrh   SELECTTRACE(1,pParse,p, ("begin processing:\n"));
5150c90713d3Sdrh   if( sqlite3SelectTrace & 0x100 ){
5151c90713d3Sdrh     sqlite3TreeViewSelect(0, p, 0);
5152c90713d3Sdrh   }
5153eb9b884cSdrh #endif
5154daffd0e5Sdrh 
51558e1ee88cSdrh   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
51568e1ee88cSdrh   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
51579afccba2Sdan   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
51589afccba2Sdan   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
51596c8c8ce0Sdanielk1977   if( IgnorableOrderby(pDest) ){
51609ed1dfa8Sdanielk1977     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
51619afccba2Sdan            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
51628e1ee88cSdrh            pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
51638e1ee88cSdrh            pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
5164ccfcbceaSdrh     /* If ORDER BY makes no difference in the output then neither does
5165ccfcbceaSdrh     ** DISTINCT so it can be removed too. */
5166ccfcbceaSdrh     sqlite3ExprListDelete(db, p->pOrderBy);
5167ccfcbceaSdrh     p->pOrderBy = 0;
51687d10d5a6Sdrh     p->selFlags &= ~SF_Distinct;
51699a99334dSdrh   }
51707d10d5a6Sdrh   sqlite3SelectPrep(pParse, p, 0);
5171079a3072Sdrh   memset(&sSort, 0, sizeof(sSort));
5172079a3072Sdrh   sSort.pOrderBy = p->pOrderBy;
5173b27b7f5dSdrh   pTabList = p->pSrc;
5174956f4319Sdanielk1977   if( pParse->nErr || db->mallocFailed ){
51759a99334dSdrh     goto select_end;
51769a99334dSdrh   }
5177adc57f68Sdrh   assert( p->pEList!=0 );
51787d10d5a6Sdrh   isAgg = (p->selFlags & SF_Aggregate)!=0;
517917645f5eSdrh #if SELECTTRACE_ENABLED
518017645f5eSdrh   if( sqlite3SelectTrace & 0x100 ){
518117645f5eSdrh     SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
518217645f5eSdrh     sqlite3TreeViewSelect(0, p, 0);
518317645f5eSdrh   }
518417645f5eSdrh #endif
5185cce7d176Sdrh 
5186f35f2f92Sdrh   /* Get a pointer the VDBE under construction, allocating a new VDBE if one
5187f35f2f92Sdrh   ** does not already exist */
5188f35f2f92Sdrh   v = sqlite3GetVdbe(pParse);
5189f35f2f92Sdrh   if( v==0 ) goto select_end;
5190f35f2f92Sdrh   if( pDest->eDest==SRT_Output ){
5191f35f2f92Sdrh     generateColumnNames(pParse, p);
5192f35f2f92Sdrh   }
5193f35f2f92Sdrh 
5194adc57f68Sdrh   /* Try to flatten subqueries in the FROM clause up into the main query
5195d820cb1bSdrh   */
519651522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
5197f23329a2Sdanielk1977   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
519813449892Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
5199daf79acbSdanielk1977     Select *pSub = pItem->pSelect;
5200f23329a2Sdanielk1977     int isAggSub;
52012679f14fSdrh     Table *pTab = pItem->pTab;
52024490c40bSdrh     if( pSub==0 ) continue;
52032679f14fSdrh 
52042679f14fSdrh     /* Catch mismatch in the declared columns of a view and the number of
52052679f14fSdrh     ** columns in the SELECT on the RHS */
52062679f14fSdrh     if( pTab->nCol!=pSub->pEList->nExpr ){
52072679f14fSdrh       sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
52082679f14fSdrh                       pTab->nCol, pTab->zName, pSub->pEList->nExpr);
52092679f14fSdrh       goto select_end;
52102679f14fSdrh     }
52112679f14fSdrh 
52124490c40bSdrh     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
52134490c40bSdrh     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
52144490c40bSdrh       /* This subquery can be absorbed into its parent. */
52154490c40bSdrh       if( isAggSub ){
52164490c40bSdrh         isAgg = 1;
52174490c40bSdrh         p->selFlags |= SF_Aggregate;
52184490c40bSdrh       }
52194490c40bSdrh       i = -1;
52204490c40bSdrh     }
52214490c40bSdrh     pTabList = p->pSrc;
52224490c40bSdrh     if( db->mallocFailed ) goto select_end;
52234490c40bSdrh     if( !IgnorableOrderby(pDest) ){
52244490c40bSdrh       sSort.pOrderBy = p->pOrderBy;
52254490c40bSdrh     }
52264490c40bSdrh   }
52274490c40bSdrh #endif
52284490c40bSdrh 
52294490c40bSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
52304490c40bSdrh   /* Handle compound SELECT statements using the separate multiSelect()
52314490c40bSdrh   ** procedure.
52324490c40bSdrh   */
52334490c40bSdrh   if( p->pPrior ){
52344490c40bSdrh     rc = multiSelect(pParse, p, pDest);
52354490c40bSdrh     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
52364490c40bSdrh #if SELECTTRACE_ENABLED
52374490c40bSdrh     SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
52384490c40bSdrh     pParse->nSelectIndent--;
52394490c40bSdrh #endif
52404490c40bSdrh     return rc;
52414490c40bSdrh   }
52424490c40bSdrh #endif
52434490c40bSdrh 
5244701caf1eSdrh   /* For each term in the FROM clause, do two things:
5245701caf1eSdrh   ** (1) Authorized unreferenced tables
5246701caf1eSdrh   ** (2) Generate code for all sub-queries
52476e17529eSdrh   */
52484490c40bSdrh   for(i=0; i<pTabList->nSrc; i++){
5249ad3cab52Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
52505cf590c1Sdrh     SelectDest dest;
5251701caf1eSdrh     Select *pSub;
5252701caf1eSdrh 
52533d240d21Sdrh     /* Issue SQLITE_READ authorizations with a fake column name for any
52543d240d21Sdrh     ** tables that are referenced but from which no values are extracted.
52553d240d21Sdrh     ** Examples of where these kinds of null SQLITE_READ authorizations
52563d240d21Sdrh     ** would occur:
5257701caf1eSdrh     **
52582336c935Sdrh     **     SELECT count(*) FROM t1;   -- SQLITE_READ t1.""
52592336c935Sdrh     **     SELECT t1.* FROM t1, t2;   -- SQLITE_READ t2.""
52602336c935Sdrh     **
52612336c935Sdrh     ** The fake column name is an empty string.  It is possible for a table to
52622336c935Sdrh     ** have a column named by the empty string, in which case there is no way to
52632336c935Sdrh     ** distinguish between an unreferenced table and an actual reference to the
52642336c935Sdrh     ** "" column. The original design was for the fake column name to be a NULL,
52652336c935Sdrh     ** which would be unambiguous.  But legacy authorization callbacks might
52663d240d21Sdrh     ** assume the column name is non-NULL and segfault.  The use of an empty
52673d240d21Sdrh     ** string for the fake column name seems safer.
5268701caf1eSdrh     */
5269701caf1eSdrh     if( pItem->colUsed==0 ){
52702336c935Sdrh       sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
5271701caf1eSdrh     }
5272701caf1eSdrh 
5273701caf1eSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
5274701caf1eSdrh     /* Generate code for all sub-queries in the FROM clause
5275701caf1eSdrh     */
5276701caf1eSdrh     pSub = pItem->pSelect;
52775b6a9ed4Sdrh     if( pSub==0 ) continue;
527821172c4cSdrh 
527921172c4cSdrh     /* Sometimes the code for a subquery will be generated more than
528021172c4cSdrh     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
528121172c4cSdrh     ** for example.  In that case, do not regenerate the code to manifest
528221172c4cSdrh     ** a view or the co-routine to implement a view.  The first instance
528321172c4cSdrh     ** is sufficient, though the subroutine to manifest the view does need
528421172c4cSdrh     ** to be invoked again. */
52855b6a9ed4Sdrh     if( pItem->addrFillSub ){
52868a48b9c0Sdrh       if( pItem->fg.viaCoroutine==0 ){
52877555581fSdrh         /* The subroutine that manifests the view might be a one-time routine,
52887555581fSdrh         ** or it might need to be rerun on each iteration because it
52897555581fSdrh         ** encodes a correlated subquery. */
52907555581fSdrh         testcase( sqlite3VdbeGetOp(v, pItem->addrFillSub)->opcode==OP_Once );
52915b6a9ed4Sdrh         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
529221172c4cSdrh       }
52935b6a9ed4Sdrh       continue;
52945b6a9ed4Sdrh     }
5295daf79acbSdanielk1977 
5296fc976065Sdanielk1977     /* Increment Parse.nHeight by the height of the largest expression
5297f7b5496eSdrh     ** tree referred to by this, the parent select. The child select
5298fc976065Sdanielk1977     ** may contain expression trees of at most
5299fc976065Sdanielk1977     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
5300fc976065Sdanielk1977     ** more conservative than necessary, but much easier than enforcing
5301fc976065Sdanielk1977     ** an exact limit.
5302fc976065Sdanielk1977     */
5303fc976065Sdanielk1977     pParse->nHeight += sqlite3SelectExprHeight(p);
5304daf79acbSdanielk1977 
5305adc57f68Sdrh     /* Make copies of constant WHERE-clause terms in the outer query down
5306adc57f68Sdrh     ** inside the subquery.  This can help the subquery to run more efficiently.
5307adc57f68Sdrh     */
53088a48b9c0Sdrh     if( (pItem->fg.jointype & JT_OUTER)==0
530944c5604cSdan      && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor)
531069b72d5aSdrh     ){
531169b72d5aSdrh #if SELECTTRACE_ENABLED
531269b72d5aSdrh       if( sqlite3SelectTrace & 0x100 ){
5313bc8edba1Sdrh         SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
531469b72d5aSdrh         sqlite3TreeViewSelect(0, p, 0);
5315daf79acbSdanielk1977       }
531669b72d5aSdrh #endif
531769b72d5aSdrh     }
5318adc57f68Sdrh 
5319adc57f68Sdrh     /* Generate code to implement the subquery
53200ff47e9eSdrh     **
53210ff47e9eSdrh     ** The subquery is implemented as a co-routine if all of these are true:
53220ff47e9eSdrh     **   (1)  The subquery is guaranteed to be the outer loop (so that it
53230ff47e9eSdrh     **        does not need to be computed more than once)
53242e9d7062Sdrh     **   (2)  REMOVED (2017-09-28): The ALL keyword after SELECT is omitted.
53250ff47e9eSdrh     **   (3)  Co-routines are not disabled using sqlite3_test_control()
53260ff47e9eSdrh     **        with SQLITE_TESTCTRL_OPTIMIZATIONS.
53270ff47e9eSdrh     **
53280ff47e9eSdrh     ** TODO: Are there other reasons beside (1) to use a co-routine
53290ff47e9eSdrh     ** implementation?
5330adc57f68Sdrh     */
53310ff47e9eSdrh     if( i==0
53320ff47e9eSdrh      && (pTabList->nSrc==1
53330ff47e9eSdrh             || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)  /* (1) */
53342e9d7062Sdrh      /*** constraint removed: && (p->selFlags & SF_All)==0             (2) */
53350ff47e9eSdrh      && OptimizationEnabled(db, SQLITE_SubqCoroutine)               /* (3) */
5336a5759677Sdrh     ){
533721172c4cSdrh       /* Implement a co-routine that will return a single row of the result
533821172c4cSdrh       ** set on each invocation.
533921172c4cSdrh       */
5340725de29aSdrh       int addrTop = sqlite3VdbeCurrentAddr(v)+1;
534121172c4cSdrh       pItem->regReturn = ++pParse->nMem;
5342725de29aSdrh       sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
5343725de29aSdrh       VdbeComment((v, "%s", pItem->pTab->zName));
534421172c4cSdrh       pItem->addrFillSub = addrTop;
534521172c4cSdrh       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
534621172c4cSdrh       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
534721172c4cSdrh       sqlite3Select(pParse, pSub, &dest);
5348c3489bbfSdrh       pItem->pTab->nRowLogEst = pSub->nSelectRow;
53498a48b9c0Sdrh       pItem->fg.viaCoroutine = 1;
53505f612295Sdrh       pItem->regResult = dest.iSdst;
53512fade2f7Sdrh       sqlite3VdbeEndCoroutine(v, pItem->regReturn);
535221172c4cSdrh       sqlite3VdbeJumpHere(v, addrTop-1);
535321172c4cSdrh       sqlite3ClearTempRegCache(pParse);
5354daf79acbSdanielk1977     }else{
53555b6a9ed4Sdrh       /* Generate a subroutine that will fill an ephemeral table with
53565b6a9ed4Sdrh       ** the content of this subquery.  pItem->addrFillSub will point
53575b6a9ed4Sdrh       ** to the address of the generated subroutine.  pItem->regReturn
53585b6a9ed4Sdrh       ** is a register allocated to hold the subroutine return address
53595b6a9ed4Sdrh       */
53607157e8eaSdrh       int topAddr;
536148f2d3b1Sdrh       int onceAddr = 0;
53627157e8eaSdrh       int retAddr;
5363e08e8d6bSdrh       struct SrcList_item *pPrior;
5364e08e8d6bSdrh 
53655b6a9ed4Sdrh       assert( pItem->addrFillSub==0 );
53665b6a9ed4Sdrh       pItem->regReturn = ++pParse->nMem;
53677157e8eaSdrh       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
53687157e8eaSdrh       pItem->addrFillSub = topAddr+1;
53698a48b9c0Sdrh       if( pItem->fg.isCorrelated==0 ){
5370ed17167eSdrh         /* If the subquery is not correlated and if we are not inside of
53715b6a9ed4Sdrh         ** a trigger, then we only need to compute the value of the subquery
53725b6a9ed4Sdrh         ** once. */
5373511f9e8dSdrh         onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
5374725de29aSdrh         VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
5375725de29aSdrh       }else{
5376725de29aSdrh         VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
53775b6a9ed4Sdrh       }
5378e08e8d6bSdrh       pPrior = isSelfJoinView(pTabList, pItem);
5379e08e8d6bSdrh       if( pPrior ){
5380e08e8d6bSdrh         sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
5381d8a29566Sdrh         explainSetInteger(pItem->iSelectId, pPrior->iSelectId);
5382eafc6dfeSdrh         assert( pPrior->pSelect!=0 );
5383eafc6dfeSdrh         pSub->nSelectRow = pPrior->pSelect->nSelectRow;
5384e08e8d6bSdrh       }else{
53851013c932Sdrh         sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
5386ce7e189dSdan         explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
53877d10d5a6Sdrh         sqlite3Select(pParse, pSub, &dest);
5388e08e8d6bSdrh       }
5389c3489bbfSdrh       pItem->pTab->nRowLogEst = pSub->nSelectRow;
539048f2d3b1Sdrh       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
53917157e8eaSdrh       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
53927157e8eaSdrh       VdbeComment((v, "end %s", pItem->pTab->zName));
53937157e8eaSdrh       sqlite3VdbeChangeP1(v, topAddr, retAddr);
5394cdc69557Sdrh       sqlite3ClearTempRegCache(pParse);
5395daf79acbSdanielk1977     }
5396adc57f68Sdrh     if( db->mallocFailed ) goto select_end;
5397fc976065Sdanielk1977     pParse->nHeight -= sqlite3SelectExprHeight(p);
5398daf79acbSdanielk1977 #endif
5399701caf1eSdrh   }
5400adc57f68Sdrh 
540138b4149cSdrh   /* Various elements of the SELECT copied into local variables for
540238b4149cSdrh   ** convenience */
5403adc57f68Sdrh   pEList = p->pEList;
5404daf79acbSdanielk1977   pWhere = p->pWhere;
5405832508b7Sdrh   pGroupBy = p->pGroupBy;
5406832508b7Sdrh   pHaving = p->pHaving;
5407e8e4af76Sdrh   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
5408832508b7Sdrh 
5409bc8edba1Sdrh #if SELECTTRACE_ENABLED
5410bc8edba1Sdrh   if( sqlite3SelectTrace & 0x400 ){
5411bc8edba1Sdrh     SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
5412bc8edba1Sdrh     sqlite3TreeViewSelect(0, p, 0);
5413f23329a2Sdanielk1977   }
5414f23329a2Sdanielk1977 #endif
5415f23329a2Sdanielk1977 
5416269ba804Sdrh #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
5417269ba804Sdrh   if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
5418269ba804Sdrh    && countOfViewOptimization(pParse, p)
5419269ba804Sdrh   ){
5420269ba804Sdrh     if( db->mallocFailed ) goto select_end;
5421269ba804Sdrh     pEList = p->pEList;
5422269ba804Sdrh     pTabList = p->pSrc;
5423269ba804Sdrh   }
5424269ba804Sdrh #endif
5425269ba804Sdrh 
542650118cdfSdan   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
542750118cdfSdan   ** if the select-list is the same as the ORDER BY list, then this query
542850118cdfSdan   ** can be rewritten as a GROUP BY. In other words, this:
542950118cdfSdan   **
543050118cdfSdan   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
543150118cdfSdan   **
543250118cdfSdan   ** is transformed to:
543350118cdfSdan   **
5434dea7d70dSdrh   **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
543550118cdfSdan   **
543650118cdfSdan   ** The second form is preferred as a single index (or temp-table) may be
543750118cdfSdan   ** used for both the ORDER BY and DISTINCT processing. As originally
543850118cdfSdan   ** written the query must use a temp-table for at least one of the ORDER
543950118cdfSdan   ** BY and DISTINCT, and an index or separate temp-table for the other.
544050118cdfSdan   */
544150118cdfSdan   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
5442adc57f68Sdrh    && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
544350118cdfSdan   ){
544450118cdfSdan     p->selFlags &= ~SF_Distinct;
5445adc57f68Sdrh     pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
5446e8e4af76Sdrh     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
5447e8e4af76Sdrh     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
5448e8e4af76Sdrh     ** original setting of the SF_Distinct flag, not the current setting */
5449e8e4af76Sdrh     assert( sDistinct.isTnct );
54507512cb47Sdrh 
54517512cb47Sdrh #if SELECTTRACE_ENABLED
54527512cb47Sdrh     if( sqlite3SelectTrace & 0x400 ){
54537512cb47Sdrh       SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
54547512cb47Sdrh       sqlite3TreeViewSelect(0, p, 0);
54557512cb47Sdrh     }
54567512cb47Sdrh #endif
545750118cdfSdan   }
545850118cdfSdan 
5459adc57f68Sdrh   /* If there is an ORDER BY clause, then create an ephemeral index to
5460adc57f68Sdrh   ** do the sorting.  But this sorting ephemeral index might end up
5461adc57f68Sdrh   ** being unused if the data can be extracted in pre-sorted order.
5462adc57f68Sdrh   ** If that is the case, then the OP_OpenEphemeral instruction will be
5463adc57f68Sdrh   ** changed to an OP_Noop once we figure out that the sorting index is
5464adc57f68Sdrh   ** not needed.  The sSort.addrSortIndex variable is used to facilitate
5465adc57f68Sdrh   ** that change.
54667cedc8d4Sdanielk1977   */
5467079a3072Sdrh   if( sSort.pOrderBy ){
54680342b1f5Sdrh     KeyInfo *pKeyInfo;
54693f39bcf5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
5470079a3072Sdrh     sSort.iECursor = pParse->nTab++;
5471079a3072Sdrh     sSort.addrSortIndex =
547266a5167bSdrh       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
5473f45f2326Sdrh           sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
5474f45f2326Sdrh           (char*)pKeyInfo, P4_KEYINFO
5475f45f2326Sdrh       );
54769d2985c7Sdrh   }else{
5477079a3072Sdrh     sSort.addrSortIndex = -1;
54787cedc8d4Sdanielk1977   }
54797cedc8d4Sdanielk1977 
54802d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
54812d0794e3Sdrh   */
54826c8c8ce0Sdanielk1977   if( pDest->eDest==SRT_EphemTab ){
54832b596da8Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
54842d0794e3Sdrh   }
54852d0794e3Sdrh 
5486f42bacc2Sdrh   /* Set the limiter.
5487f42bacc2Sdrh   */
5488f42bacc2Sdrh   iEnd = sqlite3VdbeMakeLabel(v);
548969b9383eSdan   if( (p->selFlags & SF_FixedLimit)==0 ){
5490c3489bbfSdrh     p->nSelectRow = 320;  /* 4 billion rows */
549169b9383eSdan   }
5492f42bacc2Sdrh   computeLimitRegisters(pParse, p, iEnd);
5493079a3072Sdrh   if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
54940ff287fbSdrh     sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
5495079a3072Sdrh     sSort.sortFlags |= SORTFLAG_UseSorter;
5496c6aff30cSdrh   }
5497f42bacc2Sdrh 
5498adc57f68Sdrh   /* Open an ephemeral index to use for the distinct set.
5499cce7d176Sdrh   */
55002ce22453Sdan   if( p->selFlags & SF_Distinct ){
5501e8e4af76Sdrh     sDistinct.tabTnct = pParse->nTab++;
5502e8e4af76Sdrh     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
5503e8e4af76Sdrh                              sDistinct.tabTnct, 0, 0,
5504079a3072Sdrh                              (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
55052ec2fb22Sdrh                              P4_KEYINFO);
5506d4187c71Sdrh     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
5507e8e4af76Sdrh     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
5508832508b7Sdrh   }else{
5509e8e4af76Sdrh     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
5510efb7251dSdrh   }
5511832508b7Sdrh 
551213449892Sdrh   if( !isAgg && pGroupBy==0 ){
5513e8e4af76Sdrh     /* No aggregate functions and no GROUP BY clause */
55146457a353Sdrh     u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
5515c3489bbfSdrh     assert( WHERE_USE_LIMIT==SF_FixedLimit );
5516c3489bbfSdrh     wctrlFlags |= p->selFlags & SF_FixedLimit;
551738cc40c2Sdan 
551838cc40c2Sdan     /* Begin the database scan. */
5519079a3072Sdrh     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
5520c3489bbfSdrh                                p->pEList, wctrlFlags, p->nSelectRow);
55211d83f052Sdrh     if( pWInfo==0 ) goto select_end;
55226f32848dSdrh     if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
55236f32848dSdrh       p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
55246f32848dSdrh     }
55256457a353Sdrh     if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
55266f32848dSdrh       sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
55276f32848dSdrh     }
5528079a3072Sdrh     if( sSort.pOrderBy ){
5529079a3072Sdrh       sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
5530a536df4eSdrh       sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo);
5531079a3072Sdrh       if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
5532079a3072Sdrh         sSort.pOrderBy = 0;
5533079a3072Sdrh       }
5534079a3072Sdrh     }
5535cce7d176Sdrh 
5536b9bb7c18Sdrh     /* If sorting index that was created by a prior OP_OpenEphemeral
5537b9bb7c18Sdrh     ** instruction ended up not being needed, then change the OP_OpenEphemeral
55389d2985c7Sdrh     ** into an OP_Noop.
55399d2985c7Sdrh     */
5540079a3072Sdrh     if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
5541079a3072Sdrh       sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
55429d2985c7Sdrh     }
55439d2985c7Sdrh 
554438cc40c2Sdan     /* Use the standard inner loop. */
55452def2f7eSdrh     assert( p->pEList==pEList );
55462def2f7eSdrh     selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
55476f32848dSdrh                     sqlite3WhereContinueLabel(pWInfo),
55486f32848dSdrh                     sqlite3WhereBreakLabel(pWInfo));
55492282792aSdrh 
5550cce7d176Sdrh     /* End the database scan loop.
5551cce7d176Sdrh     */
55524adee20fSdanielk1977     sqlite3WhereEnd(pWInfo);
555313449892Sdrh   }else{
5554e8e4af76Sdrh     /* This case when there exist aggregate functions or a GROUP BY clause
5555e8e4af76Sdrh     ** or both */
555613449892Sdrh     NameContext sNC;    /* Name context for processing aggregate information */
555713449892Sdrh     int iAMem;          /* First Mem address for storing current GROUP BY */
555813449892Sdrh     int iBMem;          /* First Mem address for previous GROUP BY */
555913449892Sdrh     int iUseFlag;       /* Mem address holding flag indicating that at least
556013449892Sdrh                         ** one row of the input to the aggregator has been
556113449892Sdrh                         ** processed */
556213449892Sdrh     int iAbortFlag;     /* Mem address which causes query abort if positive */
556313449892Sdrh     int groupBySort;    /* Rows come from source in GROUP BY order */
5564d176611bSdrh     int addrEnd;        /* End of processing for this SELECT */
55651c9d835dSdrh     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
55661c9d835dSdrh     int sortOut = 0;    /* Output register from the sorter */
5567374cd78cSdan     int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
5568d176611bSdrh 
5569d176611bSdrh     /* Remove any and all aliases between the result set and the
5570d176611bSdrh     ** GROUP BY clause.
5571d176611bSdrh     */
5572d176611bSdrh     if( pGroupBy ){
5573dc5ea5c7Sdrh       int k;                        /* Loop counter */
5574d176611bSdrh       struct ExprList_item *pItem;  /* For looping over expression in a list */
5575d176611bSdrh 
5576dc5ea5c7Sdrh       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
5577c2acc4e4Sdrh         pItem->u.x.iAlias = 0;
5578d176611bSdrh       }
5579dc5ea5c7Sdrh       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
5580c2acc4e4Sdrh         pItem->u.x.iAlias = 0;
5581d176611bSdrh       }
5582c3489bbfSdrh       assert( 66==sqlite3LogEst(100) );
5583c3489bbfSdrh       if( p->nSelectRow>66 ) p->nSelectRow = 66;
558495aa47b1Sdrh     }else{
5585c3489bbfSdrh       assert( 0==sqlite3LogEst(1) );
5586c3489bbfSdrh       p->nSelectRow = 0;
5587d176611bSdrh     }
5588cce7d176Sdrh 
5589374cd78cSdan     /* If there is both a GROUP BY and an ORDER BY clause and they are
5590374cd78cSdan     ** identical, then it may be possible to disable the ORDER BY clause
5591374cd78cSdan     ** on the grounds that the GROUP BY will cause elements to come out
5592adc57f68Sdrh     ** in the correct order. It also may not - the GROUP BY might use a
5593374cd78cSdan     ** database index that causes rows to be grouped together as required
5594374cd78cSdan     ** but not actually sorted. Either way, record the fact that the
5595374cd78cSdan     ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
5596374cd78cSdan     ** variable.  */
5597374cd78cSdan     if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
5598374cd78cSdan       orderByGrp = 1;
5599374cd78cSdan     }
560013449892Sdrh 
5601d176611bSdrh     /* Create a label to jump to when we want to abort the query */
560213449892Sdrh     addrEnd = sqlite3VdbeMakeLabel(v);
560313449892Sdrh 
560413449892Sdrh     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
560513449892Sdrh     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
560613449892Sdrh     ** SELECT statement.
56072282792aSdrh     */
560813449892Sdrh     memset(&sNC, 0, sizeof(sNC));
560913449892Sdrh     sNC.pParse = pParse;
561013449892Sdrh     sNC.pSrcList = pTabList;
561113449892Sdrh     sNC.pAggInfo = &sAggInfo;
56127e61d18eSdrh     sAggInfo.mnReg = pParse->nMem+1;
5613dd23c6bfSdan     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
56149d2985c7Sdrh     sAggInfo.pGroupBy = pGroupBy;
5615d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pEList);
5616079a3072Sdrh     sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
5617d2b3e23bSdrh     if( pHaving ){
5618ab31a845Sdan       if( pGroupBy ){
5619ab31a845Sdan         assert( pWhere==p->pWhere );
5620ab31a845Sdan         havingToWhere(pParse, pGroupBy, pHaving, &p->pWhere);
5621ab31a845Sdan         pWhere = p->pWhere;
5622ab31a845Sdan       }
5623d2b3e23bSdrh       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
562413449892Sdrh     }
562513449892Sdrh     sAggInfo.nAccumulator = sAggInfo.nColumn;
562613449892Sdrh     for(i=0; i<sAggInfo.nFunc; i++){
56276ab3a2ecSdanielk1977       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
56283a8c4be7Sdrh       sNC.ncFlags |= NC_InAggFunc;
56296ab3a2ecSdanielk1977       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
56303a8c4be7Sdrh       sNC.ncFlags &= ~NC_InAggFunc;
563113449892Sdrh     }
56327e61d18eSdrh     sAggInfo.mxReg = pParse->nMem;
563317435752Sdrh     if( db->mallocFailed ) goto select_end;
563413449892Sdrh 
563513449892Sdrh     /* Processing for aggregates with GROUP BY is very different and
56363c4809a2Sdanielk1977     ** much more complex than aggregates without a GROUP BY.
563713449892Sdrh     */
563813449892Sdrh     if( pGroupBy ){
563913449892Sdrh       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
5640728e0f91Sdrh       int addr1;          /* A-vs-B comparision jump */
5641d176611bSdrh       int addrOutputRow;  /* Start of subroutine that outputs a result row */
5642d176611bSdrh       int regOutputRow;   /* Return address register for output subroutine */
5643d176611bSdrh       int addrSetAbort;   /* Set the abort flag and return */
5644d176611bSdrh       int addrTopOfLoop;  /* Top of the input loop */
5645d176611bSdrh       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
5646d176611bSdrh       int addrReset;      /* Subroutine for resetting the accumulator */
5647d176611bSdrh       int regReset;       /* Return address register for reset subroutine */
564813449892Sdrh 
564913449892Sdrh       /* If there is a GROUP BY clause we might need a sorting index to
565013449892Sdrh       ** implement it.  Allocate that sorting index now.  If it turns out
56511c9d835dSdrh       ** that we do not need it after all, the OP_SorterOpen instruction
565213449892Sdrh       ** will be converted into a Noop.
565313449892Sdrh       */
565413449892Sdrh       sAggInfo.sortingIdx = pParse->nTab++;
56553f39bcf5Sdrh       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
56561c9d835dSdrh       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
5657cd3e8f7cSdanielk1977           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
56582ec2fb22Sdrh           0, (char*)pKeyInfo, P4_KEYINFO);
565913449892Sdrh 
566013449892Sdrh       /* Initialize memory locations used by GROUP BY aggregate processing
566113449892Sdrh       */
56620a07c107Sdrh       iUseFlag = ++pParse->nMem;
56630a07c107Sdrh       iAbortFlag = ++pParse->nMem;
5664d176611bSdrh       regOutputRow = ++pParse->nMem;
5665d176611bSdrh       addrOutputRow = sqlite3VdbeMakeLabel(v);
5666d176611bSdrh       regReset = ++pParse->nMem;
5667d176611bSdrh       addrReset = sqlite3VdbeMakeLabel(v);
56680a07c107Sdrh       iAMem = pParse->nMem + 1;
566913449892Sdrh       pParse->nMem += pGroupBy->nExpr;
56700a07c107Sdrh       iBMem = pParse->nMem + 1;
567113449892Sdrh       pParse->nMem += pGroupBy->nExpr;
56724c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
5673d4e70ebdSdrh       VdbeComment((v, "clear abort flag"));
56744c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
5675d4e70ebdSdrh       VdbeComment((v, "indicate accumulator empty"));
5676b8475df8Sdrh       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
5677e313382eSdrh 
567813449892Sdrh       /* Begin a loop that will extract all source rows in GROUP BY order.
567913449892Sdrh       ** This might involve two separate loops with an OP_Sort in between, or
568013449892Sdrh       ** it might be a single loop that uses an index to extract information
568113449892Sdrh       ** in the right order to begin with.
568213449892Sdrh       */
56832eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
568493ec45d5Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
5685374cd78cSdan           WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
5686374cd78cSdan       );
56875360ad34Sdrh       if( pWInfo==0 ) goto select_end;
5688ddba0c22Sdrh       if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
568913449892Sdrh         /* The optimizer is able to deliver rows in group by order so
5690b9bb7c18Sdrh         ** we do not have to sort.  The OP_OpenEphemeral table will be
569113449892Sdrh         ** cancelled later because we still need to use the pKeyInfo
569213449892Sdrh         */
569313449892Sdrh         groupBySort = 0;
569413449892Sdrh       }else{
569513449892Sdrh         /* Rows are coming out in undetermined order.  We have to push
569613449892Sdrh         ** each row into a sorting index, terminate the first loop,
569713449892Sdrh         ** then loop over the sorting index in order to get the output
569813449892Sdrh         ** in sorted order
569913449892Sdrh         */
5700892d3179Sdrh         int regBase;
5701892d3179Sdrh         int regRecord;
5702892d3179Sdrh         int nCol;
5703892d3179Sdrh         int nGroupBy;
5704892d3179Sdrh 
57052ce22453Sdan         explainTempTable(pParse,
5706e8e4af76Sdrh             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
5707e8e4af76Sdrh                     "DISTINCT" : "GROUP BY");
57082ce22453Sdan 
570913449892Sdrh         groupBySort = 1;
5710892d3179Sdrh         nGroupBy = pGroupBy->nExpr;
5711dd23c6bfSdan         nCol = nGroupBy;
5712dd23c6bfSdan         j = nGroupBy;
571313449892Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
5714892d3179Sdrh           if( sAggInfo.aCol[i].iSorterColumn>=j ){
5715892d3179Sdrh             nCol++;
571613449892Sdrh             j++;
571713449892Sdrh           }
5718892d3179Sdrh         }
5719892d3179Sdrh         regBase = sqlite3GetTempRange(pParse, nCol);
5720ceea3321Sdrh         sqlite3ExprCacheClear(pParse);
57215579d59fSdrh         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
5722dd23c6bfSdan         j = nGroupBy;
5723892d3179Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
5724892d3179Sdrh           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
5725892d3179Sdrh           if( pCol->iSorterColumn>=j ){
5726e55cbd72Sdrh             int r1 = j + regBase;
5727ce78bc6eSdrh             sqlite3ExprCodeGetColumnToReg(pParse,
5728ce78bc6eSdrh                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
57296a012f04Sdrh             j++;
5730892d3179Sdrh           }
5731892d3179Sdrh         }
5732892d3179Sdrh         regRecord = sqlite3GetTempReg(pParse);
57331db639ceSdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
57341c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
5735892d3179Sdrh         sqlite3ReleaseTempReg(pParse, regRecord);
5736892d3179Sdrh         sqlite3ReleaseTempRange(pParse, regBase, nCol);
573713449892Sdrh         sqlite3WhereEnd(pWInfo);
57385134d135Sdan         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
57391c9d835dSdrh         sortOut = sqlite3GetTempReg(pParse);
57401c9d835dSdrh         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
57411c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
5742688852abSdrh         VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
574313449892Sdrh         sAggInfo.useSortingIdx = 1;
5744ceea3321Sdrh         sqlite3ExprCacheClear(pParse);
5745374cd78cSdan 
5746374cd78cSdan       }
5747374cd78cSdan 
5748374cd78cSdan       /* If the index or temporary table used by the GROUP BY sort
5749374cd78cSdan       ** will naturally deliver rows in the order required by the ORDER BY
5750374cd78cSdan       ** clause, cancel the ephemeral table open coded earlier.
5751374cd78cSdan       **
5752374cd78cSdan       ** This is an optimization - the correct answer should result regardless.
5753374cd78cSdan       ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
5754374cd78cSdan       ** disable this optimization for testing purposes.  */
5755374cd78cSdan       if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
5756374cd78cSdan        && (groupBySort || sqlite3WhereIsSorted(pWInfo))
5757374cd78cSdan       ){
5758374cd78cSdan         sSort.pOrderBy = 0;
5759374cd78cSdan         sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
576013449892Sdrh       }
576113449892Sdrh 
576213449892Sdrh       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
576313449892Sdrh       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
576413449892Sdrh       ** Then compare the current GROUP BY terms against the GROUP BY terms
576513449892Sdrh       ** from the previous row currently stored in a0, a1, a2...
576613449892Sdrh       */
576713449892Sdrh       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
5768ceea3321Sdrh       sqlite3ExprCacheClear(pParse);
57691c9d835dSdrh       if( groupBySort ){
577038b4149cSdrh         sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
577138b4149cSdrh                           sortOut, sortPTab);
57721c9d835dSdrh       }
577313449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
577413449892Sdrh         if( groupBySort ){
57751c9d835dSdrh           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
577613449892Sdrh         }else{
577713449892Sdrh           sAggInfo.directMode = 1;
57782dcef11bSdrh           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
577913449892Sdrh         }
578013449892Sdrh       }
578116ee60ffSdrh       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
57822ec2fb22Sdrh                           (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
5783728e0f91Sdrh       addr1 = sqlite3VdbeCurrentAddr(v);
5784728e0f91Sdrh       sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
578513449892Sdrh 
578613449892Sdrh       /* Generate code that runs whenever the GROUP BY changes.
5787e00ee6ebSdrh       ** Changes in the GROUP BY are detected by the previous code
578813449892Sdrh       ** block.  If there were no changes, this block is skipped.
578913449892Sdrh       **
579013449892Sdrh       ** This code copies current group by terms in b0,b1,b2,...
579113449892Sdrh       ** over to a0,a1,a2.  It then calls the output subroutine
579213449892Sdrh       ** and resets the aggregate accumulator registers in preparation
579313449892Sdrh       ** for the next GROUP BY batch.
579413449892Sdrh       */
5795b21e7c70Sdrh       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
57962eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
5797d4e70ebdSdrh       VdbeComment((v, "output one row"));
5798688852abSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
5799d4e70ebdSdrh       VdbeComment((v, "check abort flag"));
58002eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
5801d4e70ebdSdrh       VdbeComment((v, "reset accumulator"));
580213449892Sdrh 
580313449892Sdrh       /* Update the aggregate accumulators based on the content of
580413449892Sdrh       ** the current row
580513449892Sdrh       */
5806728e0f91Sdrh       sqlite3VdbeJumpHere(v, addr1);
580713449892Sdrh       updateAccumulator(pParse, &sAggInfo);
58084c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
5809d4e70ebdSdrh       VdbeComment((v, "indicate data in accumulator"));
581013449892Sdrh 
581113449892Sdrh       /* End of the loop
581213449892Sdrh       */
581313449892Sdrh       if( groupBySort ){
58141c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
5815688852abSdrh         VdbeCoverage(v);
581613449892Sdrh       }else{
581713449892Sdrh         sqlite3WhereEnd(pWInfo);
581848f2d3b1Sdrh         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
581913449892Sdrh       }
582013449892Sdrh 
582113449892Sdrh       /* Output the final row of result
582213449892Sdrh       */
58232eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
5824d4e70ebdSdrh       VdbeComment((v, "output final row"));
582513449892Sdrh 
5826d176611bSdrh       /* Jump over the subroutines
5827d176611bSdrh       */
5828076e85f5Sdrh       sqlite3VdbeGoto(v, addrEnd);
5829d176611bSdrh 
5830d176611bSdrh       /* Generate a subroutine that outputs a single row of the result
5831d176611bSdrh       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
5832d176611bSdrh       ** is less than or equal to zero, the subroutine is a no-op.  If
5833d176611bSdrh       ** the processing calls for the query to abort, this subroutine
5834d176611bSdrh       ** increments the iAbortFlag memory location before returning in
5835d176611bSdrh       ** order to signal the caller to abort.
5836d176611bSdrh       */
5837d176611bSdrh       addrSetAbort = sqlite3VdbeCurrentAddr(v);
5838d176611bSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
5839d176611bSdrh       VdbeComment((v, "set abort flag"));
5840d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5841d176611bSdrh       sqlite3VdbeResolveLabel(v, addrOutputRow);
5842d176611bSdrh       addrOutputRow = sqlite3VdbeCurrentAddr(v);
5843d176611bSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
584438b4149cSdrh       VdbeCoverage(v);
5845d176611bSdrh       VdbeComment((v, "Groupby result generator entry point"));
5846d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5847d176611bSdrh       finalizeAggFunctions(pParse, &sAggInfo);
5848d176611bSdrh       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
58492def2f7eSdrh       selectInnerLoop(pParse, p, -1, &sSort,
5850e8e4af76Sdrh                       &sDistinct, pDest,
5851d176611bSdrh                       addrOutputRow+1, addrSetAbort);
5852d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5853d176611bSdrh       VdbeComment((v, "end groupby result generator"));
5854d176611bSdrh 
5855d176611bSdrh       /* Generate a subroutine that will reset the group-by accumulator
5856d176611bSdrh       */
5857d176611bSdrh       sqlite3VdbeResolveLabel(v, addrReset);
5858d176611bSdrh       resetAccumulator(pParse, &sAggInfo);
5859d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regReset);
5860d176611bSdrh 
586143152cf8Sdrh     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
586213449892Sdrh     else {
5863dba0137eSdanielk1977       ExprList *pDel = 0;
5864a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT
5865a5533162Sdanielk1977       Table *pTab;
5866a5533162Sdanielk1977       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
5867a5533162Sdanielk1977         /* If isSimpleCount() returns a pointer to a Table structure, then
5868a5533162Sdanielk1977         ** the SQL statement is of the form:
5869a5533162Sdanielk1977         **
5870a5533162Sdanielk1977         **   SELECT count(*) FROM <tbl>
5871a5533162Sdanielk1977         **
5872a5533162Sdanielk1977         ** where the Table structure returned represents table <tbl>.
5873a5533162Sdanielk1977         **
5874a5533162Sdanielk1977         ** This statement is so common that it is optimized specially. The
5875a5533162Sdanielk1977         ** OP_Count instruction is executed either on the intkey table that
5876a5533162Sdanielk1977         ** contains the data for table <tbl> or on one of its indexes. It
5877a5533162Sdanielk1977         ** is better to execute the op on an index, as indexes are almost
5878a5533162Sdanielk1977         ** always spread across less pages than their corresponding tables.
5879a5533162Sdanielk1977         */
5880a5533162Sdanielk1977         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
5881a5533162Sdanielk1977         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
5882a5533162Sdanielk1977         Index *pIdx;                         /* Iterator variable */
5883a5533162Sdanielk1977         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
5884a5533162Sdanielk1977         Index *pBest = 0;                    /* Best index found so far */
5885a5533162Sdanielk1977         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
5886a9d1ccb9Sdanielk1977 
5887a5533162Sdanielk1977         sqlite3CodeVerifySchema(pParse, iDb);
5888a5533162Sdanielk1977         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
5889a5533162Sdanielk1977 
5890d9e3cad2Sdrh         /* Search for the index that has the lowest scan cost.
5891a5533162Sdanielk1977         **
58923e9548b3Sdrh         ** (2011-04-15) Do not do a full scan of an unordered index.
58933e9548b3Sdrh         **
5894abcc1941Sdrh         ** (2013-10-03) Do not count the entries in a partial index.
58955f33f375Sdrh         **
5896a5533162Sdanielk1977         ** In practice the KeyInfo structure will not be used. It is only
5897a5533162Sdanielk1977         ** passed to keep OP_OpenRead happy.
5898a5533162Sdanielk1977         */
58995c7917e4Sdrh         if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
5900a5533162Sdanielk1977         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
5901d9e3cad2Sdrh           if( pIdx->bUnordered==0
5902e13e9f54Sdrh            && pIdx->szIdxRow<pTab->szTabRow
5903d3037a41Sdrh            && pIdx->pPartIdxWhere==0
5904e13e9f54Sdrh            && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
5905d9e3cad2Sdrh           ){
5906a5533162Sdanielk1977             pBest = pIdx;
5907a5533162Sdanielk1977           }
5908a5533162Sdanielk1977         }
5909d9e3cad2Sdrh         if( pBest ){
5910a5533162Sdanielk1977           iRoot = pBest->tnum;
59112ec2fb22Sdrh           pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
5912a5533162Sdanielk1977         }
5913a5533162Sdanielk1977 
5914a5533162Sdanielk1977         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
5915261c02d9Sdrh         sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
5916a5533162Sdanielk1977         if( pKeyInfo ){
59172ec2fb22Sdrh           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
5918a5533162Sdanielk1977         }
5919a5533162Sdanielk1977         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
5920a5533162Sdanielk1977         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
5921ef7075deSdan         explainSimpleCount(pParse, pTab, pBest);
5922a5533162Sdanielk1977       }else
5923a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */
5924a5533162Sdanielk1977       {
5925738bdcfbSdanielk1977         /* Check if the query is of one of the following forms:
5926738bdcfbSdanielk1977         **
5927738bdcfbSdanielk1977         **   SELECT min(x) FROM ...
5928738bdcfbSdanielk1977         **   SELECT max(x) FROM ...
5929738bdcfbSdanielk1977         **
5930738bdcfbSdanielk1977         ** If it is, then ask the code in where.c to attempt to sort results
5931738bdcfbSdanielk1977         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
5932738bdcfbSdanielk1977         ** If where.c is able to produce results sorted in this order, then
5933738bdcfbSdanielk1977         ** add vdbe code to break out of the processing loop after the
5934738bdcfbSdanielk1977         ** first iteration (since the first iteration of the loop is
5935738bdcfbSdanielk1977         ** guaranteed to operate on the row with the minimum or maximum
5936738bdcfbSdanielk1977         ** value of x, the only row required).
5937738bdcfbSdanielk1977         **
5938738bdcfbSdanielk1977         ** A special flag must be passed to sqlite3WhereBegin() to slightly
593948864df9Smistachkin         ** modify behavior as follows:
5940738bdcfbSdanielk1977         **
5941738bdcfbSdanielk1977         **   + If the query is a "SELECT min(x)", then the loop coded by
5942738bdcfbSdanielk1977         **     where.c should not iterate over any values with a NULL value
5943738bdcfbSdanielk1977         **     for x.
5944738bdcfbSdanielk1977         **
5945738bdcfbSdanielk1977         **   + The optimizer code in where.c (the thing that decides which
5946738bdcfbSdanielk1977         **     index or indices to use) should place a different priority on
5947738bdcfbSdanielk1977         **     satisfying the 'ORDER BY' clause than it does in other cases.
5948738bdcfbSdanielk1977         **     Refer to code and comments in where.c for details.
5949738bdcfbSdanielk1977         */
5950a5533162Sdanielk1977         ExprList *pMinMax = 0;
59514ac391fcSdan         u8 flag = WHERE_ORDERBY_NORMAL;
59524ac391fcSdan 
59534ac391fcSdan         assert( p->pGroupBy==0 );
59544ac391fcSdan         assert( flag==0 );
59554ac391fcSdan         if( p->pHaving==0 ){
59564ac391fcSdan           flag = minMaxQuery(&sAggInfo, &pMinMax);
59574ac391fcSdan         }
59584ac391fcSdan         assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
59594ac391fcSdan 
5960a9d1ccb9Sdanielk1977         if( flag ){
59614ac391fcSdan           pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
59626ab3a2ecSdanielk1977           pDel = pMinMax;
59634a642b60Sdrh           assert( db->mallocFailed || pMinMax!=0 );
59644a642b60Sdrh           if( !db->mallocFailed ){
5965ea678832Sdrh             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
5966a9d1ccb9Sdanielk1977             pMinMax->a[0].pExpr->op = TK_COLUMN;
5967a9d1ccb9Sdanielk1977           }
59681013c932Sdrh         }
5969a9d1ccb9Sdanielk1977 
597013449892Sdrh         /* This case runs if the aggregate has no GROUP BY clause.  The
597113449892Sdrh         ** processing is much simpler since there is only a single row
597213449892Sdrh         ** of output.
597313449892Sdrh         */
597413449892Sdrh         resetAccumulator(pParse, &sAggInfo);
597546ec5b63Sdrh         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax, 0,flag,0);
5976dba0137eSdanielk1977         if( pWInfo==0 ){
5977633e6d57Sdrh           sqlite3ExprListDelete(db, pDel);
5978dba0137eSdanielk1977           goto select_end;
5979dba0137eSdanielk1977         }
598013449892Sdrh         updateAccumulator(pParse, &sAggInfo);
598146c35f9bSdrh         assert( pMinMax==0 || pMinMax->nExpr==1 );
5982ddba0c22Sdrh         if( sqlite3WhereIsOrdered(pWInfo)>0 ){
5983076e85f5Sdrh           sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
5984a5533162Sdanielk1977           VdbeComment((v, "%s() by index",
5985a5533162Sdanielk1977                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
5986a9d1ccb9Sdanielk1977         }
598713449892Sdrh         sqlite3WhereEnd(pWInfo);
598813449892Sdrh         finalizeAggFunctions(pParse, &sAggInfo);
59897a895a80Sdanielk1977       }
59907a895a80Sdanielk1977 
5991079a3072Sdrh       sSort.pOrderBy = 0;
599235573356Sdrh       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
59932def2f7eSdrh       selectInnerLoop(pParse, p, -1, 0, 0,
5994a9671a22Sdrh                       pDest, addrEnd, addrEnd);
5995633e6d57Sdrh       sqlite3ExprListDelete(db, pDel);
599613449892Sdrh     }
599713449892Sdrh     sqlite3VdbeResolveLabel(v, addrEnd);
599813449892Sdrh 
599913449892Sdrh   } /* endif aggregate query */
60002282792aSdrh 
6001e8e4af76Sdrh   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
60022ce22453Sdan     explainTempTable(pParse, "DISTINCT");
60032ce22453Sdan   }
60042ce22453Sdan 
6005cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
6006cce7d176Sdrh   ** and send them to the callback one by one.
6007cce7d176Sdrh   */
6008079a3072Sdrh   if( sSort.pOrderBy ){
600938b4149cSdrh     explainTempTable(pParse,
601038b4149cSdrh                      sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
6011079a3072Sdrh     generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
6012cce7d176Sdrh   }
60136a535340Sdrh 
6014ec7429aeSdrh   /* Jump here to skip this query
6015ec7429aeSdrh   */
6016ec7429aeSdrh   sqlite3VdbeResolveLabel(v, iEnd);
6017ec7429aeSdrh 
60185b1c07e7Sdan   /* The SELECT has been coded. If there is an error in the Parse structure,
60195b1c07e7Sdan   ** set the return code to 1. Otherwise 0. */
60205b1c07e7Sdan   rc = (pParse->nErr>0);
60211d83f052Sdrh 
60221d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
60231d83f052Sdrh   ** successful coding of the SELECT.
60241d83f052Sdrh   */
60251d83f052Sdrh select_end:
602617c0bc0cSdan   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
6027955de52cSdanielk1977 
6028633e6d57Sdrh   sqlite3DbFree(db, sAggInfo.aCol);
6029633e6d57Sdrh   sqlite3DbFree(db, sAggInfo.aFunc);
6030eb9b884cSdrh #if SELECTTRACE_ENABLED
6031eb9b884cSdrh   SELECTTRACE(1,pParse,p,("end processing\n"));
6032eb9b884cSdrh   pParse->nSelectIndent--;
6033eb9b884cSdrh #endif
60341d83f052Sdrh   return rc;
6035cce7d176Sdrh }
6036