xref: /sqlite-3.40.0/src/select.c (revision 54422235)
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 /*
18079a3072Sdrh ** An instance of the following object is used to record information about
19079a3072Sdrh ** how to process the DISTINCT keyword, to simplify passing that information
20079a3072Sdrh ** into the selectInnerLoop() routine.
21eda639e1Sdrh */
22079a3072Sdrh typedef struct DistinctCtx DistinctCtx;
23079a3072Sdrh struct DistinctCtx {
24d6df8550Sdrh   u8 isTnct;      /* 0: Not distinct. 1: DISTICT  2: DISTINCT and ORDER BY */
25079a3072Sdrh   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
26079a3072Sdrh   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
27079a3072Sdrh   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
28079a3072Sdrh };
29079a3072Sdrh 
30079a3072Sdrh /*
31079a3072Sdrh ** An instance of the following object is used to record information about
32079a3072Sdrh ** the ORDER BY (or GROUP BY) clause of query is being coded.
3324e25d32Sdan **
3424e25d32Sdan ** The aDefer[] array is used by the sorter-references optimization. For
3524e25d32Sdan ** example, assuming there is no index that can be used for the ORDER BY,
3624e25d32Sdan ** for the query:
3724e25d32Sdan **
3824e25d32Sdan **     SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10;
3924e25d32Sdan **
4024e25d32Sdan ** it may be more efficient to add just the "a" values to the sorter, and
4124e25d32Sdan ** retrieve the associated "bigblob" values directly from table t1 as the
4224e25d32Sdan ** 10 smallest "a" values are extracted from the sorter.
4324e25d32Sdan **
4424e25d32Sdan ** When the sorter-reference optimization is used, there is one entry in the
4524e25d32Sdan ** aDefer[] array for each database table that may be read as values are
4624e25d32Sdan ** extracted from the sorter.
47079a3072Sdrh */
48079a3072Sdrh typedef struct SortCtx SortCtx;
49079a3072Sdrh struct SortCtx {
50079a3072Sdrh   ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
51079a3072Sdrh   int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
52079a3072Sdrh   int iECursor;         /* Cursor number for the sorter */
53079a3072Sdrh   int regReturn;        /* Register holding block-output return address */
54079a3072Sdrh   int labelBkOut;       /* Start label for the block-output subroutine */
55079a3072Sdrh   int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
56a04a8be2Sdrh   int labelDone;        /* Jump here when done, ex: LIMIT reached */
576ee5a7b4Sdrh   int labelOBLopt;      /* Jump here when sorter is full */
58079a3072Sdrh   u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
5924e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES
6024e25d32Sdan   u8 nDefer;            /* Number of valid entries in aDefer[] */
6124e25d32Sdan   struct DeferredCsr {
6224e25d32Sdan     Table *pTab;        /* Table definition */
6324e25d32Sdan     int iCsr;           /* Cursor number for table */
6424e25d32Sdan     int nKey;           /* Number of PK columns for table pTab (>=1) */
6524e25d32Sdan   } aDefer[4];
6624e25d32Sdan #endif
67bbd4ae5aSdrh   struct RowLoadInfo *pDeferredRowLoad;  /* Deferred row loading info or NULL */
68079a3072Sdrh };
69079a3072Sdrh #define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
70315555caSdrh 
71cce7d176Sdrh /*
72b87fbed5Sdrh ** Delete all the content of a Select structure.  Deallocate the structure
73a9ebfe20Sdrh ** itself depending on the value of bFree
74a9ebfe20Sdrh **
75a9ebfe20Sdrh ** If bFree==1, call sqlite3DbFree() on the p object.
76a9ebfe20Sdrh ** If bFree==0, Leave the first Select object unfreed
77eda639e1Sdrh */
clearSelect(sqlite3 * db,Select * p,int bFree)78b87fbed5Sdrh static void clearSelect(sqlite3 *db, Select *p, int bFree){
7941ce47c4Sdrh   assert( db!=0 );
80b87fbed5Sdrh   while( p ){
81b87fbed5Sdrh     Select *pPrior = p->pPrior;
82633e6d57Sdrh     sqlite3ExprListDelete(db, p->pEList);
83633e6d57Sdrh     sqlite3SrcListDelete(db, p->pSrc);
84633e6d57Sdrh     sqlite3ExprDelete(db, p->pWhere);
85633e6d57Sdrh     sqlite3ExprListDelete(db, p->pGroupBy);
86633e6d57Sdrh     sqlite3ExprDelete(db, p->pHaving);
87633e6d57Sdrh     sqlite3ExprListDelete(db, p->pOrderBy);
88633e6d57Sdrh     sqlite3ExprDelete(db, p->pLimit);
8950f9f6c6Sdan     if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
9067a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
91e3bf632cSdan     if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){
92e3bf632cSdan       sqlite3WindowListDelete(db, p->pWinDefn);
93e3bf632cSdan     }
9450f9f6c6Sdan     while( p->pWin ){
9550f9f6c6Sdan       assert( p->pWin->ppThis==&p->pWin );
9650f9f6c6Sdan       sqlite3WindowUnlinkFromSelect(p->pWin);
9750f9f6c6Sdan     }
9867a9b8edSdan #endif
9941ce47c4Sdrh     if( bFree ) sqlite3DbNNFreeNN(db, p);
100b87fbed5Sdrh     p = pPrior;
101b87fbed5Sdrh     bFree = 1;
102b87fbed5Sdrh   }
103eda639e1Sdrh }
104eda639e1Sdrh 
1051013c932Sdrh /*
1061013c932Sdrh ** Initialize a SelectDest structure.
1071013c932Sdrh */
sqlite3SelectDestInit(SelectDest * pDest,int eDest,int iParm)1081013c932Sdrh void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
109ea678832Sdrh   pDest->eDest = (u8)eDest;
1102b596da8Sdrh   pDest->iSDParm = iParm;
1119ed322d6Sdan   pDest->iSDParm2 = 0;
11271c57db0Sdan   pDest->zAffSdst = 0;
1132b596da8Sdrh   pDest->iSdst = 0;
1142b596da8Sdrh   pDest->nSdst = 0;
1151013c932Sdrh }
1161013c932Sdrh 
117eda639e1Sdrh 
118eda639e1Sdrh /*
1199bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that
1209bb61fe7Sdrh ** structure.
121cce7d176Sdrh */
sqlite3SelectNew(Parse * pParse,ExprList * pEList,SrcList * pSrc,Expr * pWhere,ExprList * pGroupBy,Expr * pHaving,ExprList * pOrderBy,u32 selFlags,Expr * pLimit)1224adee20fSdanielk1977 Select *sqlite3SelectNew(
12317435752Sdrh   Parse *pParse,        /* Parsing context */
124daffd0e5Sdrh   ExprList *pEList,     /* which columns to include in the result */
125ad3cab52Sdrh   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
126daffd0e5Sdrh   Expr *pWhere,         /* the WHERE clause */
127daffd0e5Sdrh   ExprList *pGroupBy,   /* the GROUP BY clause */
128daffd0e5Sdrh   Expr *pHaving,        /* the HAVING clause */
129daffd0e5Sdrh   ExprList *pOrderBy,   /* the ORDER BY clause */
130c3489bbfSdrh   u32 selFlags,         /* Flag parameters, such as SF_Distinct */
1318c0833fbSdrh   Expr *pLimit          /* LIMIT value.  NULL means not used */
1329bb61fe7Sdrh ){
133d3bf7661Sdrh   Select *pNew, *pAllocated;
134eda639e1Sdrh   Select standin;
135d3bf7661Sdrh   pAllocated = pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
136daffd0e5Sdrh   if( pNew==0 ){
137ef90a6b8Sdrh     assert( pParse->db->mallocFailed );
138eda639e1Sdrh     pNew = &standin;
139eda639e1Sdrh   }
140b733d037Sdrh   if( pEList==0 ){
1413d240d21Sdrh     pEList = sqlite3ExprListAppend(pParse, 0,
1423d240d21Sdrh                                    sqlite3Expr(pParse->db,TK_ASTERISK,0));
143b733d037Sdrh   }
1449bb61fe7Sdrh   pNew->pEList = pEList;
145ca3862dcSdrh   pNew->op = TK_SELECT;
146ca3862dcSdrh   pNew->selFlags = selFlags;
147ca3862dcSdrh   pNew->iLimit = 0;
148ca3862dcSdrh   pNew->iOffset = 0;
149fef37760Sdrh   pNew->selId = ++pParse->nSelect;
150ca3862dcSdrh   pNew->addrOpenEphm[0] = -1;
151ca3862dcSdrh   pNew->addrOpenEphm[1] = -1;
152ca3862dcSdrh   pNew->nSelectRow = 0;
153ef90a6b8Sdrh   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
1549bb61fe7Sdrh   pNew->pSrc = pSrc;
1559bb61fe7Sdrh   pNew->pWhere = pWhere;
1569bb61fe7Sdrh   pNew->pGroupBy = pGroupBy;
1579bb61fe7Sdrh   pNew->pHaving = pHaving;
1589bb61fe7Sdrh   pNew->pOrderBy = pOrderBy;
159ca3862dcSdrh   pNew->pPrior = 0;
160ca3862dcSdrh   pNew->pNext = 0;
161a2dc3b1aSdanielk1977   pNew->pLimit = pLimit;
162ca3862dcSdrh   pNew->pWith = 0;
16367a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
16486fb6e17Sdan   pNew->pWin = 0;
165e3bf632cSdan   pNew->pWinDefn = 0;
16667a9b8edSdan #endif
167ef90a6b8Sdrh   if( pParse->db->mallocFailed ) {
168ef90a6b8Sdrh     clearSelect(pParse->db, pNew, pNew!=&standin);
169d3bf7661Sdrh     pAllocated = 0;
170a464c234Sdrh   }else{
171a464c234Sdrh     assert( pNew->pSrc!=0 || pParse->nErr>0 );
172daffd0e5Sdrh   }
173d3bf7661Sdrh   return pAllocated;
1749bb61fe7Sdrh }
1759bb61fe7Sdrh 
176eb9b884cSdrh 
1779bb61fe7Sdrh /*
178eda639e1Sdrh ** Delete the given Select structure and all of its substructures.
179eda639e1Sdrh */
sqlite3SelectDelete(sqlite3 * db,Select * p)180633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){
1818906a4b8Sdrh   if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
182eda639e1Sdrh }
183eda639e1Sdrh 
184eda639e1Sdrh /*
185d227a291Sdrh ** Return a pointer to the right-most SELECT statement in a compound.
186d227a291Sdrh */
findRightmost(Select * p)187d227a291Sdrh static Select *findRightmost(Select *p){
188d227a291Sdrh   while( p->pNext ) p = p->pNext;
189d227a291Sdrh   return p;
1909bb61fe7Sdrh }
1919bb61fe7Sdrh 
1929bb61fe7Sdrh /*
193f7b5496eSdrh ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
19401f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
19501f3f253Sdrh ** in terms of the following bit values:
19601f3f253Sdrh **
19701f3f253Sdrh **     JT_INNER
1983dec223cSdrh **     JT_CROSS
19901f3f253Sdrh **     JT_OUTER
20001f3f253Sdrh **     JT_NATURAL
20101f3f253Sdrh **     JT_LEFT
20201f3f253Sdrh **     JT_RIGHT
20301f3f253Sdrh **
20401f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
20501f3f253Sdrh **
20601f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
20701f3f253Sdrh ** a join type, but put an error in the pParse structure.
20881a23623Sdrh **
20981a23623Sdrh ** These are the valid join types:
21081a23623Sdrh **
21181a23623Sdrh **
21281a23623Sdrh **      pA       pB       pC               Return Value
21381a23623Sdrh **     -------  -----    -----             ------------
21481a23623Sdrh **     CROSS      -        -                 JT_CROSS
21581a23623Sdrh **     INNER      -        -                 JT_INNER
21681a23623Sdrh **     LEFT       -        -                 JT_LEFT|JT_OUTER
21781a23623Sdrh **     LEFT     OUTER      -                 JT_LEFT|JT_OUTER
21881a23623Sdrh **     RIGHT      -        -                 JT_RIGHT|JT_OUTER
21981a23623Sdrh **     RIGHT    OUTER      -                 JT_RIGHT|JT_OUTER
22081a23623Sdrh **     FULL       -        -                 JT_LEFT|JT_RIGHT|JT_OUTER
22181a23623Sdrh **     FULL     OUTER      -                 JT_LEFT|JT_RIGHT|JT_OUTER
22281a23623Sdrh **     NATURAL  INNER      -                 JT_NATURAL|JT_INNER
22381a23623Sdrh **     NATURAL  LEFT       -                 JT_NATURAL|JT_LEFT|JT_OUTER
22481a23623Sdrh **     NATURAL  LEFT     OUTER               JT_NATURAL|JT_LEFT|JT_OUTER
22581a23623Sdrh **     NATURAL  RIGHT      -                 JT_NATURAL|JT_RIGHT|JT_OUTER
22681a23623Sdrh **     NATURAL  RIGHT    OUTER               JT_NATURAL|JT_RIGHT|JT_OUTER
22781a23623Sdrh **     NATURAL  FULL       -                 JT_NATURAL|JT_LEFT|JT_RIGHT
22881a23623Sdrh **     NATURAL  FULL     OUTER               JT_NATRUAL|JT_LEFT|JT_RIGHT
22981a23623Sdrh **
23081a23623Sdrh ** To preserve historical compatibly, SQLite also accepts a variety
23181a23623Sdrh ** of other non-standard and in many cases non-sensical join types.
23281a23623Sdrh ** This routine makes as much sense at it can from the nonsense join
23381a23623Sdrh ** type and returns a result.  Examples of accepted nonsense join types
23481a23623Sdrh ** include but are not limited to:
23581a23623Sdrh **
23681a23623Sdrh **          INNER CROSS JOIN        ->   same as JOIN
23781a23623Sdrh **          NATURAL CROSS JOIN      ->   same as NATURAL JOIN
23881a23623Sdrh **          OUTER LEFT JOIN         ->   same as LEFT JOIN
23981a23623Sdrh **          LEFT NATURAL JOIN       ->   same as NATURAL LEFT JOIN
24081a23623Sdrh **          LEFT RIGHT JOIN         ->   same as FULL JOIN
24181a23623Sdrh **          RIGHT OUTER FULL JOIN   ->   same as FULL JOIN
24281a23623Sdrh **          CROSS CROSS CROSS JOIN  ->   same as JOIN
24381a23623Sdrh **
24481a23623Sdrh ** The only restrictions on the join type name are:
24581a23623Sdrh **
24681a23623Sdrh **    *   "INNER" cannot appear together with "OUTER", "LEFT", "RIGHT",
24781a23623Sdrh **        or "FULL".
24881a23623Sdrh **
24981a23623Sdrh **    *   "CROSS" cannot appear together with "OUTER", "LEFT", "RIGHT,
25081a23623Sdrh **        or "FULL".
25181a23623Sdrh **
25281a23623Sdrh **    *   If "OUTER" is present then there must also be one of
25381a23623Sdrh **        "LEFT", "RIGHT", or "FULL"
25401f3f253Sdrh */
sqlite3JoinType(Parse * pParse,Token * pA,Token * pB,Token * pC)2554adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
25601f3f253Sdrh   int jointype = 0;
25701f3f253Sdrh   Token *apAll[3];
25801f3f253Sdrh   Token *p;
259373cc2ddSdrh                              /*   0123456789 123456789 123456789 123 */
260373cc2ddSdrh   static const char zKeyText[] = "naturaleftouterightfullinnercross";
2615719628aSdrh   static const struct {
262373cc2ddSdrh     u8 i;        /* Beginning of keyword text in zKeyText[] */
263373cc2ddSdrh     u8 nChar;    /* Length of the keyword in characters */
264373cc2ddSdrh     u8 code;     /* Join type mask */
265373cc2ddSdrh   } aKeyword[] = {
26681a23623Sdrh     /* (0) natural */ { 0,  7, JT_NATURAL                },
26781a23623Sdrh     /* (1) left    */ { 6,  4, JT_LEFT|JT_OUTER          },
26881a23623Sdrh     /* (2) outer   */ { 10, 5, JT_OUTER                  },
26981a23623Sdrh     /* (3) right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
27081a23623Sdrh     /* (4) full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
27181a23623Sdrh     /* (5) inner   */ { 23, 5, JT_INNER                  },
27281a23623Sdrh     /* (6) cross   */ { 28, 5, JT_INNER|JT_CROSS         },
27301f3f253Sdrh   };
27401f3f253Sdrh   int i, j;
27501f3f253Sdrh   apAll[0] = pA;
27601f3f253Sdrh   apAll[1] = pB;
27701f3f253Sdrh   apAll[2] = pC;
278195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
27901f3f253Sdrh     p = apAll[i];
280373cc2ddSdrh     for(j=0; j<ArraySize(aKeyword); j++){
281373cc2ddSdrh       if( p->n==aKeyword[j].nChar
282373cc2ddSdrh           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
283373cc2ddSdrh         jointype |= aKeyword[j].code;
28401f3f253Sdrh         break;
28501f3f253Sdrh       }
28601f3f253Sdrh     }
287373cc2ddSdrh     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
288373cc2ddSdrh     if( j>=ArraySize(aKeyword) ){
28901f3f253Sdrh       jointype |= JT_ERROR;
29001f3f253Sdrh       break;
29101f3f253Sdrh     }
29201f3f253Sdrh   }
293ad2d8307Sdrh   if(
294ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
29581a23623Sdrh      (jointype & JT_ERROR)!=0 ||
29681a23623Sdrh      (jointype & (JT_OUTER|JT_LEFT|JT_RIGHT))==JT_OUTER
297ad2d8307Sdrh   ){
29881a23623Sdrh     const char *zSp1 = " ";
29981a23623Sdrh     const char *zSp2 = " ";
30081a23623Sdrh     if( pB==0 ){ zSp1++; }
30181a23623Sdrh     if( pC==0 ){ zSp2++; }
3020879d5f9Sdrh     sqlite3ErrorMsg(pParse, "unknown join type: "
30381a23623Sdrh        "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
30401f3f253Sdrh     jointype = JT_INNER;
30501f3f253Sdrh   }
30601f3f253Sdrh   return jointype;
30701f3f253Sdrh }
30801f3f253Sdrh 
30901f3f253Sdrh /*
310ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
311ad2d8307Sdrh ** is not contained in the table.
312ad2d8307Sdrh */
sqlite3ColumnIndex(Table * pTab,const char * zCol)3136e6d9833Sdan int sqlite3ColumnIndex(Table *pTab, const char *zCol){
314ad2d8307Sdrh   int i;
315a192807cSdrh   u8 h = sqlite3StrIHash(zCol);
316a192807cSdrh   Column *pCol;
317a192807cSdrh   for(pCol=pTab->aCol, i=0; i<pTab->nCol; pCol++, i++){
318cf9d36d1Sdrh     if( pCol->hName==h && sqlite3StrICmp(pCol->zCnName, zCol)==0 ) return i;
319ad2d8307Sdrh   }
320ad2d8307Sdrh   return -1;
321ad2d8307Sdrh }
322ad2d8307Sdrh 
323ad2d8307Sdrh /*
324815b782eSdrh ** Mark a subquery result column as having been used.
325815b782eSdrh */
sqlite3SrcItemColumnUsed(SrcItem * pItem,int iCol)326815b782eSdrh void sqlite3SrcItemColumnUsed(SrcItem *pItem, int iCol){
327815b782eSdrh   assert( pItem!=0 );
32807fae32dSmistachkin   assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem->pSelect) );
329815b782eSdrh   if( pItem->fg.isNestedFrom ){
330815b782eSdrh     ExprList *pResults;
331815b782eSdrh     assert( pItem->pSelect!=0 );
332815b782eSdrh     pResults = pItem->pSelect->pEList;
333815b782eSdrh     assert( pResults!=0 );
334815b782eSdrh     assert( iCol>=0 && iCol<pResults->nExpr );
335d88fd539Sdrh     pResults->a[iCol].fg.bUsed = 1;
336815b782eSdrh   }
337815b782eSdrh }
338815b782eSdrh 
339815b782eSdrh /*
340fe146997Sdrh ** Search the tables iStart..iEnd (inclusive) in pSrc, looking for a
341fe146997Sdrh ** table that has a column named zCol.  The search is left-to-right.
342fe146997Sdrh ** The first match found is returned.
34322c4bc89Sdrh **
3442179b434Sdrh ** When found, set *piTab and *piCol to the table index and column index
3452179b434Sdrh ** of the matching column and return TRUE.
3462179b434Sdrh **
3472179b434Sdrh ** If not found, return FALSE.
3482179b434Sdrh */
tableAndColumnIndex(SrcList * pSrc,int iStart,int iEnd,const char * zCol,int * piTab,int * piCol,int bIgnoreHidden)3492179b434Sdrh static int tableAndColumnIndex(
3502179b434Sdrh   SrcList *pSrc,       /* Array of tables to search */
351fe146997Sdrh   int iStart,          /* First member of pSrc->a[] to check */
352fe146997Sdrh   int iEnd,            /* Last member of pSrc->a[] to check */
3532179b434Sdrh   const char *zCol,    /* Name of the column we are looking for */
3542179b434Sdrh   int *piTab,          /* Write index of pSrc->a[] here */
3559d41af23Sdan   int *piCol,          /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
356fe146997Sdrh   int bIgnoreHidden    /* Ignore hidden columns */
3572179b434Sdrh ){
3582179b434Sdrh   int i;               /* For looping over tables in pSrc */
3592179b434Sdrh   int iCol;            /* Index of column matching zCol */
36022c4bc89Sdrh 
361fe146997Sdrh   assert( iEnd<pSrc->nSrc );
362fe146997Sdrh   assert( iStart>=0 );
3632179b434Sdrh   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
364fe146997Sdrh 
365fe146997Sdrh   for(i=iStart; i<=iEnd; i++){
3666e6d9833Sdan     iCol = sqlite3ColumnIndex(pSrc->a[i].pTab, zCol);
3679d41af23Sdan     if( iCol>=0
3689d41af23Sdan      && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pTab->aCol[iCol])==0)
3699d41af23Sdan     ){
3702179b434Sdrh       if( piTab ){
371815b782eSdrh         sqlite3SrcItemColumnUsed(&pSrc->a[i], iCol);
3722179b434Sdrh         *piTab = i;
3732179b434Sdrh         *piCol = iCol;
3742179b434Sdrh       }
375fe146997Sdrh       return 1;
3762179b434Sdrh     }
3772179b434Sdrh   }
378fe146997Sdrh   return 0;
379ad2d8307Sdrh }
380ad2d8307Sdrh 
381ad2d8307Sdrh /*
38267a99dbeSdrh ** Set the EP_OuterON property on all terms of the given expression.
383d1985262Sdrh ** And set the Expr.w.iJoin to iTable for every term in the
38422d6a53aSdrh ** expression.
3851cc093c2Sdrh **
38667a99dbeSdrh ** The EP_OuterON property is used on terms of an expression to tell
387b77c07a7Sdrh ** the OUTER JOIN processing logic that this term is part of the
3881f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
3891f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
3901f16230bSdrh ** WHERE clause during join processing but we need to remember that they
3911f16230bSdrh ** originated in the ON or USING clause.
39222d6a53aSdrh **
393d1985262Sdrh ** The Expr.w.iJoin tells the WHERE clause processing that the
394d1985262Sdrh ** expression depends on table w.iJoin even if that table is not
39522d6a53aSdrh ** explicitly mentioned in the expression.  That information is needed
39622d6a53aSdrh ** for cases like this:
39722d6a53aSdrh **
39822d6a53aSdrh **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
39922d6a53aSdrh **
40022d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5
40122d6a53aSdrh ** term until after the t2 loop of the join.  In that way, a
40222d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
40322d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately
40422d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in
40522d6a53aSdrh ** the output, which is incorrect.
4061cc093c2Sdrh */
sqlite3SetJoinExpr(Expr * p,int iTable,u32 joinFlag)4073a6e4c59Sdrh void sqlite3SetJoinExpr(Expr *p, int iTable, u32 joinFlag){
40867a99dbeSdrh   assert( joinFlag==EP_OuterON || joinFlag==EP_InnerON );
4091cc093c2Sdrh   while( p ){
4103a6e4c59Sdrh     ExprSetProperty(p, joinFlag);
411c5cd1249Sdrh     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
412ebb6a65dSdrh     ExprSetVVAProperty(p, EP_NoReduce);
413d1985262Sdrh     p->w.iJoin = iTable;
414a4eeccdfSdrh     if( p->op==TK_FUNCTION ){
415a4eeccdfSdrh       assert( ExprUseXList(p) );
416a4eeccdfSdrh       if( p->x.pList ){
417606f2344Sdrh         int i;
418606f2344Sdrh         for(i=0; i<p->x.pList->nExpr; i++){
4193a6e4c59Sdrh           sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable, joinFlag);
420606f2344Sdrh         }
421606f2344Sdrh       }
422a4eeccdfSdrh     }
4233a6e4c59Sdrh     sqlite3SetJoinExpr(p->pLeft, iTable, joinFlag);
4241cc093c2Sdrh     p = p->pRight;
4251cc093c2Sdrh   }
4261cc093c2Sdrh }
4271cc093c2Sdrh 
428d7480403Sdrh /* Undo the work of sqlite3SetJoinExpr().  This is used when a LEFT JOIN
429d7480403Sdrh ** is simplified into an ordinary JOIN, and when an ON expression is
430d7480403Sdrh ** "pushed down" into the WHERE clause of a subquery.
4312589787cSdrh **
432d7480403Sdrh ** Convert every term that is marked with EP_OuterON and w.iJoin==iTable into
433d7480403Sdrh ** an ordinary term that omits the EP_OuterON mark.  Or if iTable<0, then
434d7480403Sdrh ** just clear every EP_OuterON and EP_InnerON mark from the expression tree.
43592d1afbaSdrh **
43692d1afbaSdrh ** If nullable is true, that means that Expr p might evaluate to NULL even
43792d1afbaSdrh ** if it is a reference to a NOT NULL column.  This can happen, for example,
43892d1afbaSdrh ** if the table that p references is on the left side of a RIGHT JOIN.
43992d1afbaSdrh ** If nullable is true, then take care to not remove the EP_CanBeNull bit.
44092d1afbaSdrh ** See forum thread https://sqlite.org/forum/forumpost/b40696f50145d21c
4412589787cSdrh */
unsetJoinExpr(Expr * p,int iTable,int nullable)44292d1afbaSdrh static void unsetJoinExpr(Expr *p, int iTable, int nullable){
4432589787cSdrh   while( p ){
444d7480403Sdrh     if( iTable<0 || (ExprHasProperty(p, EP_OuterON) && p->w.iJoin==iTable) ){
445d7480403Sdrh       ExprClearProperty(p, EP_OuterON|EP_InnerON);
446d7480403Sdrh       if( iTable>=0 ) ExprSetProperty(p, EP_InnerON);
4472589787cSdrh     }
44892d1afbaSdrh     if( p->op==TK_COLUMN && p->iTable==iTable && !nullable ){
4498ddf6862Sdan       ExprClearProperty(p, EP_CanBeNull);
4508ddf6862Sdan     }
451a4eeccdfSdrh     if( p->op==TK_FUNCTION ){
452a4eeccdfSdrh       assert( ExprUseXList(p) );
453a4eeccdfSdrh       if( p->x.pList ){
4542589787cSdrh         int i;
4552589787cSdrh         for(i=0; i<p->x.pList->nExpr; i++){
45692d1afbaSdrh           unsetJoinExpr(p->x.pList->a[i].pExpr, iTable, nullable);
4572589787cSdrh         }
4582589787cSdrh       }
459a4eeccdfSdrh     }
46092d1afbaSdrh     unsetJoinExpr(p->pLeft, iTable, nullable);
4612589787cSdrh     p = p->pRight;
4622589787cSdrh   }
4632589787cSdrh }
4642589787cSdrh 
4651cc093c2Sdrh /*
466ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
467bc656e22Sdrh **
468bc656e22Sdrh **   *  A NATURAL join is converted into a USING join.  After that, we
469bc656e22Sdrh **      do not need to be concerned with NATURAL joins and we only have
470bc656e22Sdrh **      think about USING joins.
471bc656e22Sdrh **
472bc656e22Sdrh **   *  ON and USING clauses result in extra terms being added to the
473bc656e22Sdrh **      WHERE clause to enforce the specified constraints.  The extra
47467a99dbeSdrh **      WHERE clause terms will be tagged with EP_OuterON or
47567a99dbeSdrh **      EP_InnerON so that we know that they originated in ON/USING.
476ad2d8307Sdrh **
47791bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure.
47891bb0eedSdrh ** The left most table is the first entry in Select.pSrc.  The right-most
47991bb0eedSdrh ** table is the last entry.  The join operator is held in the entry to
480bc656e22Sdrh ** the right.  Thus entry 1 contains the join operator for the join between
48191bb0eedSdrh ** entries 0 and 1.  Any ON or USING clauses associated with the join are
482bc656e22Sdrh ** also attached to the right entry.
48391bb0eedSdrh **
484ad2d8307Sdrh ** This routine returns the number of errors encountered.
485ad2d8307Sdrh */
sqlite3ProcessJoin(Parse * pParse,Select * p)486358424aeSdrh static int sqlite3ProcessJoin(Parse *pParse, Select *p){
48791bb0eedSdrh   SrcList *pSrc;                  /* All tables in the FROM clause */
48891bb0eedSdrh   int i, j;                       /* Loop counters */
4897601294aSdrh   SrcItem *pLeft;                 /* Left table being joined */
4907601294aSdrh   SrcItem *pRight;                /* Right table being joined */
491ad2d8307Sdrh 
49291bb0eedSdrh   pSrc = p->pSrc;
49391bb0eedSdrh   pLeft = &pSrc->a[0];
49491bb0eedSdrh   pRight = &pLeft[1];
49591bb0eedSdrh   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
49691bb0eedSdrh     Table *pRightTab = pRight->pTab;
4973a6e4c59Sdrh     u32 joinType;
49891bb0eedSdrh 
499ce2c482eSdrh     if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
50067a99dbeSdrh     joinType = (pRight->fg.jointype & JT_OUTER)!=0 ? EP_OuterON : EP_InnerON;
501ad2d8307Sdrh 
50222c4bc89Sdrh     /* If this is a NATURAL join, synthesize an approprate USING clause
50322c4bc89Sdrh     ** to specify which columns should be joined.
504ad2d8307Sdrh     */
5058a48b9c0Sdrh     if( pRight->fg.jointype & JT_NATURAL ){
50622c4bc89Sdrh       IdList *pUsing = 0;
507d44f8b23Sdrh       if( pRight->fg.isUsing || pRight->u3.pOn ){
5084adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
509ad2d8307Sdrh            "an ON or USING clause", 0);
510ad2d8307Sdrh         return 1;
511ad2d8307Sdrh       }
5122179b434Sdrh       for(j=0; j<pRightTab->nCol; j++){
5132179b434Sdrh         char *zName;   /* Name of column in the right table */
5142179b434Sdrh 
5159d41af23Sdan         if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue;
516cf9d36d1Sdrh         zName = pRightTab->aCol[j].zCnName;
517fe146997Sdrh         if( tableAndColumnIndex(pSrc, 0, i, zName, 0, 0, 1) ){
518d0453f7eSdrh           pUsing = sqlite3IdListAppend(pParse, pUsing, 0);
519d0453f7eSdrh           if( pUsing ){
520d0453f7eSdrh             assert( pUsing->nId>0 );
521d0453f7eSdrh             assert( pUsing->a[pUsing->nId-1].zName==0 );
522d0453f7eSdrh             pUsing->a[pUsing->nId-1].zName = sqlite3DbStrDup(pParse->db, zName);
523d0453f7eSdrh           }
524ad2d8307Sdrh         }
525ad2d8307Sdrh       }
52622c4bc89Sdrh       if( pUsing ){
52722c4bc89Sdrh         pRight->fg.isUsing = 1;
5284ce7bf91Sdrh         pRight->fg.isSynthUsing = 1;
52922c4bc89Sdrh         pRight->u3.pUsing = pUsing;
53022c4bc89Sdrh       }
531abf86bd3Sdrh       if( pParse->nErr ) return 1;
532ad2d8307Sdrh     }
533ad2d8307Sdrh 
534ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
535ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
536ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
537ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
538ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
539ad2d8307Sdrh     ** not contained in both tables to be joined.
540ad2d8307Sdrh     */
541d44f8b23Sdrh     if( pRight->fg.isUsing ){
542d44f8b23Sdrh       IdList *pList = pRight->u3.pUsing;
543fe146997Sdrh       sqlite3 *db = pParse->db;
544d44f8b23Sdrh       assert( pList!=0 );
545ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
5462179b434Sdrh         char *zName;     /* Name of the term in the USING clause */
5472179b434Sdrh         int iLeft;       /* Table on the left with matching column name */
5482179b434Sdrh         int iLeftCol;    /* Column number of matching column on the left */
5492179b434Sdrh         int iRightCol;   /* Column number of matching column on the right */
550fe146997Sdrh         Expr *pE1;       /* Reference to the column on the LEFT of the join */
551fe146997Sdrh         Expr *pE2;       /* Reference to the column on the RIGHT of the join */
552fe146997Sdrh         Expr *pEq;       /* Equality constraint.  pE1 == pE2 */
5532179b434Sdrh 
5542179b434Sdrh         zName = pList->a[j].zName;
5556e6d9833Sdan         iRightCol = sqlite3ColumnIndex(pRightTab, zName);
5562179b434Sdrh         if( iRightCol<0
557fe146997Sdrh          || tableAndColumnIndex(pSrc, 0, i, zName, &iLeft, &iLeftCol,
558fe146997Sdrh                                 pRight->fg.isSynthUsing)==0
5592179b434Sdrh         ){
5604adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
56191bb0eedSdrh             "not present in both tables", zName);
562ad2d8307Sdrh           return 1;
563ad2d8307Sdrh         }
564fe146997Sdrh         pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iLeftCol);
56522b410d8Sdrh         sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol);
566fe146997Sdrh         if( (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
567fe146997Sdrh           /* This branch runs if the query contains one or more RIGHT or FULL
568fe146997Sdrh           ** JOINs.  If only a single table on the left side of this join
569bc656e22Sdrh           ** contains the zName column, then this branch is a no-op.
570bc656e22Sdrh           ** But if there are two or more tables on the left side
571fe146997Sdrh           ** of the join, construct a coalesce() function that gathers all
572fe146997Sdrh           ** such tables.  Raise an error if more than one of those references
573fe146997Sdrh           ** to zName is not also within a prior USING clause.
574fe146997Sdrh           **
575fe146997Sdrh           ** We really ought to raise an error if there are two or more
576fe146997Sdrh           ** non-USING references to zName on the left of an INNER or LEFT
577fe146997Sdrh           ** JOIN.  But older versions of SQLite do not do that, so we avoid
578fe146997Sdrh           ** adding a new error so as to not break legacy applications.
579052953a4Sdrh           */
580fe146997Sdrh           ExprList *pFuncArgs = 0;   /* Arguments to the coalesce() */
581052953a4Sdrh           static const Token tkCoalesce = { "coalesce", 8 };
582fe146997Sdrh           while( tableAndColumnIndex(pSrc, iLeft+1, i, zName, &iLeft, &iLeftCol,
583fe146997Sdrh                                      pRight->fg.isSynthUsing)!=0 ){
584fe146997Sdrh             if( pSrc->a[iLeft].fg.isUsing==0
585fe146997Sdrh              || sqlite3IdListIndex(pSrc->a[iLeft].u3.pUsing, zName)<0
586fe146997Sdrh             ){
587fe146997Sdrh               sqlite3ErrorMsg(pParse, "ambiguous reference to %s in USING()",
588fe146997Sdrh                               zName);
589fe146997Sdrh               break;
590052953a4Sdrh             }
591fe146997Sdrh             pFuncArgs = sqlite3ExprListAppend(pParse, pFuncArgs, pE1);
592fe146997Sdrh             pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iLeftCol);
59322b410d8Sdrh             sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol);
594fe146997Sdrh           }
595fe146997Sdrh           if( pFuncArgs ){
596fe146997Sdrh             pFuncArgs = sqlite3ExprListAppend(pParse, pFuncArgs, pE1);
597fe146997Sdrh             pE1 = sqlite3ExprFunction(pParse, pFuncArgs, &tkCoalesce, 0);
598fe146997Sdrh           }
599fe146997Sdrh         }
600052953a4Sdrh         pE2 = sqlite3CreateColumnExpr(db, pSrc, i+1, iRightCol);
601815b782eSdrh         sqlite3SrcItemColumnUsed(pRight, iRightCol);
602fe146997Sdrh         pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
603052953a4Sdrh         assert( pE2!=0 || pEq==0 );
604052953a4Sdrh         if( pEq ){
605052953a4Sdrh           ExprSetProperty(pEq, joinType);
606052953a4Sdrh           assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
607052953a4Sdrh           ExprSetVVAProperty(pEq, EP_NoReduce);
608052953a4Sdrh           pEq->w.iJoin = pE2->iTable;
609052953a4Sdrh         }
610052953a4Sdrh         p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pEq);
611052953a4Sdrh       }
612ad2d8307Sdrh     }
613d44f8b23Sdrh 
614d44f8b23Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
615d44f8b23Sdrh     ** an AND operator.
616d44f8b23Sdrh     */
617d44f8b23Sdrh     else if( pRight->u3.pOn ){
6183a6e4c59Sdrh       sqlite3SetJoinExpr(pRight->u3.pOn, pRight->iCursor, joinType);
619d44f8b23Sdrh       p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->u3.pOn);
620d44f8b23Sdrh       pRight->u3.pOn = 0;
6215c118e39Sdrh       pRight->fg.isOn = 1;
622d44f8b23Sdrh     }
623ad2d8307Sdrh   }
624ad2d8307Sdrh   return 0;
625ad2d8307Sdrh }
626ad2d8307Sdrh 
627ad2d8307Sdrh /*
628bbd4ae5aSdrh ** An instance of this object holds information (beyond pParse and pSelect)
629bbd4ae5aSdrh ** needed to load the next result row that is to be added to the sorter.
630bbd4ae5aSdrh */
631bbd4ae5aSdrh typedef struct RowLoadInfo RowLoadInfo;
632bbd4ae5aSdrh struct RowLoadInfo {
633bbd4ae5aSdrh   int regResult;               /* Store results in array of registers here */
634bbd4ae5aSdrh   u8 ecelFlags;                /* Flag argument to ExprCodeExprList() */
635bbd4ae5aSdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES
636bbd4ae5aSdrh   ExprList *pExtra;            /* Extra columns needed by sorter refs */
637bbd4ae5aSdrh   int regExtraResult;          /* Where to load the extra columns */
638bbd4ae5aSdrh #endif
639bbd4ae5aSdrh };
640bbd4ae5aSdrh 
641bbd4ae5aSdrh /*
642bbd4ae5aSdrh ** This routine does the work of loading query data into an array of
643bbd4ae5aSdrh ** registers so that it can be added to the sorter.
644bbd4ae5aSdrh */
innerLoopLoadRow(Parse * pParse,Select * pSelect,RowLoadInfo * pInfo)645bbd4ae5aSdrh static void innerLoopLoadRow(
646bbd4ae5aSdrh   Parse *pParse,             /* Statement under construction */
647bbd4ae5aSdrh   Select *pSelect,           /* The query being coded */
648bbd4ae5aSdrh   RowLoadInfo *pInfo         /* Info needed to complete the row load */
649bbd4ae5aSdrh ){
650bbd4ae5aSdrh   sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
651bbd4ae5aSdrh                           0, pInfo->ecelFlags);
652bbd4ae5aSdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES
653bbd4ae5aSdrh   if( pInfo->pExtra ){
654bbd4ae5aSdrh     sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
655bbd4ae5aSdrh     sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
656bbd4ae5aSdrh   }
657bbd4ae5aSdrh #endif
658bbd4ae5aSdrh }
659bbd4ae5aSdrh 
660bbd4ae5aSdrh /*
661bbd4ae5aSdrh ** Code the OP_MakeRecord instruction that generates the entry to be
662bbd4ae5aSdrh ** added into the sorter.
663bbd4ae5aSdrh **
664bbd4ae5aSdrh ** Return the register in which the result is stored.
665bbd4ae5aSdrh */
makeSorterRecord(Parse * pParse,SortCtx * pSort,Select * pSelect,int regBase,int nBase)666bbd4ae5aSdrh static int makeSorterRecord(
667bbd4ae5aSdrh   Parse *pParse,
668bbd4ae5aSdrh   SortCtx *pSort,
669bbd4ae5aSdrh   Select *pSelect,
670bbd4ae5aSdrh   int regBase,
671bbd4ae5aSdrh   int nBase
672bbd4ae5aSdrh ){
673bbd4ae5aSdrh   int nOBSat = pSort->nOBSat;
674bbd4ae5aSdrh   Vdbe *v = pParse->pVdbe;
675bbd4ae5aSdrh   int regOut = ++pParse->nMem;
676bbd4ae5aSdrh   if( pSort->pDeferredRowLoad ){
677bbd4ae5aSdrh     innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
678bbd4ae5aSdrh   }
679bbd4ae5aSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
680bbd4ae5aSdrh   return regOut;
681bbd4ae5aSdrh }
682bbd4ae5aSdrh 
683bbd4ae5aSdrh /*
684f45f2326Sdrh ** Generate code that will push the record in registers regData
685f45f2326Sdrh ** through regData+nData-1 onto the sorter.
686c926afbcSdrh */
pushOntoSorter(Parse * pParse,SortCtx * pSort,Select * pSelect,int regData,int regOrigData,int nData,int nPrefixReg)687d59ba6ceSdrh static void pushOntoSorter(
688d59ba6ceSdrh   Parse *pParse,         /* Parser context */
689079a3072Sdrh   SortCtx *pSort,        /* Information about the ORDER BY clause */
690b7654111Sdrh   Select *pSelect,       /* The whole SELECT statement */
691f45f2326Sdrh   int regData,           /* First register holding data to be sorted */
6925579d59fSdrh   int regOrigData,       /* First register holding data before packing */
693bbd4ae5aSdrh   int nData,             /* Number of elements in the regData data array */
694fd0a2f97Sdrh   int nPrefixReg         /* No. of reg prior to regData available for use */
695d59ba6ceSdrh ){
696f45f2326Sdrh   Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
69778d58432Sdan   int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
698f45f2326Sdrh   int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
69978d58432Sdan   int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
700fd0a2f97Sdrh   int regBase;                                     /* Regs for sorter record */
701bbd4ae5aSdrh   int regRecord = 0;                               /* Assembled sorter record */
70278d58432Sdan   int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
703f45f2326Sdrh   int op;                            /* Opcode to add sorter record to sorter */
704a04a8be2Sdrh   int iLimit;                        /* LIMIT counter */
705bbd4ae5aSdrh   int iSkip = 0;                     /* End of the sorter insert loop */
706f45f2326Sdrh 
70778d58432Sdan   assert( bSeq==0 || bSeq==1 );
708bbd4ae5aSdrh 
709bbd4ae5aSdrh   /* Three cases:
710bbd4ae5aSdrh   **   (1) The data to be sorted has already been packed into a Record
711bbd4ae5aSdrh   **       by a prior OP_MakeRecord.  In this case nData==1 and regData
712bbd4ae5aSdrh   **       will be completely unrelated to regOrigData.
713bbd4ae5aSdrh   **   (2) All output columns are included in the sort record.  In that
714bbd4ae5aSdrh   **       case regData==regOrigData.
715bbd4ae5aSdrh   **   (3) Some output columns are omitted from the sort record due to
716bbd4ae5aSdrh   **       the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the
717c6f36fa3Sdrh   **       SQLITE_ECEL_OMITREF optimization, or due to the
718c6f36fa3Sdrh   **       SortCtx.pDeferredRowLoad optimiation.  In any of these cases
719c6f36fa3Sdrh   **       regOrigData is 0 to prevent this routine from trying to copy
720c6f36fa3Sdrh   **       values that might not yet exist.
721bbd4ae5aSdrh   */
7229af90b72Sdan   assert( nData==1 || regData==regOrigData || regOrigData==0 );
723bbd4ae5aSdrh 
724fd0a2f97Sdrh   if( nPrefixReg ){
72578d58432Sdan     assert( nPrefixReg==nExpr+bSeq );
726bbd4ae5aSdrh     regBase = regData - nPrefixReg;
727fd0a2f97Sdrh   }else{
728fb0d6e56Sdrh     regBase = pParse->nMem + 1;
729fb0d6e56Sdrh     pParse->nMem += nBase;
730fd0a2f97Sdrh   }
731a04a8be2Sdrh   assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
732a04a8be2Sdrh   iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
733ec4ccdbcSdrh   pSort->labelDone = sqlite3VdbeMakeLabel(pParse);
7345579d59fSdrh   sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
7359af90b72Sdan                           SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
73678d58432Sdan   if( bSeq ){
737079a3072Sdrh     sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
738fd0a2f97Sdrh   }
739257c13faSdan   if( nPrefixReg==0 && nData>0 ){
740236241aeSdrh     sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
74178d58432Sdan   }
742079a3072Sdrh   if( nOBSat>0 ){
743079a3072Sdrh     int regPrevKey;   /* The first nOBSat columns of the previous row */
744079a3072Sdrh     int addrFirst;    /* Address of the OP_IfNot opcode */
745079a3072Sdrh     int addrJmp;      /* Address of the OP_Jump opcode */
746079a3072Sdrh     VdbeOp *pOp;      /* Opcode that opens the sorter */
747079a3072Sdrh     int nKey;         /* Number of sorting key columns, including OP_Sequence */
748dbfca2b7Sdrh     KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
749079a3072Sdrh 
750bbd4ae5aSdrh     regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
75126d7e7c6Sdrh     regPrevKey = pParse->nMem+1;
75226d7e7c6Sdrh     pParse->nMem += pSort->nOBSat;
75378d58432Sdan     nKey = nExpr - pSort->nOBSat + bSeq;
75478d58432Sdan     if( bSeq ){
75578d58432Sdan       addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
75678d58432Sdan     }else{
75778d58432Sdan       addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
75878d58432Sdan     }
75978d58432Sdan     VdbeCoverage(v);
76026d7e7c6Sdrh     sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
761079a3072Sdrh     pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
76259b8f2e1Sdrh     if( pParse->db->mallocFailed ) return;
763fb0d6e56Sdrh     pOp->p2 = nKey + nData;
764dbfca2b7Sdrh     pKI = pOp->p4.pKeyInfo;
7656e11892dSdan     memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */
766dbfca2b7Sdrh     sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
767a485ad19Sdrh     testcase( pKI->nAllField > pKI->nKeyField+2 );
768f9eae18bSdan     pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
769a485ad19Sdrh                                            pKI->nAllField-pKI->nKeyField-1);
770166bc383Sdrh     pOp = 0; /* Ensure pOp not used after sqltie3VdbeAddOp3() */
771079a3072Sdrh     addrJmp = sqlite3VdbeCurrentAddr(v);
772079a3072Sdrh     sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
773ec4ccdbcSdrh     pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);
774079a3072Sdrh     pSort->regReturn = ++pParse->nMem;
775079a3072Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
77665ea12cbSdrh     sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
777a04a8be2Sdrh     if( iLimit ){
778a04a8be2Sdrh       sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
779a04a8be2Sdrh       VdbeCoverage(v);
780a04a8be2Sdrh     }
781079a3072Sdrh     sqlite3VdbeJumpHere(v, addrFirst);
782236241aeSdrh     sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
783079a3072Sdrh     sqlite3VdbeJumpHere(v, addrJmp);
784079a3072Sdrh   }
785f226f03dSdan   if( iLimit ){
786f226f03dSdan     /* At this point the values for the new sorter entry are stored
787f226f03dSdan     ** in an array of registers. They need to be composed into a record
788f226f03dSdan     ** and inserted into the sorter if either (a) there are currently
789f226f03dSdan     ** less than LIMIT+OFFSET items or (b) the new record is smaller than
790f226f03dSdan     ** the largest record currently in the sorter. If (b) is true and there
791f226f03dSdan     ** are already LIMIT+OFFSET items in the sorter, delete the largest
792f226f03dSdan     ** entry before inserting the new one. This way there are never more
793f226f03dSdan     ** than LIMIT+OFFSET items in the sorter.
794f226f03dSdan     **
795f226f03dSdan     ** If the new record does not need to be inserted into the sorter,
7966ee5a7b4Sdrh     ** jump to the next iteration of the loop. If the pSort->labelOBLopt
7976ee5a7b4Sdrh     ** value is not zero, then it is a label of where to jump.  Otherwise,
7986ee5a7b4Sdrh     ** just bypass the row insert logic.  See the header comment on the
7996ee5a7b4Sdrh     ** sqlite3WhereOrderByLimitOptLabel() function for additional info.
800f226f03dSdan     */
801f226f03dSdan     int iCsr = pSort->iECursor;
802f226f03dSdan     sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);
803f226f03dSdan     VdbeCoverage(v);
804f226f03dSdan     sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);
805bbd4ae5aSdrh     iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,
806bbd4ae5aSdrh                                  iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
807f226f03dSdan     VdbeCoverage(v);
808f226f03dSdan     sqlite3VdbeAddOp1(v, OP_Delete, iCsr);
809f226f03dSdan   }
810bbd4ae5aSdrh   if( regRecord==0 ){
811bbd4ae5aSdrh     regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
812f226f03dSdan   }
813079a3072Sdrh   if( pSort->sortFlags & SORTFLAG_UseSorter ){
814c6aff30cSdrh     op = OP_SorterInsert;
815c6aff30cSdrh   }else{
816c6aff30cSdrh     op = OP_IdxInsert;
817c6aff30cSdrh   }
8184a8b013eSdrh   sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
8194a8b013eSdrh                        regBase+nOBSat, nBase-nOBSat);
820bbd4ae5aSdrh   if( iSkip ){
821bbd4ae5aSdrh     sqlite3VdbeChangeP2(v, iSkip,
8226ee5a7b4Sdrh          pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));
823bbd4ae5aSdrh   }
824c926afbcSdrh }
825c926afbcSdrh 
826c926afbcSdrh /*
827ec7429aeSdrh ** Add code to implement the OFFSET
828ea48eb2eSdrh */
codeOffset(Vdbe * v,int iOffset,int iContinue)829ec7429aeSdrh static void codeOffset(
830bab39e13Sdrh   Vdbe *v,          /* Generate code into this VM */
831aa9ce707Sdrh   int iOffset,      /* Register holding the offset counter */
832b7654111Sdrh   int iContinue     /* Jump here to skip the current record */
833ea48eb2eSdrh ){
834a22a75e5Sdrh   if( iOffset>0 ){
8358b0cf38aSdrh     sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
8368b0cf38aSdrh     VdbeComment((v, "OFFSET"));
837ea48eb2eSdrh   }
838ea48eb2eSdrh }
839ea48eb2eSdrh 
840ea48eb2eSdrh /*
84196ecb7b0Sdan ** Add code that will check to make sure the array of registers starting at
84296ecb7b0Sdan ** iMem form a distinct entry. This is used by both "SELECT DISTINCT ..." and
84376075807Sdan ** distinct aggregates ("SELECT count(DISTINCT <expr>) ..."). Three strategies
84476075807Sdan ** are available. Which is used depends on the value of parameter eTnctType,
84576075807Sdan ** as follows:
846a2a49dc9Sdrh **
84796ecb7b0Sdan **   WHERE_DISTINCT_UNORDERED/WHERE_DISTINCT_NOOP:
8489be1339fSdrh **     Build an ephemeral table that contains all entries seen before and
8499be1339fSdrh **     skip entries which have been seen before.
8509be1339fSdrh **
85176075807Sdan **     Parameter iTab is the cursor number of an ephemeral table that must
85276075807Sdan **     be opened before the VM code generated by this routine is executed.
8535383db71Sdan **     The ephemeral cursor table is queried for a record identical to the
85496ecb7b0Sdan **     record formed by the current array of registers. If one is found,
85596ecb7b0Sdan **     jump to VM address addrRepeat. Otherwise, insert a new record into
85696ecb7b0Sdan **     the ephemeral cursor and proceed.
85796ecb7b0Sdan **
85876075807Sdan **     The returned value in this case is a copy of parameter iTab.
85976075807Sdan **
86096ecb7b0Sdan **   WHERE_DISTINCT_ORDERED:
8619be1339fSdrh **     In this case rows are being delivered sorted order. The ephermal
8629be1339fSdrh **     table is not required. Instead, the current set of values
8639be1339fSdrh **     is compared against previous row. If they match, the new row
86496ecb7b0Sdan **     is not distinct and control jumps to VM address addrRepeat. Otherwise,
86596ecb7b0Sdan **     the VM program proceeds with processing the new row.
86696ecb7b0Sdan **
86776075807Sdan **     The returned value in this case is the register number of the first
86876075807Sdan **     in an array of registers used to store the previous result row so that
8699be1339fSdrh **     it can be compared to the next. The caller must ensure that this
8709be1339fSdrh **     register is initialized to NULL.  (The fixDistinctOpenEph() routine
8719be1339fSdrh **     will take care of this initialization.)
87276075807Sdan **
87396ecb7b0Sdan **   WHERE_DISTINCT_UNIQUE:
87496ecb7b0Sdan **     In this case it has already been determined that the rows are distinct.
8759be1339fSdrh **     No special action is required. The return value is zero.
87696ecb7b0Sdan **
87796ecb7b0Sdan ** Parameter pEList is the list of expressions used to generated the
87896ecb7b0Sdan ** contents of each row. It is used by this routine to determine (a)
87996ecb7b0Sdan ** how many elements there are in the array of registers and (b) the
88096ecb7b0Sdan ** collation sequences that should be used for the comparisons if
88196ecb7b0Sdan ** eTnctType is WHERE_DISTINCT_ORDERED.
882a2a49dc9Sdrh */
codeDistinct(Parse * pParse,int eTnctType,int iTab,int addrRepeat,ExprList * pEList,int regElem)8835383db71Sdan static int codeDistinct(
8842dcef11bSdrh   Parse *pParse,     /* Parsing and code generating context */
8854fcb30b7Sdan   int eTnctType,     /* WHERE_DISTINCT_* value */
886a2a49dc9Sdrh   int iTab,          /* A sorting index used to test for distinctness */
887a2a49dc9Sdrh   int addrRepeat,    /* Jump to here if not distinct */
8884fcb30b7Sdan   ExprList *pEList,  /* Expression for each element */
8894fcb30b7Sdan   int regElem        /* First element */
890a2a49dc9Sdrh ){
8915383db71Sdan   int iRet = 0;
8924fcb30b7Sdan   int nResultCol = pEList->nExpr;
8934fcb30b7Sdan   Vdbe *v = pParse->pVdbe;
8942dcef11bSdrh 
8954fcb30b7Sdan   switch( eTnctType ){
8964fcb30b7Sdan     case WHERE_DISTINCT_ORDERED: {
8974fcb30b7Sdan       int i;
8984fcb30b7Sdan       int iJump;              /* Jump destination */
8994fcb30b7Sdan       int regPrev;            /* Previous row content */
9004fcb30b7Sdan 
9014fcb30b7Sdan       /* Allocate space for the previous row */
9025383db71Sdan       iRet = regPrev = pParse->nMem+1;
9034fcb30b7Sdan       pParse->nMem += nResultCol;
9044fcb30b7Sdan 
9054fcb30b7Sdan       iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
9064fcb30b7Sdan       for(i=0; i<nResultCol; i++){
9074fcb30b7Sdan         CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
9084fcb30b7Sdan         if( i<nResultCol-1 ){
9094fcb30b7Sdan           sqlite3VdbeAddOp3(v, OP_Ne, regElem+i, iJump, regPrev+i);
9104fcb30b7Sdan           VdbeCoverage(v);
9114fcb30b7Sdan         }else{
9124fcb30b7Sdan           sqlite3VdbeAddOp3(v, OP_Eq, regElem+i, addrRepeat, regPrev+i);
9134fcb30b7Sdan           VdbeCoverage(v);
9144fcb30b7Sdan          }
9154fcb30b7Sdan         sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
9164fcb30b7Sdan         sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
9174fcb30b7Sdan       }
9184fcb30b7Sdan       assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
9194fcb30b7Sdan       sqlite3VdbeAddOp3(v, OP_Copy, regElem, regPrev, nResultCol-1);
9204fcb30b7Sdan       break;
9214fcb30b7Sdan     }
9224fcb30b7Sdan 
9234fcb30b7Sdan     case WHERE_DISTINCT_UNIQUE: {
9245383db71Sdan       /* nothing to do */
9254fcb30b7Sdan       break;
9264fcb30b7Sdan     }
9274fcb30b7Sdan 
9284fcb30b7Sdan     default: {
9294fcb30b7Sdan       int r1 = sqlite3GetTempReg(pParse);
9304fcb30b7Sdan       sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, regElem, nResultCol);
9314fcb30b7Sdan       VdbeCoverage(v);
9324fcb30b7Sdan       sqlite3VdbeAddOp3(v, OP_MakeRecord, regElem, nResultCol, r1);
9334fcb30b7Sdan       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, regElem, nResultCol);
934a67b5cb6Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
9352dcef11bSdrh       sqlite3ReleaseTempReg(pParse, r1);
9365383db71Sdan       iRet = iTab;
9374fcb30b7Sdan       break;
9384fcb30b7Sdan     }
9394fcb30b7Sdan   }
9405383db71Sdan 
9415383db71Sdan   return iRet;
9425383db71Sdan }
9435383db71Sdan 
94476075807Sdan /*
9459be1339fSdrh ** This routine runs after codeDistinct().  It makes necessary
9469be1339fSdrh ** adjustments to the OP_OpenEphemeral opcode that the codeDistinct()
9479be1339fSdrh ** routine made use of.  This processing must be done separately since
9489be1339fSdrh ** sometimes codeDistinct is called before the OP_OpenEphemeral is actually
9499be1339fSdrh ** laid down.
95076075807Sdan **
9519be1339fSdrh ** WHERE_DISTINCT_NOOP:
9529be1339fSdrh ** WHERE_DISTINCT_UNORDERED:
9539be1339fSdrh **
9549be1339fSdrh **     No adjustments necessary.  This function is a no-op.
95576075807Sdan **
95676075807Sdan ** WHERE_DISTINCT_UNIQUE:
9579be1339fSdrh **
9589be1339fSdrh **     The ephemeral table is not needed.  So change the
9599be1339fSdrh **     OP_OpenEphemeral opcode into an OP_Noop.
96076075807Sdan **
96176075807Sdan ** WHERE_DISTINCT_ORDERED:
9629be1339fSdrh **
9639be1339fSdrh **     The ephemeral table is not needed.  But we do need register
9649be1339fSdrh **     iVal to be initialized to NULL.  So change the OP_OpenEphemeral
9659be1339fSdrh **     into an OP_Null on the iVal register.
96676075807Sdan */
fixDistinctOpenEph(Parse * pParse,int eTnctType,int iVal,int iOpenEphAddr)9675383db71Sdan static void fixDistinctOpenEph(
9685383db71Sdan   Parse *pParse,     /* Parsing and code generating context */
9695383db71Sdan   int eTnctType,     /* WHERE_DISTINCT_* value */
9705383db71Sdan   int iVal,          /* Value returned by codeDistinct() */
97176075807Sdan   int iOpenEphAddr   /* Address of OP_OpenEphemeral instruction for iTab */
9725383db71Sdan ){
973c6da6dbaSdrh   if( pParse->nErr==0
974c6da6dbaSdrh    && (eTnctType==WHERE_DISTINCT_UNIQUE || eTnctType==WHERE_DISTINCT_ORDERED)
975c6da6dbaSdrh   ){
9765383db71Sdan     Vdbe *v = pParse->pVdbe;
97776075807Sdan     sqlite3VdbeChangeToNoop(v, iOpenEphAddr);
9789be1339fSdrh     if( sqlite3VdbeGetOp(v, iOpenEphAddr+1)->opcode==OP_Explain ){
9799be1339fSdrh       sqlite3VdbeChangeToNoop(v, iOpenEphAddr+1);
9809be1339fSdrh     }
9815383db71Sdan     if( eTnctType==WHERE_DISTINCT_ORDERED ){
9825383db71Sdan       /* Change the OP_OpenEphemeral to an OP_Null that sets the MEM_Cleared
9835383db71Sdan       ** bit on the first register of the previous value.  This will cause the
9845383db71Sdan       ** OP_Ne added in codeDistinct() to always fail on the first iteration of
9855383db71Sdan       ** the loop even if the first row is all NULLs.  */
98676075807Sdan       VdbeOp *pOp = sqlite3VdbeGetOp(v, iOpenEphAddr);
9875383db71Sdan       pOp->opcode = OP_Null;
9885383db71Sdan       pOp->p1 = 1;
9895383db71Sdan       pOp->p2 = iVal;
9905383db71Sdan     }
9915383db71Sdan   }
992a2a49dc9Sdrh }
993a2a49dc9Sdrh 
99424e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES
99524e25d32Sdan /*
99624e25d32Sdan ** This function is called as part of inner-loop generation for a SELECT
99724e25d32Sdan ** statement with an ORDER BY that is not optimized by an index. It
99824e25d32Sdan ** determines the expressions, if any, that the sorter-reference
99924e25d32Sdan ** optimization should be used for. The sorter-reference optimization
100024e25d32Sdan ** is used for SELECT queries like:
100124e25d32Sdan **
100224e25d32Sdan **   SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10
100324e25d32Sdan **
100424e25d32Sdan ** If the optimization is used for expression "bigblob", then instead of
100524e25d32Sdan ** storing values read from that column in the sorter records, the PK of
100624e25d32Sdan ** the row from table t1 is stored instead. Then, as records are extracted from
100724e25d32Sdan ** the sorter to return to the user, the required value of bigblob is
100824e25d32Sdan ** retrieved directly from table t1. If the values are very large, this
100924e25d32Sdan ** can be more efficient than storing them directly in the sorter records.
101024e25d32Sdan **
101100e5d3d5Sdrh ** The ExprList_item.fg.bSorterRef flag is set for each expression in pEList
101224e25d32Sdan ** for which the sorter-reference optimization should be enabled.
101324e25d32Sdan ** Additionally, the pSort->aDefer[] array is populated with entries
101424e25d32Sdan ** for all cursors required to evaluate all selected expressions. Finally.
101524e25d32Sdan ** output variable (*ppExtra) is set to an expression list containing
101624e25d32Sdan ** expressions for all extra PK values that should be stored in the
101724e25d32Sdan ** sorter records.
101824e25d32Sdan */
selectExprDefer(Parse * pParse,SortCtx * pSort,ExprList * pEList,ExprList ** ppExtra)101924e25d32Sdan static void selectExprDefer(
102024e25d32Sdan   Parse *pParse,                  /* Leave any error here */
102124e25d32Sdan   SortCtx *pSort,                 /* Sorter context */
102224e25d32Sdan   ExprList *pEList,               /* Expressions destined for sorter */
102324e25d32Sdan   ExprList **ppExtra              /* Expressions to append to sorter record */
102424e25d32Sdan ){
102524e25d32Sdan   int i;
102624e25d32Sdan   int nDefer = 0;
102724e25d32Sdan   ExprList *pExtra = 0;
102824e25d32Sdan   for(i=0; i<pEList->nExpr; i++){
102924e25d32Sdan     struct ExprList_item *pItem = &pEList->a[i];
103024e25d32Sdan     if( pItem->u.x.iOrderByCol==0 ){
103124e25d32Sdan       Expr *pExpr = pItem->pExpr;
1032477572b9Sdrh       Table *pTab;
1033ffa5b054Sdrh       if( pExpr->op==TK_COLUMN
1034ffa5b054Sdrh        && pExpr->iColumn>=0
1035ffa5b054Sdrh        && ALWAYS( ExprUseYTab(pExpr) )
1036ffa5b054Sdrh        && (pTab = pExpr->y.pTab)!=0
1037ffa5b054Sdrh        && IsOrdinaryTable(pTab)
1038ffa5b054Sdrh        && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)!=0
103924e25d32Sdan       ){
104024e25d32Sdan         int j;
104124e25d32Sdan         for(j=0; j<nDefer; j++){
104224e25d32Sdan           if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
104324e25d32Sdan         }
104424e25d32Sdan         if( j==nDefer ){
104524e25d32Sdan           if( nDefer==ArraySize(pSort->aDefer) ){
104624e25d32Sdan             continue;
104724e25d32Sdan           }else{
104824e25d32Sdan             int nKey = 1;
104924e25d32Sdan             int k;
105024e25d32Sdan             Index *pPk = 0;
105124e25d32Sdan             if( !HasRowid(pTab) ){
105224e25d32Sdan               pPk = sqlite3PrimaryKeyIndex(pTab);
105324e25d32Sdan               nKey = pPk->nKeyCol;
105424e25d32Sdan             }
105524e25d32Sdan             for(k=0; k<nKey; k++){
105624e25d32Sdan               Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
105724e25d32Sdan               if( pNew ){
105824e25d32Sdan                 pNew->iTable = pExpr->iTable;
1059477572b9Sdrh                 assert( ExprUseYTab(pNew) );
1060eda079cdSdrh                 pNew->y.pTab = pExpr->y.pTab;
106124e25d32Sdan                 pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
106224e25d32Sdan                 pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
106324e25d32Sdan               }
106424e25d32Sdan             }
1065eda079cdSdrh             pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
106624e25d32Sdan             pSort->aDefer[nDefer].iCsr = pExpr->iTable;
106724e25d32Sdan             pSort->aDefer[nDefer].nKey = nKey;
106824e25d32Sdan             nDefer++;
106924e25d32Sdan           }
107024e25d32Sdan         }
1071d88fd539Sdrh         pItem->fg.bSorterRef = 1;
107224e25d32Sdan       }
107324e25d32Sdan     }
107424e25d32Sdan   }
107524e25d32Sdan   pSort->nDefer = (u8)nDefer;
107624e25d32Sdan   *ppExtra = pExtra;
107724e25d32Sdan }
107824e25d32Sdan #endif
107924e25d32Sdan 
1080c99130fdSdrh /*
10812282792aSdrh ** This routine generates the code for the inside of the inner loop
10822282792aSdrh ** of a SELECT.
108382c3d636Sdrh **
10842def2f7eSdrh ** If srcTab is negative, then the p->pEList expressions
1085340309fdSdrh ** are evaluated in order to get the data for this row.  If srcTab is
10862def2f7eSdrh ** zero or more, then data is pulled from srcTab and p->pEList is used only
1087257c13faSdan ** to get the number of columns and the collation sequence for each column.
10882282792aSdrh */
selectInnerLoop(Parse * pParse,Select * p,int srcTab,SortCtx * pSort,DistinctCtx * pDistinct,SelectDest * pDest,int iContinue,int iBreak)1089d2b3e23bSdrh static void selectInnerLoop(
10902282792aSdrh   Parse *pParse,          /* The parser context */
1091df199a25Sdrh   Select *p,              /* The complete select statement being coded */
10922def2f7eSdrh   int srcTab,             /* Pull data from this table if non-negative */
1093079a3072Sdrh   SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
1094e8e4af76Sdrh   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
10956c8c8ce0Sdanielk1977   SelectDest *pDest,      /* How to dispose of the results */
10962282792aSdrh   int iContinue,          /* Jump here to continue with next row */
1097a9671a22Sdrh   int iBreak              /* Jump here to break out of the inner loop */
10982282792aSdrh ){
10992282792aSdrh   Vdbe *v = pParse->pVdbe;
1100d847eaadSdrh   int i;
1101ea48eb2eSdrh   int hasDistinct;            /* True if the DISTINCT keyword is present */
1102d847eaadSdrh   int eDest = pDest->eDest;   /* How to dispose of results */
11032b596da8Sdrh   int iParm = pDest->iSDParm; /* First argument to disposal method */
1104d847eaadSdrh   int nResultCol;             /* Number of result columns */
1105fd0a2f97Sdrh   int nPrefixReg = 0;         /* Number of extra registers before regResult */
1106bbd4ae5aSdrh   RowLoadInfo sRowLoadInfo;   /* Info for deferred row loading */
110738640e15Sdrh 
11089af90b72Sdan   /* Usually, regResult is the first cell in an array of memory cells
11099af90b72Sdan   ** containing the current result row. In this case regOrig is set to the
11109af90b72Sdan   ** same value. However, if the results are being sent to the sorter, the
11119af90b72Sdan   ** values for any expressions that are also part of the sort-key are omitted
11129af90b72Sdan   ** from this array. In this case regOrig is set to zero.  */
11139af90b72Sdan   int regResult;              /* Start of memory holding current results */
11149af90b72Sdan   int regOrig;                /* Start of memory holding full result (or 0) */
11159af90b72Sdan 
11161c767f0dSdrh   assert( v );
11172def2f7eSdrh   assert( p->pEList!=0 );
1118e8e4af76Sdrh   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
1119079a3072Sdrh   if( pSort && pSort->pOrderBy==0 ) pSort = 0;
1120079a3072Sdrh   if( pSort==0 && !hasDistinct ){
1121a22a75e5Sdrh     assert( iContinue!=0 );
1122aa9ce707Sdrh     codeOffset(v, p->iOffset, iContinue);
1123df199a25Sdrh   }
1124df199a25Sdrh 
1125967e8b73Sdrh   /* Pull the requested columns.
11262282792aSdrh   */
11272def2f7eSdrh   nResultCol = p->pEList->nExpr;
112805a86c5cSdrh 
11292b596da8Sdrh   if( pDest->iSdst==0 ){
1130fd0a2f97Sdrh     if( pSort ){
113178d58432Sdan       nPrefixReg = pSort->pOrderBy->nExpr;
113278d58432Sdan       if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
1133fd0a2f97Sdrh       pParse->nMem += nPrefixReg;
11341013c932Sdrh     }
1135a2a49dc9Sdrh     pDest->iSdst = pParse->nMem+1;
1136477df4b3Sdrh     pParse->nMem += nResultCol;
113705a86c5cSdrh   }else if( pDest->iSdst+nResultCol > pParse->nMem ){
113805a86c5cSdrh     /* This is an error condition that can result, for example, when a SELECT
113905a86c5cSdrh     ** on the right-hand side of an INSERT contains more result columns than
114005a86c5cSdrh     ** there are columns in the table on the left.  The error will be caught
114105a86c5cSdrh     ** and reported later.  But we need to make sure enough memory is allocated
114205a86c5cSdrh     ** to avoid other spurious errors in the meantime. */
114305a86c5cSdrh     pParse->nMem += nResultCol;
11444c583128Sdrh   }
114505a86c5cSdrh   pDest->nSdst = nResultCol;
11469af90b72Sdan   regOrig = regResult = pDest->iSdst;
1147340309fdSdrh   if( srcTab>=0 ){
1148340309fdSdrh     for(i=0; i<nResultCol; i++){
1149d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
115041cee668Sdrh       VdbeComment((v, "%s", p->pEList->a[i].zEName));
115182c3d636Sdrh     }
11529ed1dfa8Sdanielk1977   }else if( eDest!=SRT_Exists ){
115324e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES
115424e25d32Sdan     ExprList *pExtra = 0;
115524e25d32Sdan #endif
11569ed1dfa8Sdanielk1977     /* If the destination is an EXISTS(...) expression, the actual
11579ed1dfa8Sdanielk1977     ** values returned by the SELECT are not required.
11589ed1dfa8Sdanielk1977     */
1159bbd4ae5aSdrh     u8 ecelFlags;    /* "ecel" is an abbreviation of "ExprCodeExprList" */
1160bbd4ae5aSdrh     ExprList *pEList;
1161df553659Sdrh     if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
1162df553659Sdrh       ecelFlags = SQLITE_ECEL_DUP;
1163df553659Sdrh     }else{
1164df553659Sdrh       ecelFlags = 0;
1165a2a49dc9Sdrh     }
1166ac56ab7eSdan     if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
11672def2f7eSdrh       /* For each expression in p->pEList that is a copy of an expression in
1168257c13faSdan       ** the ORDER BY clause (pSort->pOrderBy), set the associated
1169257c13faSdan       ** iOrderByCol value to one more than the index of the ORDER BY
1170257c13faSdan       ** expression within the sort-key that pushOntoSorter() will generate.
11712def2f7eSdrh       ** This allows the p->pEList field to be omitted from the sorted record,
1172257c13faSdan       ** saving space and CPU cycles.  */
1173257c13faSdan       ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
1174bbd4ae5aSdrh 
1175257c13faSdan       for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
1176257c13faSdan         int j;
1177257c13faSdan         if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
11782def2f7eSdrh           p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
1179257c13faSdan         }
1180257c13faSdan       }
118124e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES
118224e25d32Sdan       selectExprDefer(pParse, pSort, p->pEList, &pExtra);
11835a2e65edSdrh       if( pExtra && pParse->db->mallocFailed==0 ){
118424e25d32Sdan         /* If there are any extra PK columns to add to the sorter records,
118524e25d32Sdan         ** allocate extra memory cells and adjust the OpenEphemeral
118624e25d32Sdan         ** instruction to account for the larger records. This is only
118724e25d32Sdan         ** required if there are one or more WITHOUT ROWID tables with
118824e25d32Sdan         ** composite primary keys in the SortCtx.aDefer[] array.  */
118924e25d32Sdan         VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
119024e25d32Sdan         pOp->p2 += (pExtra->nExpr - pSort->nDefer);
119124e25d32Sdan         pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
119224e25d32Sdan         pParse->nMem += pExtra->nExpr;
119324e25d32Sdan       }
119424e25d32Sdan #endif
1195bbd4ae5aSdrh 
1196bbd4ae5aSdrh       /* Adjust nResultCol to account for columns that are omitted
1197bbd4ae5aSdrh       ** from the sorter by the optimizations in this branch */
1198bbd4ae5aSdrh       pEList = p->pEList;
1199bbd4ae5aSdrh       for(i=0; i<pEList->nExpr; i++){
1200bbd4ae5aSdrh         if( pEList->a[i].u.x.iOrderByCol>0
1201bbd4ae5aSdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1202d88fd539Sdrh          || pEList->a[i].fg.bSorterRef
1203bbd4ae5aSdrh #endif
1204bbd4ae5aSdrh         ){
1205bbd4ae5aSdrh           nResultCol--;
12069af90b72Sdan           regOrig = 0;
1207bbd4ae5aSdrh         }
1208bbd4ae5aSdrh       }
1209bbd4ae5aSdrh 
1210bbd4ae5aSdrh       testcase( regOrig );
1211bbd4ae5aSdrh       testcase( eDest==SRT_Set );
1212bbd4ae5aSdrh       testcase( eDest==SRT_Mem );
1213bbd4ae5aSdrh       testcase( eDest==SRT_Coroutine );
1214bbd4ae5aSdrh       testcase( eDest==SRT_Output );
1215257c13faSdan       assert( eDest==SRT_Set || eDest==SRT_Mem
1216f2972b60Sdan            || eDest==SRT_Coroutine || eDest==SRT_Output
1217f2972b60Sdan            || eDest==SRT_Upfrom );
1218257c13faSdan     }
1219bbd4ae5aSdrh     sRowLoadInfo.regResult = regResult;
1220bbd4ae5aSdrh     sRowLoadInfo.ecelFlags = ecelFlags;
122124e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1222bbd4ae5aSdrh     sRowLoadInfo.pExtra = pExtra;
1223bbd4ae5aSdrh     sRowLoadInfo.regExtraResult = regResult + nResultCol;
1224bbd4ae5aSdrh     if( pExtra ) nResultCol += pExtra->nExpr;
122524e25d32Sdan #endif
1226bbd4ae5aSdrh     if( p->iLimit
1227bbd4ae5aSdrh      && (ecelFlags & SQLITE_ECEL_OMITREF)!=0
1228bbd4ae5aSdrh      && nPrefixReg>0
1229bbd4ae5aSdrh     ){
1230bbd4ae5aSdrh       assert( pSort!=0 );
1231bbd4ae5aSdrh       assert( hasDistinct==0 );
1232bbd4ae5aSdrh       pSort->pDeferredRowLoad = &sRowLoadInfo;
1233c6f36fa3Sdrh       regOrig = 0;
1234bbd4ae5aSdrh     }else{
1235bbd4ae5aSdrh       innerLoopLoadRow(pParse, p, &sRowLoadInfo);
1236bbd4ae5aSdrh     }
1237a2a49dc9Sdrh   }
12382282792aSdrh 
1239daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
1240daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
1241daffd0e5Sdrh   ** part of the result.
12422282792aSdrh   */
1243ea48eb2eSdrh   if( hasDistinct ){
12445383db71Sdan     int eType = pDistinct->eTnctType;
12455383db71Sdan     int iTab = pDistinct->tabTnct;
12464fcb30b7Sdan     assert( nResultCol==p->pEList->nExpr );
12475383db71Sdan     iTab = codeDistinct(pParse, eType, iTab, iContinue, p->pEList, regResult);
12485383db71Sdan     fixDistinctOpenEph(pParse, eType, iTab, pDistinct->addrTnct);
1249079a3072Sdrh     if( pSort==0 ){
1250aa9ce707Sdrh       codeOffset(v, p->iOffset, iContinue);
1251ea48eb2eSdrh     }
12522282792aSdrh   }
125382c3d636Sdrh 
1254c926afbcSdrh   switch( eDest ){
125582c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
125682c3d636Sdrh     ** table iParm.
12572282792aSdrh     */
125813449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1259c926afbcSdrh     case SRT_Union: {
12609cbf3425Sdrh       int r1;
12619cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
1262340309fdSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
12639b4eaebcSdrh       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
12649cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
1265c926afbcSdrh       break;
1266c926afbcSdrh     }
126782c3d636Sdrh 
126882c3d636Sdrh     /* Construct a record from the query result, but instead of
126982c3d636Sdrh     ** saving that record, use it as a key to delete elements from
127082c3d636Sdrh     ** the temporary table iParm.
127182c3d636Sdrh     */
1272c926afbcSdrh     case SRT_Except: {
1273340309fdSdrh       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
1274c926afbcSdrh       break;
1275c926afbcSdrh     }
1276781def29Sdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
12775338a5f7Sdanielk1977 
12785338a5f7Sdanielk1977     /* Store the result as data using a unique key.
12795338a5f7Sdanielk1977     */
12808e1ee88cSdrh     case SRT_Fifo:
12818e1ee88cSdrh     case SRT_DistFifo:
12825338a5f7Sdanielk1977     case SRT_Table:
1283b9bb7c18Sdrh     case SRT_EphemTab: {
1284fd0a2f97Sdrh       int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
1285373cc2ddSdrh       testcase( eDest==SRT_Table );
1286373cc2ddSdrh       testcase( eDest==SRT_EphemTab );
1287e2248cfdSdrh       testcase( eDest==SRT_Fifo );
1288e2248cfdSdrh       testcase( eDest==SRT_DistFifo );
1289fd0a2f97Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
12905fdb9a35Sdrh       if( pDest->zAffSdst ){
12915fdb9a35Sdrh         sqlite3VdbeChangeP4(v, -1, pDest->zAffSdst, nResultCol);
12925fdb9a35Sdrh       }
12938ce7184bSdan #ifndef SQLITE_OMIT_CTE
12948e1ee88cSdrh       if( eDest==SRT_DistFifo ){
12958e1ee88cSdrh         /* If the destination is DistFifo, then cursor (iParm+1) is open
12968ce7184bSdan         ** on an ephemeral index. If the current row is already present
12978ce7184bSdan         ** in the index, do not write it to the output. If not, add the
12988ce7184bSdan         ** current row to the index and proceed with writing it to the
12998ce7184bSdan         ** output table as well.  */
13008ce7184bSdan         int addr = sqlite3VdbeCurrentAddr(v) + 4;
130138b4149cSdrh         sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
130238b4149cSdrh         VdbeCoverage(v);
13039b4eaebcSdrh         sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
1304079a3072Sdrh         assert( pSort==0 );
13058ce7184bSdan       }
13068ce7184bSdan #endif
1307079a3072Sdrh       if( pSort ){
1308bbd4ae5aSdrh         assert( regResult==regOrig );
1309bbd4ae5aSdrh         pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);
13105338a5f7Sdanielk1977       }else{
1311b7654111Sdrh         int r2 = sqlite3GetTempReg(pParse);
1312b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
1313b7654111Sdrh         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
1314b7654111Sdrh         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1315b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r2);
13165338a5f7Sdanielk1977       }
1317fd0a2f97Sdrh       sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
13185338a5f7Sdanielk1977       break;
13195338a5f7Sdanielk1977     }
13202282792aSdrh 
13219ed322d6Sdan     case SRT_Upfrom: {
1322f2972b60Sdan       if( pSort ){
1323f2972b60Sdan         pushOntoSorter(
1324f2972b60Sdan             pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
13252add24c0Sdrh       }else{
13269ed322d6Sdan         int i2 = pDest->iSDParm2;
13279ed322d6Sdan         int r1 = sqlite3GetTempReg(pParse);
132809cf5692Sdrh 
132909cf5692Sdrh         /* If the UPDATE FROM join is an aggregate that matches no rows, it
133009cf5692Sdrh         ** might still be trying to return one row, because that is what
133109cf5692Sdrh         ** aggregates do.  Don't record that empty row in the output table. */
133209cf5692Sdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regResult, iBreak); VdbeCoverage(v);
133309cf5692Sdrh 
133409cf5692Sdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord,
133509cf5692Sdrh                           regResult+(i2<0), nResultCol-(i2<0), r1);
13369ed322d6Sdan         if( i2<0 ){
13379ed322d6Sdan           sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regResult);
13389ed322d6Sdan         }else{
13399ed322d6Sdan           sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, i2);
13409ed322d6Sdan         }
1341f2972b60Sdan       }
13429ed322d6Sdan       break;
13439ed322d6Sdan     }
13449ed322d6Sdan 
13459ed322d6Sdan #ifndef SQLITE_OMIT_SUBQUERY
13462282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
13472282792aSdrh     ** then there should be a single item on the stack.  Write this
13482282792aSdrh     ** item into the set table with bogus data.
13492282792aSdrh     */
1350c926afbcSdrh     case SRT_Set: {
1351079a3072Sdrh       if( pSort ){
1352de941c60Sdrh         /* At first glance you would think we could optimize out the
1353de941c60Sdrh         ** ORDER BY in this case since the order of entries in the set
1354de941c60Sdrh         ** does not matter.  But there might be a LIMIT clause, in which
1355de941c60Sdrh         ** case the order does matter */
135651d82d1dSdan         pushOntoSorter(
13579af90b72Sdan             pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
1358c926afbcSdrh       }else{
1359b7654111Sdrh         int r1 = sqlite3GetTempReg(pParse);
13609ed322d6Sdan         assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
13619ed322d6Sdan         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
13629ed322d6Sdan             r1, pDest->zAffSdst, nResultCol);
13639b4eaebcSdrh         sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
1364b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r1);
1365c926afbcSdrh       }
1366c926afbcSdrh       break;
1367c926afbcSdrh     }
136882c3d636Sdrh 
13699ed322d6Sdan 
1370504b6989Sdrh     /* If any row exist in the result set, record that fact and abort.
1371ec7429aeSdrh     */
1372ec7429aeSdrh     case SRT_Exists: {
13734c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
1374ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
1375ec7429aeSdrh       break;
1376ec7429aeSdrh     }
1377ec7429aeSdrh 
13782282792aSdrh     /* If this is a scalar select that is part of an expression, then
1379870a0705Sdan     ** store the results in the appropriate memory cell or array of
1380870a0705Sdan     ** memory cells and break out of the scan loop.
13812282792aSdrh     */
1382c926afbcSdrh     case SRT_Mem: {
1383079a3072Sdrh       if( pSort ){
1384257c13faSdan         assert( nResultCol<=pDest->nSdst );
1385870a0705Sdan         pushOntoSorter(
13869af90b72Sdan             pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
1387c926afbcSdrh       }else{
1388257c13faSdan         assert( nResultCol==pDest->nSdst );
138953932ce8Sdrh         assert( regResult==iParm );
1390ec7429aeSdrh         /* The LIMIT clause will jump out of the loop for us */
1391c926afbcSdrh       }
1392c926afbcSdrh       break;
1393c926afbcSdrh     }
139493758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
13952282792aSdrh 
139681cf13ecSdrh     case SRT_Coroutine:       /* Send data to a co-routine */
139781cf13ecSdrh     case SRT_Output: {        /* Return the results */
1398373cc2ddSdrh       testcase( eDest==SRT_Coroutine );
1399373cc2ddSdrh       testcase( eDest==SRT_Output );
1400079a3072Sdrh       if( pSort ){
14019af90b72Sdan         pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
14025579d59fSdrh                        nPrefixReg);
1403e00ee6ebSdrh       }else if( eDest==SRT_Coroutine ){
14042b596da8Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1405c182d163Sdrh       }else{
1406340309fdSdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
1407ac82fcf5Sdrh       }
1408142e30dfSdrh       break;
1409142e30dfSdrh     }
1410142e30dfSdrh 
1411fe1c6bb9Sdrh #ifndef SQLITE_OMIT_CTE
1412fe1c6bb9Sdrh     /* Write the results into a priority queue that is order according to
1413fe1c6bb9Sdrh     ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
1414fe1c6bb9Sdrh     ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
1415fe1c6bb9Sdrh     ** pSO->nExpr columns, then make sure all keys are unique by adding a
1416fe1c6bb9Sdrh     ** final OP_Sequence column.  The last column is the record as a blob.
1417fe1c6bb9Sdrh     */
1418fe1c6bb9Sdrh     case SRT_DistQueue:
1419fe1c6bb9Sdrh     case SRT_Queue: {
1420fe1c6bb9Sdrh       int nKey;
1421fe1c6bb9Sdrh       int r1, r2, r3;
1422fe1c6bb9Sdrh       int addrTest = 0;
1423fe1c6bb9Sdrh       ExprList *pSO;
1424fe1c6bb9Sdrh       pSO = pDest->pOrderBy;
1425fe1c6bb9Sdrh       assert( pSO );
1426fe1c6bb9Sdrh       nKey = pSO->nExpr;
1427fe1c6bb9Sdrh       r1 = sqlite3GetTempReg(pParse);
1428fe1c6bb9Sdrh       r2 = sqlite3GetTempRange(pParse, nKey+2);
1429fe1c6bb9Sdrh       r3 = r2+nKey+1;
1430fe1c6bb9Sdrh       if( eDest==SRT_DistQueue ){
1431fe1c6bb9Sdrh         /* If the destination is DistQueue, then cursor (iParm+1) is open
1432fe1c6bb9Sdrh         ** on a second ephemeral index that holds all values every previously
14337e4efaecSdrh         ** added to the queue. */
14347e4efaecSdrh         addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
14357e4efaecSdrh                                         regResult, nResultCol);
1436688852abSdrh         VdbeCoverage(v);
14377e4efaecSdrh       }
14387e4efaecSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
14397e4efaecSdrh       if( eDest==SRT_DistQueue ){
1440fe1c6bb9Sdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
1441cfe24586Sdan         sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1442fe1c6bb9Sdrh       }
1443fe1c6bb9Sdrh       for(i=0; i<nKey; i++){
1444fe1c6bb9Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy,
1445fe1c6bb9Sdrh                           regResult + pSO->a[i].u.x.iOrderByCol - 1,
1446fe1c6bb9Sdrh                           r2+i);
1447fe1c6bb9Sdrh       }
1448fe1c6bb9Sdrh       sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
1449fe1c6bb9Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
14509b4eaebcSdrh       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
1451fe1c6bb9Sdrh       if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
1452fe1c6bb9Sdrh       sqlite3ReleaseTempReg(pParse, r1);
1453fe1c6bb9Sdrh       sqlite3ReleaseTempRange(pParse, r2, nKey+2);
1454fe1c6bb9Sdrh       break;
1455fe1c6bb9Sdrh     }
1456fe1c6bb9Sdrh #endif /* SQLITE_OMIT_CTE */
1457fe1c6bb9Sdrh 
1458fe1c6bb9Sdrh 
1459fe1c6bb9Sdrh 
14606a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER)
1461d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
1462d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
1463d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
1464d7489c39Sdrh     ** about the actual results of the select.
1465d7489c39Sdrh     */
1466c926afbcSdrh     default: {
1467f46f905aSdrh       assert( eDest==SRT_Discard );
1468c926afbcSdrh       break;
1469c926afbcSdrh     }
147093758c8dSdanielk1977 #endif
1471c926afbcSdrh   }
1472ec7429aeSdrh 
14735e87be87Sdrh   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
14745e87be87Sdrh   ** there is a sorter, in which case the sorter has already limited
14755e87be87Sdrh   ** the output for us.
1476ec7429aeSdrh   */
1477079a3072Sdrh   if( pSort==0 && p->iLimit ){
147816897072Sdrh     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
1479ec7429aeSdrh   }
148082c3d636Sdrh }
148182c3d636Sdrh 
148282c3d636Sdrh /*
1483ad124329Sdrh ** Allocate a KeyInfo object sufficient for an index of N key columns and
1484ad124329Sdrh ** X extra columns.
1485323df790Sdrh */
sqlite3KeyInfoAlloc(sqlite3 * db,int N,int X)1486ad124329Sdrh KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
1487d4ab003dSdrh   int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
1488d8e4b132Sdrh   KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
1489323df790Sdrh   if( p ){
14906e11892dSdan     p->aSortFlags = (u8*)&p->aColl[N+X];
1491a485ad19Sdrh     p->nKeyField = (u16)N;
1492a485ad19Sdrh     p->nAllField = (u16)(N+X);
1493323df790Sdrh     p->enc = ENC(db);
1494323df790Sdrh     p->db = db;
14952ec2fb22Sdrh     p->nRef = 1;
1496c263f7c4Sdrh     memset(&p[1], 0, nExtra);
14972ec2fb22Sdrh   }else{
14983cdb1394Sdrh     return (KeyInfo*)sqlite3OomFault(db);
1499323df790Sdrh   }
1500323df790Sdrh   return p;
1501323df790Sdrh }
1502323df790Sdrh 
1503323df790Sdrh /*
15042ec2fb22Sdrh ** Deallocate a KeyInfo object
15052ec2fb22Sdrh */
sqlite3KeyInfoUnref(KeyInfo * p)15062ec2fb22Sdrh void sqlite3KeyInfoUnref(KeyInfo *p){
15072ec2fb22Sdrh   if( p ){
150841ce47c4Sdrh     assert( p->db!=0 );
15092ec2fb22Sdrh     assert( p->nRef>0 );
15102ec2fb22Sdrh     p->nRef--;
151141ce47c4Sdrh     if( p->nRef==0 ) sqlite3DbNNFreeNN(p->db, p);
15122ec2fb22Sdrh   }
15132ec2fb22Sdrh }
15142ec2fb22Sdrh 
15152ec2fb22Sdrh /*
15162ec2fb22Sdrh ** Make a new pointer to a KeyInfo object
15172ec2fb22Sdrh */
sqlite3KeyInfoRef(KeyInfo * p)15182ec2fb22Sdrh KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
15192ec2fb22Sdrh   if( p ){
15202ec2fb22Sdrh     assert( p->nRef>0 );
15212ec2fb22Sdrh     p->nRef++;
15222ec2fb22Sdrh   }
15232ec2fb22Sdrh   return p;
15242ec2fb22Sdrh }
15252ec2fb22Sdrh 
15262ec2fb22Sdrh #ifdef SQLITE_DEBUG
15272ec2fb22Sdrh /*
15282ec2fb22Sdrh ** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
15292ec2fb22Sdrh ** can only be changed if this is just a single reference to the object.
15302ec2fb22Sdrh **
15312ec2fb22Sdrh ** This routine is used only inside of assert() statements.
15322ec2fb22Sdrh */
sqlite3KeyInfoIsWriteable(KeyInfo * p)15332ec2fb22Sdrh int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
15342ec2fb22Sdrh #endif /* SQLITE_DEBUG */
15352ec2fb22Sdrh 
15362ec2fb22Sdrh /*
1537dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records
1538dece1a84Sdrh ** the collating sequence for each expression in that expression list.
1539dece1a84Sdrh **
15400342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
15410342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to
15420342b1f5Sdrh ** implement that clause.  If the ExprList is the result set of a SELECT
15430342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual
15440342b1f5Sdrh ** index to implement a DISTINCT test.
15450342b1f5Sdrh **
154660ec914cSpeter.d.reid ** Space to hold the KeyInfo structure is obtained from malloc.  The calling
1547dece1a84Sdrh ** function is responsible for seeing that this structure is eventually
15482ec2fb22Sdrh ** freed.
1549dece1a84Sdrh */
sqlite3KeyInfoFromExprList(Parse * pParse,ExprList * pList,int iStart,int nExtra)1550f9eae18bSdan KeyInfo *sqlite3KeyInfoFromExprList(
1551079a3072Sdrh   Parse *pParse,       /* Parsing context */
1552079a3072Sdrh   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
1553079a3072Sdrh   int iStart,          /* Begin with this column of pList */
1554079a3072Sdrh   int nExtra           /* Add this many extra columns to the end */
1555079a3072Sdrh ){
1556dece1a84Sdrh   int nExpr;
1557dece1a84Sdrh   KeyInfo *pInfo;
1558dece1a84Sdrh   struct ExprList_item *pItem;
1559323df790Sdrh   sqlite3 *db = pParse->db;
1560dece1a84Sdrh   int i;
1561dece1a84Sdrh 
1562dece1a84Sdrh   nExpr = pList->nExpr;
15633f39bcf5Sdrh   pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
1564dece1a84Sdrh   if( pInfo ){
15652ec2fb22Sdrh     assert( sqlite3KeyInfoIsWriteable(pInfo) );
15666284db90Sdrh     for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
156770efa84dSdrh       pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
1568d88fd539Sdrh       pInfo->aSortFlags[i-iStart] = pItem->fg.sortFlags;
1569dece1a84Sdrh     }
1570dece1a84Sdrh   }
1571dece1a84Sdrh   return pInfo;
1572dece1a84Sdrh }
1573dece1a84Sdrh 
15747f61e92cSdan /*
15757f61e92cSdan ** Name of the connection operator, used for error messages.
15767f61e92cSdan */
sqlite3SelectOpName(int id)1577aae0f74eSdrh const char *sqlite3SelectOpName(int id){
15787f61e92cSdan   char *z;
15797f61e92cSdan   switch( id ){
15807f61e92cSdan     case TK_ALL:       z = "UNION ALL";   break;
15817f61e92cSdan     case TK_INTERSECT: z = "INTERSECT";   break;
15827f61e92cSdan     case TK_EXCEPT:    z = "EXCEPT";      break;
15837f61e92cSdan     default:           z = "UNION";       break;
15847f61e92cSdan   }
15857f61e92cSdan   return z;
15867f61e92cSdan }
15877f61e92cSdan 
15882ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN
158917c0bc0cSdan /*
159017c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
159117c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
159217c0bc0cSdan ** where the caption is of the form:
159317c0bc0cSdan **
159417c0bc0cSdan **   "USE TEMP B-TREE FOR xxx"
159517c0bc0cSdan **
159617c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
159717c0bc0cSdan ** is determined by the zUsage argument.
159817c0bc0cSdan */
explainTempTable(Parse * pParse,const char * zUsage)15992ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){
1600e2ca99c9Sdrh   ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
16012ce22453Sdan }
160217c0bc0cSdan 
160317c0bc0cSdan /*
1604bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro
1605bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
1606bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that
1607bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
1608bb2b4418Sdan ** code with #ifndef directives.
1609bb2b4418Sdan */
1610bb2b4418Sdan # define explainSetInteger(a, b) a = b
1611bb2b4418Sdan 
1612bb2b4418Sdan #else
1613bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */
1614bb2b4418Sdan # define explainTempTable(y,z)
1615bb2b4418Sdan # define explainSetInteger(y,z)
1616bb2b4418Sdan #endif
1617bb2b4418Sdan 
1618dece1a84Sdrh 
1619dece1a84Sdrh /*
1620d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
1621d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
1622d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
1623d8bc7086Sdrh ** routine generates the code needed to do that.
1624d8bc7086Sdrh */
generateSortTail(Parse * pParse,Select * p,SortCtx * pSort,int nColumn,SelectDest * pDest)1625c926afbcSdrh static void generateSortTail(
1626cdd536f0Sdrh   Parse *pParse,    /* Parsing context */
1627c926afbcSdrh   Select *p,        /* The SELECT statement */
1628079a3072Sdrh   SortCtx *pSort,   /* Information on the ORDER BY clause */
1629c926afbcSdrh   int nColumn,      /* Number of columns of data */
16306c8c8ce0Sdanielk1977   SelectDest *pDest /* Write the sorted results here */
1631c926afbcSdrh ){
1632ddba0c22Sdrh   Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
1633a04a8be2Sdrh   int addrBreak = pSort->labelDone;            /* Jump here to exit loop */
1634ec4ccdbcSdrh   int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */
163524e25d32Sdan   int addr;                       /* Top of output loop. Jump for Next. */
1636079a3072Sdrh   int addrOnce = 0;
16370342b1f5Sdrh   int iTab;
1638079a3072Sdrh   ExprList *pOrderBy = pSort->pOrderBy;
16396c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
16402b596da8Sdrh   int iParm = pDest->iSDParm;
16412d401ab8Sdrh   int regRow;
16422d401ab8Sdrh   int regRowid;
1643257c13faSdan   int iCol;
164424e25d32Sdan   int nKey;                       /* Number of key columns in sorter record */
1645f45f2326Sdrh   int iSortTab;                   /* Sorter cursor to read from */
1646f45f2326Sdrh   int i;
164778d58432Sdan   int bSeq;                       /* True if sorter record includes seq. no. */
164824e25d32Sdan   int nRefKey = 0;
164970f624c3Sdrh   struct ExprList_item *aOutEx = p->pEList->a;
16502d401ab8Sdrh 
1651a04a8be2Sdrh   assert( addrBreak<0 );
1652079a3072Sdrh   if( pSort->labelBkOut ){
1653079a3072Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
1654076e85f5Sdrh     sqlite3VdbeGoto(v, addrBreak);
1655079a3072Sdrh     sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
1656079a3072Sdrh   }
165724e25d32Sdan 
165824e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES
165924e25d32Sdan   /* Open any cursors needed for sorter-reference expressions */
166024e25d32Sdan   for(i=0; i<pSort->nDefer; i++){
166124e25d32Sdan     Table *pTab = pSort->aDefer[i].pTab;
166224e25d32Sdan     int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
166324e25d32Sdan     sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
166424e25d32Sdan     nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
166524e25d32Sdan   }
166624e25d32Sdan #endif
166724e25d32Sdan 
1668079a3072Sdrh   iTab = pSort->iECursor;
166971c57db0Sdan   if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
16708efc6a8cSdrh     if( eDest==SRT_Mem && p->iOffset ){
16718efc6a8cSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, pDest->iSdst);
16728efc6a8cSdrh     }
16733e9ca094Sdrh     regRowid = 0;
1674f45f2326Sdrh     regRow = pDest->iSdst;
1675ed24da4bSdrh   }else{
167651d82d1dSdan     regRowid = sqlite3GetTempReg(pParse);
1677375afb8bSdrh     if( eDest==SRT_EphemTab || eDest==SRT_Table ){
1678375afb8bSdrh       regRow = sqlite3GetTempReg(pParse);
1679375afb8bSdrh       nColumn = 0;
1680375afb8bSdrh     }else{
168151d82d1dSdan       regRow = sqlite3GetTempRange(pParse, nColumn);
1682cdd536f0Sdrh     }
1683375afb8bSdrh   }
1684079a3072Sdrh   nKey = pOrderBy->nExpr - pSort->nOBSat;
1685079a3072Sdrh   if( pSort->sortFlags & SORTFLAG_UseSorter ){
1686c2bb3282Sdrh     int regSortOut = ++pParse->nMem;
1687f45f2326Sdrh     iSortTab = pParse->nTab++;
168883553eefSdrh     if( pSort->labelBkOut ){
1689511f9e8dSdrh       addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
169083553eefSdrh     }
169124e25d32Sdan     sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut,
169224e25d32Sdan         nKey+1+nColumn+nRefKey);
1693079a3072Sdrh     if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
1694c6aff30cSdrh     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
1695688852abSdrh     VdbeCoverage(v);
1696bffd5c1eSdrh     assert( p->iLimit==0 && p->iOffset==0 );
16976cf4a7dfSdrh     sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
169878d58432Sdan     bSeq = 0;
1699c6aff30cSdrh   }else{
1700688852abSdrh     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
1701aa9ce707Sdrh     codeOffset(v, p->iOffset, addrContinue);
1702f45f2326Sdrh     iSortTab = iTab;
170378d58432Sdan     bSeq = 1;
1704bffd5c1eSdrh     if( p->iOffset>0 ){
1705bffd5c1eSdrh       sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
1706bffd5c1eSdrh     }
1707f45f2326Sdrh   }
1708d6189eafSdan   for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
170924e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1710d88fd539Sdrh     if( aOutEx[i].fg.bSorterRef ) continue;
171124e25d32Sdan #endif
17129f895239Sdrh     if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;
17139f895239Sdrh   }
171424e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES
171524e25d32Sdan   if( pSort->nDefer ){
171624e25d32Sdan     int iKey = iCol+1;
171724e25d32Sdan     int regKey = sqlite3GetTempRange(pParse, nRefKey);
171824e25d32Sdan 
171924e25d32Sdan     for(i=0; i<pSort->nDefer; i++){
172024e25d32Sdan       int iCsr = pSort->aDefer[i].iCsr;
172124e25d32Sdan       Table *pTab = pSort->aDefer[i].pTab;
172224e25d32Sdan       int nKey = pSort->aDefer[i].nKey;
172324e25d32Sdan 
172424e25d32Sdan       sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
172524e25d32Sdan       if( HasRowid(pTab) ){
172624e25d32Sdan         sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);
172724e25d32Sdan         sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr,
172824e25d32Sdan             sqlite3VdbeCurrentAddr(v)+1, regKey);
172924e25d32Sdan       }else{
173024e25d32Sdan         int k;
173124e25d32Sdan         int iJmp;
17327590d093Sdrh         assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
173324e25d32Sdan         for(k=0; k<nKey; k++){
173424e25d32Sdan           sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k);
173524e25d32Sdan         }
173624e25d32Sdan         iJmp = sqlite3VdbeCurrentAddr(v);
173724e25d32Sdan         sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey);
173824e25d32Sdan         sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey);
173924e25d32Sdan         sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
174024e25d32Sdan       }
174124e25d32Sdan     }
174224e25d32Sdan     sqlite3ReleaseTempRange(pParse, regKey, nRefKey);
174324e25d32Sdan   }
174424e25d32Sdan #endif
1745d6189eafSdan   for(i=nColumn-1; i>=0; i--){
174624e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1747d88fd539Sdrh     if( aOutEx[i].fg.bSorterRef ){
174824e25d32Sdan       sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i);
174924e25d32Sdan     }else
175024e25d32Sdan #endif
175124e25d32Sdan     {
1752257c13faSdan       int iRead;
1753257c13faSdan       if( aOutEx[i].u.x.iOrderByCol ){
1754257c13faSdan         iRead = aOutEx[i].u.x.iOrderByCol-1;
1755257c13faSdan       }else{
17569f895239Sdrh         iRead = iCol--;
1757257c13faSdan       }
1758257c13faSdan       sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
1759cbb9da33Sdrh       VdbeComment((v, "%s", aOutEx[i].zEName));
1760c6aff30cSdrh     }
176124e25d32Sdan   }
1762c926afbcSdrh   switch( eDest ){
1763ac56ab7eSdan     case SRT_Table:
1764b9bb7c18Sdrh     case SRT_EphemTab: {
1765375afb8bSdrh       sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow);
17662d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
17672d401ab8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
17682d401ab8Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1769c926afbcSdrh       break;
1770c926afbcSdrh     }
177193758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
1772c926afbcSdrh     case SRT_Set: {
177371c57db0Sdan       assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
177471c57db0Sdan       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
1775553168c7Sdan                         pDest->zAffSdst, nColumn);
17769b4eaebcSdrh       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
1777c926afbcSdrh       break;
1778c926afbcSdrh     }
1779c926afbcSdrh     case SRT_Mem: {
1780ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
1781c926afbcSdrh       break;
1782c926afbcSdrh     }
178393758c8dSdanielk1977 #endif
1784f2972b60Sdan     case SRT_Upfrom: {
1785f2972b60Sdan       int i2 = pDest->iSDParm2;
1786f2972b60Sdan       int r1 = sqlite3GetTempReg(pParse);
1787f2972b60Sdan       sqlite3VdbeAddOp3(v, OP_MakeRecord,regRow+(i2<0),nColumn-(i2<0),r1);
1788f2972b60Sdan       if( i2<0 ){
1789f2972b60Sdan         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regRow);
1790f2972b60Sdan       }else{
1791f2972b60Sdan         sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regRow, i2);
1792f2972b60Sdan       }
1793f2972b60Sdan       break;
1794f2972b60Sdan     }
1795373cc2ddSdrh     default: {
1796373cc2ddSdrh       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
17971c767f0dSdrh       testcase( eDest==SRT_Output );
17981c767f0dSdrh       testcase( eDest==SRT_Coroutine );
17997d10d5a6Sdrh       if( eDest==SRT_Output ){
18002b596da8Sdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
1801a9671a22Sdrh       }else{
18022b596da8Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1803ce665cf6Sdrh       }
1804ac82fcf5Sdrh       break;
1805ac82fcf5Sdrh     }
1806c926afbcSdrh   }
1807f45f2326Sdrh   if( regRowid ){
180851d82d1dSdan     if( eDest==SRT_Set ){
180951d82d1dSdan       sqlite3ReleaseTempRange(pParse, regRow, nColumn);
181051d82d1dSdan     }else{
18112d401ab8Sdrh       sqlite3ReleaseTempReg(pParse, regRow);
181251d82d1dSdan     }
18132d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regRowid);
1814f45f2326Sdrh   }
1815ec7429aeSdrh   /* The bottom of the loop
1816ec7429aeSdrh   */
1817dc5ea5c7Sdrh   sqlite3VdbeResolveLabel(v, addrContinue);
1818079a3072Sdrh   if( pSort->sortFlags & SORTFLAG_UseSorter ){
1819688852abSdrh     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
1820c6aff30cSdrh   }else{
1821688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
1822c6aff30cSdrh   }
1823079a3072Sdrh   if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
1824dc5ea5c7Sdrh   sqlite3VdbeResolveLabel(v, addrBreak);
1825d8bc7086Sdrh }
1826d8bc7086Sdrh 
1827d8bc7086Sdrh /*
1828517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
1829517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
1830e78e8284Sdrh **
1831955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the
1832955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The
1833955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
1834955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The
1835955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is
1836955de52cSdanielk1977 ** considered a column by this function.
1837e78e8284Sdrh **
1838955de52cSdanielk1977 **   SELECT col FROM tbl;
1839955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl;
1840955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl);
1841955de52cSdanielk1977 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
1842955de52cSdanielk1977 **
1843955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL.
18445f3e5e74Sdrh **
18455f3e5e74Sdrh ** This routine has either 3 or 6 parameters depending on whether or not
18465f3e5e74Sdrh ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
1847fcb78a49Sdrh */
18485f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1849cafc2f7bSdrh # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
1850b121dd14Sdrh #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
1851cafc2f7bSdrh # define columnType(A,B,C,D,E) columnTypeImpl(A,B)
1852b121dd14Sdrh #endif
columnTypeImpl(NameContext * pNC,Expr * pExpr)18535f3e5e74Sdrh static const char *columnTypeImpl(
1854955de52cSdanielk1977   NameContext *pNC,
1855cafc2f7bSdrh #ifndef SQLITE_ENABLE_COLUMN_METADATA
1856cafc2f7bSdrh   Expr *pExpr
1857cafc2f7bSdrh #else
1858955de52cSdanielk1977   Expr *pExpr,
18595f3e5e74Sdrh   const char **pzOrigDb,
18605f3e5e74Sdrh   const char **pzOrigTab,
1861cafc2f7bSdrh   const char **pzOrigCol
1862b121dd14Sdrh #endif
1863955de52cSdanielk1977 ){
1864955de52cSdanielk1977   char const *zType = 0;
1865517eb646Sdanielk1977   int j;
1866b121dd14Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1867b121dd14Sdrh   char const *zOrigDb = 0;
1868b121dd14Sdrh   char const *zOrigTab = 0;
1869b121dd14Sdrh   char const *zOrigCol = 0;
1870b121dd14Sdrh #endif
18715338a5f7Sdanielk1977 
1872f7ce4291Sdrh   assert( pExpr!=0 );
1873f7ce4291Sdrh   assert( pNC->pSrcList!=0 );
187400e279d9Sdanielk1977   switch( pExpr->op ){
187500e279d9Sdanielk1977     case TK_COLUMN: {
1876955de52cSdanielk1977       /* The expression is a column. Locate the table the column is being
1877955de52cSdanielk1977       ** extracted from in NameContext.pSrcList. This table may be real
1878955de52cSdanielk1977       ** database table or a subquery.
1879955de52cSdanielk1977       */
1880955de52cSdanielk1977       Table *pTab = 0;            /* Table structure column is extracted from */
1881955de52cSdanielk1977       Select *pS = 0;             /* Select the column is extracted from */
1882955de52cSdanielk1977       int iCol = pExpr->iColumn;  /* Index of column in pTab */
188343bc88bbSdan       while( pNC && !pTab ){
1884b3bce662Sdanielk1977         SrcList *pTabList = pNC->pSrcList;
1885b3bce662Sdanielk1977         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
1886b3bce662Sdanielk1977         if( j<pTabList->nSrc ){
18876a3ea0e6Sdrh           pTab = pTabList->a[j].pTab;
1888955de52cSdanielk1977           pS = pTabList->a[j].pSelect;
1889b3bce662Sdanielk1977         }else{
1890b3bce662Sdanielk1977           pNC = pNC->pNext;
1891b3bce662Sdanielk1977         }
1892b3bce662Sdanielk1977       }
1893955de52cSdanielk1977 
189443bc88bbSdan       if( pTab==0 ){
1895417168adSdrh         /* At one time, code such as "SELECT new.x" within a trigger would
1896417168adSdrh         ** cause this condition to run.  Since then, we have restructured how
1897417168adSdrh         ** trigger code is generated and so this condition is no longer
189843bc88bbSdan         ** possible. However, it can still be true for statements like
189943bc88bbSdan         ** the following:
190043bc88bbSdan         **
190143bc88bbSdan         **   CREATE TABLE t1(col INTEGER);
190243bc88bbSdan         **   SELECT (SELECT t1.col) FROM FROM t1;
190343bc88bbSdan         **
190443bc88bbSdan         ** when columnType() is called on the expression "t1.col" in the
190543bc88bbSdan         ** sub-select. In this case, set the column type to NULL, even
190643bc88bbSdan         ** though it should really be "INTEGER".
190743bc88bbSdan         **
190843bc88bbSdan         ** This is not a problem, as the column type of "t1.col" is never
190943bc88bbSdan         ** used. When columnType() is called on the expression
191043bc88bbSdan         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
191143bc88bbSdan         ** branch below.  */
19127e62779aSdrh         break;
19137e62779aSdrh       }
1914955de52cSdanielk1977 
1915477572b9Sdrh       assert( pTab && ExprUseYTab(pExpr) && pExpr->y.pTab==pTab );
1916955de52cSdanielk1977       if( pS ){
1917955de52cSdanielk1977         /* The "table" is actually a sub-select or a view in the FROM clause
1918955de52cSdanielk1977         ** of the SELECT statement. Return the declaration type and origin
1919955de52cSdanielk1977         ** data for the result-set column of the sub-select.
1920955de52cSdanielk1977         */
19216e5020e8Sdrh         if( iCol<pS->pEList->nExpr
19226e5020e8Sdrh #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
19236e5020e8Sdrh          && iCol>=0
19246e5020e8Sdrh #else
19256e5020e8Sdrh          && ALWAYS(iCol>=0)
19266e5020e8Sdrh #endif
19276e5020e8Sdrh         ){
1928955de52cSdanielk1977           /* If iCol is less than zero, then the expression requests the
1929955de52cSdanielk1977           ** rowid of the sub-select or view. This expression is legal (see
1930955de52cSdanielk1977           ** test case misc2.2.2) - it always evaluates to NULL.
1931955de52cSdanielk1977           */
1932955de52cSdanielk1977           NameContext sNC;
1933955de52cSdanielk1977           Expr *p = pS->pEList->a[iCol].pExpr;
1934955de52cSdanielk1977           sNC.pSrcList = pS->pSrc;
193543bc88bbSdan           sNC.pNext = pNC;
1936955de52cSdanielk1977           sNC.pParse = pNC->pParse;
1937cafc2f7bSdrh           zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
1938955de52cSdanielk1977         }
1939a78d757cSdrh       }else{
1940a78d757cSdrh         /* A real table or a CTE table */
1941955de52cSdanielk1977         assert( !pS );
19425f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1943a78d757cSdrh         if( iCol<0 ) iCol = pTab->iPKey;
1944a78d757cSdrh         assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
1945fcb78a49Sdrh         if( iCol<0 ){
1946fcb78a49Sdrh           zType = "INTEGER";
19475f3e5e74Sdrh           zOrigCol = "rowid";
1948fcb78a49Sdrh         }else{
1949cf9d36d1Sdrh           zOrigCol = pTab->aCol[iCol].zCnName;
1950d7564865Sdrh           zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
1951955de52cSdanielk1977         }
19525f3e5e74Sdrh         zOrigTab = pTab->zName;
1953a78d757cSdrh         if( pNC->pParse && pTab->pSchema ){
1954955de52cSdanielk1977           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
1955e59be010Sdrh           zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
1956955de52cSdanielk1977         }
19575f3e5e74Sdrh #else
1958a78d757cSdrh         assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
19595f3e5e74Sdrh         if( iCol<0 ){
19605f3e5e74Sdrh           zType = "INTEGER";
19615f3e5e74Sdrh         }else{
1962d7564865Sdrh           zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
19635f3e5e74Sdrh         }
19645f3e5e74Sdrh #endif
1965fcb78a49Sdrh       }
196600e279d9Sdanielk1977       break;
1967736c22b8Sdrh     }
196893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
196900e279d9Sdanielk1977     case TK_SELECT: {
1970955de52cSdanielk1977       /* The expression is a sub-select. Return the declaration type and
1971955de52cSdanielk1977       ** origin info for the single column in the result set of the SELECT
1972955de52cSdanielk1977       ** statement.
1973955de52cSdanielk1977       */
1974b3bce662Sdanielk1977       NameContext sNC;
1975a4eeccdfSdrh       Select *pS;
1976a4eeccdfSdrh       Expr *p;
1977a4eeccdfSdrh       assert( ExprUseXSelect(pExpr) );
1978a4eeccdfSdrh       pS = pExpr->x.pSelect;
1979a4eeccdfSdrh       p = pS->pEList->a[0].pExpr;
1980955de52cSdanielk1977       sNC.pSrcList = pS->pSrc;
1981b3bce662Sdanielk1977       sNC.pNext = pNC;
1982955de52cSdanielk1977       sNC.pParse = pNC->pParse;
1983cafc2f7bSdrh       zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
198400e279d9Sdanielk1977       break;
1985fcb78a49Sdrh     }
198693758c8dSdanielk1977 #endif
198700e279d9Sdanielk1977   }
198800e279d9Sdanielk1977 
19895f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
19905f3e5e74Sdrh   if( pzOrigDb ){
19915f3e5e74Sdrh     assert( pzOrigTab && pzOrigCol );
19925f3e5e74Sdrh     *pzOrigDb = zOrigDb;
19935f3e5e74Sdrh     *pzOrigTab = zOrigTab;
19945f3e5e74Sdrh     *pzOrigCol = zOrigCol;
1995955de52cSdanielk1977   }
19965f3e5e74Sdrh #endif
1997517eb646Sdanielk1977   return zType;
1998517eb646Sdanielk1977 }
1999517eb646Sdanielk1977 
2000517eb646Sdanielk1977 /*
2001517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
2002517eb646Sdanielk1977 ** in the result set.
2003517eb646Sdanielk1977 */
generateColumnTypes(Parse * pParse,SrcList * pTabList,ExprList * pEList)2004517eb646Sdanielk1977 static void generateColumnTypes(
2005517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
2006517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
2007517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
2008517eb646Sdanielk1977 ){
20093f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE
2010517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
2011517eb646Sdanielk1977   int i;
2012b3bce662Sdanielk1977   NameContext sNC;
2013b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
2014955de52cSdanielk1977   sNC.pParse = pParse;
2015eac5fc04Sdrh   sNC.pNext = 0;
2016517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
2017517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
20183f913576Sdrh     const char *zType;
20193f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
2020955de52cSdanielk1977     const char *zOrigDb = 0;
2021955de52cSdanielk1977     const char *zOrigTab = 0;
2022955de52cSdanielk1977     const char *zOrigCol = 0;
2023cafc2f7bSdrh     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
2024955de52cSdanielk1977 
202585b623f2Sdrh     /* The vdbe must make its own copy of the column-type and other
20264b1ae99dSdanielk1977     ** column specific strings, in case the schema is reset before this
20274b1ae99dSdanielk1977     ** virtual machine is deleted.
2028fbcd585fSdanielk1977     */
202910fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
203010fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
203110fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
20323f913576Sdrh #else
2033cafc2f7bSdrh     zType = columnType(&sNC, p, 0, 0, 0);
20343f913576Sdrh #endif
203510fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
2036fcb78a49Sdrh   }
20375f3e5e74Sdrh #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
2038fcb78a49Sdrh }
2039fcb78a49Sdrh 
2040eac5fc04Sdrh 
2041eac5fc04Sdrh /*
2042ec360a8dSdrh ** Compute the column names for a SELECT statement.
2043ec360a8dSdrh **
2044ec360a8dSdrh ** The only guarantee that SQLite makes about column names is that if the
2045ec360a8dSdrh ** column has an AS clause assigning it a name, that will be the name used.
2046ec360a8dSdrh ** That is the only documented guarantee.  However, countless applications
2047ec360a8dSdrh ** developed over the years have made baseless assumptions about column names
2048ec360a8dSdrh ** and will break if those assumptions changes.  Hence, use extreme caution
2049ec360a8dSdrh ** when modifying this routine to avoid breaking legacy.
2050ec360a8dSdrh **
2051ec360a8dSdrh ** See Also: sqlite3ColumnsFromExprList()
2052ec360a8dSdrh **
2053ec360a8dSdrh ** The PRAGMA short_column_names and PRAGMA full_column_names settings are
2054ec360a8dSdrh ** deprecated.  The default setting is short=ON, full=OFF.  99.9% of all
2055ec360a8dSdrh ** applications should operate this way.  Nevertheless, we need to support the
2056ec360a8dSdrh ** other modes for legacy:
2057ec360a8dSdrh **
2058ec360a8dSdrh **    short=OFF, full=OFF:      Column name is the text of the expression has it
2059ec360a8dSdrh **                              originally appears in the SELECT statement.  In
2060ec360a8dSdrh **                              other words, the zSpan of the result expression.
2061ec360a8dSdrh **
2062ec360a8dSdrh **    short=ON, full=OFF:       (This is the default setting).  If the result
20633d240d21Sdrh **                              refers directly to a table column, then the
20643d240d21Sdrh **                              result column name is just the table column
20653d240d21Sdrh **                              name: COLUMN.  Otherwise use zSpan.
2066ec360a8dSdrh **
2067ec360a8dSdrh **    full=ON, short=ANY:       If the result refers directly to a table column,
2068ec360a8dSdrh **                              then the result column name with the table name
2069ec360a8dSdrh **                              prefix, ex: TABLE.COLUMN.  Otherwise use zSpan.
207082c3d636Sdrh */
sqlite3GenerateColumnNames(Parse * pParse,Select * pSelect)20719088186bSdrh void sqlite3GenerateColumnNames(
2072832508b7Sdrh   Parse *pParse,      /* Parser context */
2073f35f2f92Sdrh   Select *pSelect     /* Generate column names for this SELECT statement */
2074832508b7Sdrh ){
2075d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
2076eac5fc04Sdrh   int i;
2077eac5fc04Sdrh   Table *pTab;
2078f35f2f92Sdrh   SrcList *pTabList;
2079f35f2f92Sdrh   ExprList *pEList;
20809bb575fdSdrh   sqlite3 *db = pParse->db;
2081ec360a8dSdrh   int fullName;    /* TABLE.COLUMN if no AS clause and is a direct table ref */
2082ec360a8dSdrh   int srcName;     /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
2083fcabd464Sdrh 
2084fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN
20853cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
20863cf86063Sdanielk1977   if( pParse->explain ){
208761de0d1bSdanielk1977     return;
20883cf86063Sdanielk1977   }
20895338a5f7Sdanielk1977 #endif
20903cf86063Sdanielk1977 
20915e8b9853Sdrh   if( pParse->colNamesSet ) return;
2092f35f2f92Sdrh   /* Column names are determined by the left-most term of a compound select */
2093f35f2f92Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
209407859486Sdrh   SELECTTRACE(1,pParse,pSelect,("generating column names\n"));
2095f35f2f92Sdrh   pTabList = pSelect->pSrc;
2096f35f2f92Sdrh   pEList = pSelect->pEList;
20979802947fSdrh   assert( v!=0 );
2098f7ce4291Sdrh   assert( pTabList!=0 );
2099d8bc7086Sdrh   pParse->colNamesSet = 1;
2100ec360a8dSdrh   fullName = (db->flags & SQLITE_FullColNames)!=0;
2101ec360a8dSdrh   srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
210222322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
210382c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
2104ec360a8dSdrh     Expr *p = pEList->a[i].pExpr;
2105ec360a8dSdrh 
2106ec360a8dSdrh     assert( p!=0 );
21074dd89d5aSdrh     assert( p->op!=TK_AGG_COLUMN );  /* Agg processing has not run yet */
2108477572b9Sdrh     assert( p->op!=TK_COLUMN
2109477572b9Sdrh         || (ExprUseYTab(p) && p->y.pTab!=0) ); /* Covering idx not yet coded */
2110d88fd539Sdrh     if( pEList->a[i].zEName && pEList->a[i].fg.eEName==ENAME_NAME ){
2111ec360a8dSdrh       /* An AS clause always takes first priority */
211241cee668Sdrh       char *zName = pEList->a[i].zEName;
211310fb749bSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
2114f35f2f92Sdrh     }else if( srcName && p->op==TK_COLUMN ){
211597665873Sdrh       char *zCol;
21168aff1015Sdrh       int iCol = p->iColumn;
2117eda079cdSdrh       pTab = p->y.pTab;
2118f35f2f92Sdrh       assert( pTab!=0 );
21198aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
212097665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
2121b1363206Sdrh       if( iCol<0 ){
212247a6db2bSdrh         zCol = "rowid";
2123b1363206Sdrh       }else{
2124cf9d36d1Sdrh         zCol = pTab->aCol[iCol].zCnName;
2125b1363206Sdrh       }
2126ec360a8dSdrh       if( fullName ){
212782c3d636Sdrh         char *zName = 0;
21281c767f0dSdrh         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
212910fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
213082c3d636Sdrh       }else{
213110fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
213282c3d636Sdrh       }
21331bee3d7bSdrh     }else{
2134cbb9da33Sdrh       const char *z = pEList->a[i].zEName;
2135859bc542Sdrh       z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
2136859bc542Sdrh       sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
213782c3d636Sdrh     }
213882c3d636Sdrh   }
213976d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
21405080aaa7Sdrh }
214182c3d636Sdrh 
2142d8bc7086Sdrh /*
214360ec914cSpeter.d.reid ** Given an expression list (which is really the list of expressions
21447d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate
21457d10d5a6Sdrh ** column names for a table that would hold the expression list.
21467d10d5a6Sdrh **
21477d10d5a6Sdrh ** All column names will be unique.
21487d10d5a6Sdrh **
21497d10d5a6Sdrh ** Only the column names are computed.  Column.zType, Column.zColl,
21507d10d5a6Sdrh ** and other fields of Column are zeroed.
21517d10d5a6Sdrh **
21527d10d5a6Sdrh ** Return SQLITE_OK on success.  If a memory allocation error occurs,
21537d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
2154ec360a8dSdrh **
2155ec360a8dSdrh ** The only guarantee that SQLite makes about column names is that if the
2156ec360a8dSdrh ** column has an AS clause assigning it a name, that will be the name used.
2157ec360a8dSdrh ** That is the only documented guarantee.  However, countless applications
2158ec360a8dSdrh ** developed over the years have made baseless assumptions about column names
2159ec360a8dSdrh ** and will break if those assumptions changes.  Hence, use extreme caution
2160ec360a8dSdrh ** when modifying this routine to avoid breaking legacy.
2161ec360a8dSdrh **
21629088186bSdrh ** See Also: sqlite3GenerateColumnNames()
2163315555caSdrh */
sqlite3ColumnsFromExprList(Parse * pParse,ExprList * pEList,i16 * pnCol,Column ** paCol)21648981b904Sdrh int sqlite3ColumnsFromExprList(
21657d10d5a6Sdrh   Parse *pParse,          /* Parsing context */
21667d10d5a6Sdrh   ExprList *pEList,       /* Expr list from which to derive column names */
2167d815f17dSdrh   i16 *pnCol,             /* Write the number of columns here */
21687d10d5a6Sdrh   Column **paCol          /* Write the new column list here */
21697d10d5a6Sdrh ){
2170dc5ea5c7Sdrh   sqlite3 *db = pParse->db;   /* Database connection */
2171dc5ea5c7Sdrh   int i, j;                   /* Loop counters */
2172ebed3fa3Sdrh   u32 cnt;                    /* Index added to make the name unique */
2173dc5ea5c7Sdrh   Column *aCol, *pCol;        /* For looping over result columns */
2174dc5ea5c7Sdrh   int nCol;                   /* Number of columns in the result set */
2175dc5ea5c7Sdrh   char *zName;                /* Column name */
2176dc5ea5c7Sdrh   int nName;                  /* Size of name in zName[] */
21770315e3ccSdrh   Hash ht;                    /* Hash table of column names */
21786d5ab2a1Sdrh   Table *pTab;
217979d5f63fSdrh 
21800315e3ccSdrh   sqlite3HashInit(&ht);
21818c2e0f02Sdan   if( pEList ){
21828c2e0f02Sdan     nCol = pEList->nExpr;
21838c2e0f02Sdan     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
21848c2e0f02Sdan     testcase( aCol==0 );
2185080fe6deSdrh     if( NEVER(nCol>32767) ) nCol = 32767;
21868c2e0f02Sdan   }else{
21878c2e0f02Sdan     nCol = 0;
21888c2e0f02Sdan     aCol = 0;
21898c2e0f02Sdan   }
21908836cbbcSdan   assert( nCol==(i16)nCol );
21918c2e0f02Sdan   *pnCol = nCol;
21928c2e0f02Sdan   *paCol = aCol;
21938c2e0f02Sdan 
21940315e3ccSdrh   for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
219518f8600fSdrh     struct ExprList_item *pX = &pEList->a[i];
219645e41b73Sdrh     struct ExprList_item *pCollide;
219779d5f63fSdrh     /* Get an appropriate name for the column
219879d5f63fSdrh     */
2199d88fd539Sdrh     if( (zName = pX->zEName)!=0 && pX->fg.eEName==ENAME_NAME ){
220079d5f63fSdrh       /* If the column contains an "AS <name>" phrase, use <name> as the name */
22017d10d5a6Sdrh     }else{
220218f8600fSdrh       Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pX->pExpr);
2203235667a8Sdrh       while( ALWAYS(pColExpr!=0) && pColExpr->op==TK_DOT ){
2204b07028f7Sdrh         pColExpr = pColExpr->pRight;
2205b07028f7Sdrh         assert( pColExpr!=0 );
2206b07028f7Sdrh       }
2207477572b9Sdrh       if( pColExpr->op==TK_COLUMN
2208477572b9Sdrh        && ALWAYS( ExprUseYTab(pColExpr) )
22095af8a86dSdrh        && ALWAYS( pColExpr->y.pTab!=0 )
2210477572b9Sdrh       ){
221193a960a0Sdrh         /* For columns use the column name name */
2212dc5ea5c7Sdrh         int iCol = pColExpr->iColumn;
22135af8a86dSdrh         pTab = pColExpr->y.pTab;
2214f0209f74Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
2215cf9d36d1Sdrh         zName = iCol>=0 ? pTab->aCol[iCol].zCnName : "rowid";
2216b7916a78Sdrh       }else if( pColExpr->op==TK_ID ){
221733e619fcSdrh         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
221896ceaf86Sdrh         zName = pColExpr->u.zToken;
221993a960a0Sdrh       }else{
222079d5f63fSdrh         /* Use the original text of the column expression as its name */
222118f8600fSdrh         assert( zName==pX->zEName );  /* pointer comparison intended */
22227d10d5a6Sdrh       }
222322f70c32Sdrh     }
22240cbec59cSdrh     if( zName && !sqlite3IsTrueOrFalse(zName) ){
2225d7ca600eSdrh       zName = sqlite3DbStrDup(db, zName);
2226d7ca600eSdrh     }else{
2227155507b3Sdrh       zName = sqlite3MPrintf(db,"column%d",i+1);
2228d7ca600eSdrh     }
222979d5f63fSdrh 
223079d5f63fSdrh     /* Make sure the column name is unique.  If the name is not unique,
223160ec914cSpeter.d.reid     ** append an integer to the name so that it becomes unique.
223279d5f63fSdrh     */
22330315e3ccSdrh     cnt = 0;
223445e41b73Sdrh     while( zName && (pCollide = sqlite3HashFind(&ht, zName))!=0 ){
2235d88fd539Sdrh       if( pCollide->fg.bUsingTerm ){
2236ab843a51Sdrh         pCol->colFlags |= COLFLAG_NOEXPAND;
223745e41b73Sdrh       }
22380315e3ccSdrh       nName = sqlite3Strlen30(zName);
2239f7ee8965Sdrh       if( nName>0 ){
22400315e3ccSdrh         for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
22410315e3ccSdrh         if( zName[j]==':' ) nName = j;
2242f7ee8965Sdrh       }
224396ceaf86Sdrh       zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
2244ebed3fa3Sdrh       if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
224579d5f63fSdrh     }
2246cf9d36d1Sdrh     pCol->zCnName = zName;
2247d44390c8Sdrh     pCol->hName = sqlite3StrIHash(zName);
2248d88fd539Sdrh     if( pX->fg.bNoExpand ){
224972d620bdSdrh       pCol->colFlags |= COLFLAG_NOEXPAND;
225072d620bdSdrh     }
2251ba68f8f3Sdan     sqlite3ColumnPropertiesFromName(0, pCol);
225245e41b73Sdrh     if( zName && sqlite3HashInsert(&ht, zName, pX)==pX ){
22534a642b60Sdrh       sqlite3OomFault(db);
22547d10d5a6Sdrh     }
22550315e3ccSdrh   }
22560315e3ccSdrh   sqlite3HashClear(&ht);
22577d10d5a6Sdrh   if( db->mallocFailed ){
22587d10d5a6Sdrh     for(j=0; j<i; j++){
2259cf9d36d1Sdrh       sqlite3DbFree(db, aCol[j].zCnName);
22607d10d5a6Sdrh     }
22617d10d5a6Sdrh     sqlite3DbFree(db, aCol);
22627d10d5a6Sdrh     *paCol = 0;
22637d10d5a6Sdrh     *pnCol = 0;
2264fad3039cSmistachkin     return SQLITE_NOMEM_BKPT;
22657d10d5a6Sdrh   }
22667d10d5a6Sdrh   return SQLITE_OK;
22677d10d5a6Sdrh }
2268e014a838Sdanielk1977 
22697d10d5a6Sdrh /*
22707d10d5a6Sdrh ** Add type and collation information to a column list based on
22717d10d5a6Sdrh ** a SELECT statement.
22727d10d5a6Sdrh **
22737d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList().
22747d10d5a6Sdrh ** The column list has only names, not types or collations.  This
22757d10d5a6Sdrh ** routine goes through and adds the types and collations.
22767d10d5a6Sdrh **
2277b08a67a7Sshane ** This routine requires that all identifiers in the SELECT
22787d10d5a6Sdrh ** statement be resolved.
227979d5f63fSdrh */
sqlite3SelectAddColumnTypeAndCollation(Parse * pParse,Table * pTab,Select * pSelect,char aff)2280ed06a131Sdrh void sqlite3SelectAddColumnTypeAndCollation(
22817d10d5a6Sdrh   Parse *pParse,        /* Parsing contexts */
2282186ad8ccSdrh   Table *pTab,          /* Add column type information to this table */
228381506b88Sdrh   Select *pSelect,      /* SELECT used to determine types and collations */
228481506b88Sdrh   char aff              /* Default affinity for columns */
22857d10d5a6Sdrh ){
22867d10d5a6Sdrh   sqlite3 *db = pParse->db;
22877d10d5a6Sdrh   NameContext sNC;
22887d10d5a6Sdrh   Column *pCol;
22897d10d5a6Sdrh   CollSeq *pColl;
22907d10d5a6Sdrh   int i;
22917d10d5a6Sdrh   Expr *p;
22927d10d5a6Sdrh   struct ExprList_item *a;
22937d10d5a6Sdrh 
22947d10d5a6Sdrh   assert( pSelect!=0 );
22957d10d5a6Sdrh   assert( (pSelect->selFlags & SF_Resolved)!=0 );
2296186ad8ccSdrh   assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
22977d10d5a6Sdrh   if( db->mallocFailed ) return;
2298c43e8be8Sdrh   memset(&sNC, 0, sizeof(sNC));
2299b3bce662Sdanielk1977   sNC.pSrcList = pSelect->pSrc;
23007d10d5a6Sdrh   a = pSelect->pEList->a;
2301186ad8ccSdrh   for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
2302ed06a131Sdrh     const char *zType;
2303913306a5Sdrh     i64 n, m;
23046f6e60ddSdrh     pTab->tabFlags |= (pCol->colFlags & COLFLAG_NOINSERT);
23057d10d5a6Sdrh     p = a[i].pExpr;
2306cafc2f7bSdrh     zType = columnType(&sNC, p, 0, 0, 0);
2307cafc2f7bSdrh     /* pCol->szEst = ... // Column size est for SELECT tables never used */
2308c60e9b82Sdanielk1977     pCol->affinity = sqlite3ExprAffinity(p);
23090c4db034Sdrh     if( zType ){
23100c4db034Sdrh       m = sqlite3Strlen30(zType);
2311cf9d36d1Sdrh       n = sqlite3Strlen30(pCol->zCnName);
2312cf9d36d1Sdrh       pCol->zCnName = sqlite3DbReallocOrFree(db, pCol->zCnName, n+m+2);
2313cf9d36d1Sdrh       if( pCol->zCnName ){
2314cf9d36d1Sdrh         memcpy(&pCol->zCnName[n+1], zType, m+1);
2315ed06a131Sdrh         pCol->colFlags |= COLFLAG_HASTYPE;
2316146121f5Sdrh       }else{
2317146121f5Sdrh         testcase( pCol->colFlags & COLFLAG_HASTYPE );
2318146121f5Sdrh         pCol->colFlags &= ~(COLFLAG_HASTYPE|COLFLAG_HASCOLL);
2319ed06a131Sdrh       }
2320ed06a131Sdrh     }
232196fb16eeSdrh     if( pCol->affinity<=SQLITE_AFF_NONE ) pCol->affinity = aff;
2322b3bf556eSdanielk1977     pColl = sqlite3ExprCollSeq(pParse, p);
23235ced0a91Sdrh     if( pColl ){
232465b40093Sdrh       assert( pTab->pIndex==0 );
232565b40093Sdrh       sqlite3ColumnSetColl(db, pCol, pColl->zName);
23260202b29eSdanielk1977     }
232722f70c32Sdrh   }
2328cafc2f7bSdrh   pTab->szTabRow = 1; /* Any non-zero value works */
23297d10d5a6Sdrh }
23307d10d5a6Sdrh 
23317d10d5a6Sdrh /*
23327d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes
23337d10d5a6Sdrh ** the result set of that SELECT.
23347d10d5a6Sdrh */
sqlite3ResultSetOfSelect(Parse * pParse,Select * pSelect,char aff)233581506b88Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){
23367d10d5a6Sdrh   Table *pTab;
23377d10d5a6Sdrh   sqlite3 *db = pParse->db;
233870d5dfbaSdrh   u64 savedFlags;
23397d10d5a6Sdrh 
23407d10d5a6Sdrh   savedFlags = db->flags;
2341d5b44d60Sdrh   db->flags &= ~(u64)SQLITE_FullColNames;
23427d10d5a6Sdrh   db->flags |= SQLITE_ShortColNames;
23437d10d5a6Sdrh   sqlite3SelectPrep(pParse, pSelect, 0);
2344491b6d89Sdrh   db->flags = savedFlags;
23457d10d5a6Sdrh   if( pParse->nErr ) return 0;
23467d10d5a6Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
23477d10d5a6Sdrh   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
23487d10d5a6Sdrh   if( pTab==0 ){
23497d10d5a6Sdrh     return 0;
23507d10d5a6Sdrh   }
235179df7782Sdrh   pTab->nTabRef = 1;
23527d10d5a6Sdrh   pTab->zName = 0;
2353cfc9df76Sdan   pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
23548981b904Sdrh   sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
235581506b88Sdrh   sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect, aff);
235622f70c32Sdrh   pTab->iPKey = -1;
23577ce72f69Sdrh   if( db->mallocFailed ){
23581feeaed2Sdan     sqlite3DeleteTable(db, pTab);
23597ce72f69Sdrh     return 0;
23607ce72f69Sdrh   }
236122f70c32Sdrh   return pTab;
236222f70c32Sdrh }
236322f70c32Sdrh 
236422f70c32Sdrh /*
2365d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
2366d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
2367d8bc7086Sdrh */
sqlite3GetVdbe(Parse * pParse)236855965619Sdrh Vdbe *sqlite3GetVdbe(Parse *pParse){
236955965619Sdrh   if( pParse->pVdbe ){
237055965619Sdrh     return pParse->pVdbe;
237155965619Sdrh   }
2372e0e261a4Sdrh   if( pParse->pToplevel==0
2373e0e261a4Sdrh    && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
2374e0e261a4Sdrh   ){
2375e0e261a4Sdrh     pParse->okConstFactor = 1;
2376949f9cd5Sdrh   }
237755965619Sdrh   return sqlite3VdbeCreate(pParse);
23786f077343Sdrh }
2379d8bc7086Sdrh 
238015007a99Sdrh 
2381d8bc7086Sdrh /*
23827b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
23838c0833fbSdrh ** pLimit expressions.  pLimit->pLeft and pLimit->pRight hold the expressions
23847b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
2385a2dc3b1aSdanielk1977 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
2386a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute
2387a2dc3b1aSdanielk1977 ** the limit and offset.  If there is no limit and/or offset, then
2388a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative.
23897b58daeaSdrh **
2390d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if
23918c0833fbSdrh ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight.  iLimit
23928c0833fbSdrh ** and iOffset should have been preset to appropriate default values (zero)
2393aa9ce707Sdrh ** prior to calling this routine.
2394aa9ce707Sdrh **
2395aa9ce707Sdrh ** The iOffset register (if it exists) is initialized to the value
2396aa9ce707Sdrh ** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
2397aa9ce707Sdrh ** iOffset+1 is initialized to LIMIT+OFFSET.
2398aa9ce707Sdrh **
23998c0833fbSdrh ** Only if pLimit->pLeft!=0 do the limit registers get
24007b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
24017b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
24027b58daeaSdrh ** SELECT statements.
24037b58daeaSdrh */
computeLimitRegisters(Parse * pParse,Select * p,int iBreak)2404ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
240502afc861Sdrh   Vdbe *v = 0;
240602afc861Sdrh   int iLimit = 0;
240715007a99Sdrh   int iOffset;
24088b0cf38aSdrh   int n;
24098c0833fbSdrh   Expr *pLimit = p->pLimit;
24108c0833fbSdrh 
24110acb7e48Sdrh   if( p->iLimit ) return;
241215007a99Sdrh 
24137b58daeaSdrh   /*
24147b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
2415f7b5496eSdrh   ** controversy about what the correct behavior should be.
24167b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
24177b58daeaSdrh   ** no rows.
24187b58daeaSdrh   */
24198c0833fbSdrh   if( pLimit ){
24208c0833fbSdrh     assert( pLimit->op==TK_LIMIT );
24218c0833fbSdrh     assert( pLimit->pLeft!=0 );
24220a07c107Sdrh     p->iLimit = iLimit = ++pParse->nMem;
242315007a99Sdrh     v = sqlite3GetVdbe(pParse);
2424aa9ce707Sdrh     assert( v!=0 );
24258c0833fbSdrh     if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
24269b918ed1Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
24279b918ed1Sdrh       VdbeComment((v, "LIMIT counter"));
2428456e4e4fSdrh       if( n==0 ){
2429076e85f5Sdrh         sqlite3VdbeGoto(v, iBreak);
2430c3489bbfSdrh       }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
2431c3489bbfSdrh         p->nSelectRow = sqlite3LogEst((u64)n);
2432c3489bbfSdrh         p->selFlags |= SF_FixedLimit;
24339b918ed1Sdrh       }
24349b918ed1Sdrh     }else{
24358c0833fbSdrh       sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
2436688852abSdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
2437d4e70ebdSdrh       VdbeComment((v, "LIMIT counter"));
243816897072Sdrh       sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
24399b918ed1Sdrh     }
24408c0833fbSdrh     if( pLimit->pRight ){
24410a07c107Sdrh       p->iOffset = iOffset = ++pParse->nMem;
2442b7654111Sdrh       pParse->nMem++;   /* Allocate an extra register for limit+offset */
24438c0833fbSdrh       sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
2444688852abSdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
2445d4e70ebdSdrh       VdbeComment((v, "OFFSET counter"));
2446cc2fa4cfSdrh       sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
2447d4e70ebdSdrh       VdbeComment((v, "LIMIT+OFFSET"));
2448b7654111Sdrh     }
2449d59ba6ceSdrh   }
24507b58daeaSdrh }
24517b58daeaSdrh 
2452b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
2453fbc4ee7bSdrh /*
2454fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
2455fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
2456fbc4ee7bSdrh ** the column has no default collating sequence.
2457fbc4ee7bSdrh **
2458fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
2459fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
2460fbc4ee7bSdrh */
multiSelectCollSeq(Parse * pParse,Select * p,int iCol)2461dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
2462fbc4ee7bSdrh   CollSeq *pRet;
2463dc1bdc4fSdanielk1977   if( p->pPrior ){
2464dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
2465fbc4ee7bSdrh   }else{
2466fbc4ee7bSdrh     pRet = 0;
2467dc1bdc4fSdanielk1977   }
246810c081adSdrh   assert( iCol>=0 );
24692ec18a3cSdrh   /* iCol must be less than p->pEList->nExpr.  Otherwise an error would
24702ec18a3cSdrh   ** have been thrown during name resolution and we would not have gotten
24712ec18a3cSdrh   ** this far */
24722ec18a3cSdrh   if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
2473dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
2474dc1bdc4fSdanielk1977   }
2475dc1bdc4fSdanielk1977   return pRet;
2476d3d39e93Sdrh }
2477d3d39e93Sdrh 
247853bed45eSdan /*
247953bed45eSdan ** The select statement passed as the second parameter is a compound SELECT
248053bed45eSdan ** with an ORDER BY clause. This function allocates and returns a KeyInfo
248153bed45eSdan ** structure suitable for implementing the ORDER BY.
248253bed45eSdan **
248353bed45eSdan ** Space to hold the KeyInfo structure is obtained from malloc. The calling
248453bed45eSdan ** function is responsible for ensuring that this structure is eventually
248553bed45eSdan ** freed.
248653bed45eSdan */
multiSelectOrderByKeyInfo(Parse * pParse,Select * p,int nExtra)248753bed45eSdan static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
248853bed45eSdan   ExprList *pOrderBy = p->pOrderBy;
24897d4c94bcSdrh   int nOrderBy = ALWAYS(pOrderBy!=0) ? pOrderBy->nExpr : 0;
249053bed45eSdan   sqlite3 *db = pParse->db;
249153bed45eSdan   KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
249253bed45eSdan   if( pRet ){
249353bed45eSdan     int i;
249453bed45eSdan     for(i=0; i<nOrderBy; i++){
249553bed45eSdan       struct ExprList_item *pItem = &pOrderBy->a[i];
249653bed45eSdan       Expr *pTerm = pItem->pExpr;
249753bed45eSdan       CollSeq *pColl;
249853bed45eSdan 
249953bed45eSdan       if( pTerm->flags & EP_Collate ){
250053bed45eSdan         pColl = sqlite3ExprCollSeq(pParse, pTerm);
250153bed45eSdan       }else{
250253bed45eSdan         pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
250353bed45eSdan         if( pColl==0 ) pColl = db->pDfltColl;
250453bed45eSdan         pOrderBy->a[i].pExpr =
250553bed45eSdan           sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
250653bed45eSdan       }
250753bed45eSdan       assert( sqlite3KeyInfoIsWriteable(pRet) );
250853bed45eSdan       pRet->aColl[i] = pColl;
2509d88fd539Sdrh       pRet->aSortFlags[i] = pOrderBy->a[i].fg.sortFlags;
251053bed45eSdan     }
251153bed45eSdan   }
251253bed45eSdan 
251353bed45eSdan   return pRet;
251453bed45eSdan }
2515d3d39e93Sdrh 
2516781def29Sdrh #ifndef SQLITE_OMIT_CTE
2517781def29Sdrh /*
2518781def29Sdrh ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
2519781def29Sdrh ** query of the form:
2520781def29Sdrh **
2521781def29Sdrh **   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
2522781def29Sdrh **                         \___________/             \_______________/
2523781def29Sdrh **                           p->pPrior                      p
2524781def29Sdrh **
2525781def29Sdrh **
2526781def29Sdrh ** There is exactly one reference to the recursive-table in the FROM clause
25278a48b9c0Sdrh ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
2528781def29Sdrh **
2529781def29Sdrh ** The setup-query runs once to generate an initial set of rows that go
2530781def29Sdrh ** into a Queue table.  Rows are extracted from the Queue table one by
2531fe1c6bb9Sdrh ** one.  Each row extracted from Queue is output to pDest.  Then the single
2532fe1c6bb9Sdrh ** extracted row (now in the iCurrent table) becomes the content of the
2533fe1c6bb9Sdrh ** recursive-table for a recursive-query run.  The output of the recursive-query
2534781def29Sdrh ** is added back into the Queue table.  Then another row is extracted from Queue
2535781def29Sdrh ** and the iteration continues until the Queue table is empty.
2536781def29Sdrh **
2537781def29Sdrh ** If the compound query operator is UNION then no duplicate rows are ever
2538781def29Sdrh ** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
2539781def29Sdrh ** that have ever been inserted into Queue and causes duplicates to be
2540781def29Sdrh ** discarded.  If the operator is UNION ALL, then duplicates are allowed.
2541781def29Sdrh **
2542781def29Sdrh ** If the query has an ORDER BY, then entries in the Queue table are kept in
2543781def29Sdrh ** ORDER BY order and the first entry is extracted for each cycle.  Without
2544781def29Sdrh ** an ORDER BY, the Queue table is just a FIFO.
2545781def29Sdrh **
2546781def29Sdrh ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
2547781def29Sdrh ** have been output to pDest.  A LIMIT of zero means to output no rows and a
2548781def29Sdrh ** negative LIMIT means to output all rows.  If there is also an OFFSET clause
2549781def29Sdrh ** with a positive value, then the first OFFSET outputs are discarded rather
2550781def29Sdrh ** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
2551781def29Sdrh ** rows have been skipped.
2552781def29Sdrh */
generateWithRecursiveQuery(Parse * pParse,Select * p,SelectDest * pDest)2553781def29Sdrh static void generateWithRecursiveQuery(
2554781def29Sdrh   Parse *pParse,        /* Parsing context */
2555781def29Sdrh   Select *p,            /* The recursive SELECT to be coded */
2556781def29Sdrh   SelectDest *pDest     /* What to do with query results */
2557781def29Sdrh ){
2558781def29Sdrh   SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
2559781def29Sdrh   int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
2560781def29Sdrh   Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
2561e85e1da0Sdrh   Select *pSetup;               /* The setup query */
256234055854Sdrh   Select *pFirstRec;            /* Left-most recursive term */
2563781def29Sdrh   int addrTop;                  /* Top of the loop */
2564781def29Sdrh   int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
2565edf83d1eSdrh   int iCurrent = 0;             /* The Current table */
2566781def29Sdrh   int regCurrent;               /* Register holding Current table */
2567781def29Sdrh   int iQueue;                   /* The Queue table */
2568781def29Sdrh   int iDistinct = 0;            /* To ensure unique results if UNION */
25698e1ee88cSdrh   int eDest = SRT_Fifo;         /* How to write to Queue */
2570781def29Sdrh   SelectDest destQueue;         /* SelectDest targetting the Queue table */
2571781def29Sdrh   int i;                        /* Loop counter */
2572781def29Sdrh   int rc;                       /* Result code */
2573fe1c6bb9Sdrh   ExprList *pOrderBy;           /* The ORDER BY clause */
25748c0833fbSdrh   Expr *pLimit;                 /* Saved LIMIT and OFFSET */
2575aa9ce707Sdrh   int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
2576781def29Sdrh 
25776afa35c9Sdan #ifndef SQLITE_OMIT_WINDOWFUNC
25786afa35c9Sdan   if( p->pWin ){
25796afa35c9Sdan     sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries");
25806afa35c9Sdan     return;
25816afa35c9Sdan   }
25826afa35c9Sdan #endif
25836afa35c9Sdan 
2584781def29Sdrh   /* Obtain authorization to do a recursive query */
2585781def29Sdrh   if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
2586781def29Sdrh 
2587aa9ce707Sdrh   /* Process the LIMIT and OFFSET clauses, if they exist */
2588ec4ccdbcSdrh   addrBreak = sqlite3VdbeMakeLabel(pParse);
258969b9383eSdan   p->nSelectRow = 320;  /* 4 billion rows */
2590aa9ce707Sdrh   computeLimitRegisters(pParse, p, addrBreak);
2591aa9ce707Sdrh   pLimit = p->pLimit;
2592aa9ce707Sdrh   regLimit = p->iLimit;
2593aa9ce707Sdrh   regOffset = p->iOffset;
25948c0833fbSdrh   p->pLimit = 0;
2595aa9ce707Sdrh   p->iLimit = p->iOffset = 0;
259653bed45eSdan   pOrderBy = p->pOrderBy;
2597781def29Sdrh 
2598781def29Sdrh   /* Locate the cursor number of the Current table */
2599781def29Sdrh   for(i=0; ALWAYS(i<pSrc->nSrc); i++){
26008a48b9c0Sdrh     if( pSrc->a[i].fg.isRecursive ){
2601781def29Sdrh       iCurrent = pSrc->a[i].iCursor;
2602781def29Sdrh       break;
2603781def29Sdrh     }
2604781def29Sdrh   }
2605781def29Sdrh 
2606fe1c6bb9Sdrh   /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
2607781def29Sdrh   ** the Distinct table must be exactly one greater than Queue in order
26088e1ee88cSdrh   ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
2609781def29Sdrh   iQueue = pParse->nTab++;
2610781def29Sdrh   if( p->op==TK_UNION ){
26118e1ee88cSdrh     eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
2612781def29Sdrh     iDistinct = pParse->nTab++;
2613fe1c6bb9Sdrh   }else{
26148e1ee88cSdrh     eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
2615781def29Sdrh   }
2616781def29Sdrh   sqlite3SelectDestInit(&destQueue, eDest, iQueue);
2617781def29Sdrh 
2618781def29Sdrh   /* Allocate cursors for Current, Queue, and Distinct. */
2619781def29Sdrh   regCurrent = ++pParse->nMem;
2620781def29Sdrh   sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
2621fe1c6bb9Sdrh   if( pOrderBy ){
262253bed45eSdan     KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
2623fe1c6bb9Sdrh     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
2624fe1c6bb9Sdrh                       (char*)pKeyInfo, P4_KEYINFO);
2625fe1c6bb9Sdrh     destQueue.pOrderBy = pOrderBy;
2626fe1c6bb9Sdrh   }else{
2627781def29Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
2628fe1c6bb9Sdrh   }
2629fe1c6bb9Sdrh   VdbeComment((v, "Queue table"));
2630781def29Sdrh   if( iDistinct ){
2631781def29Sdrh     p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
2632781def29Sdrh     p->selFlags |= SF_UsesEphemeral;
2633781def29Sdrh   }
2634781def29Sdrh 
263553bed45eSdan   /* Detach the ORDER BY clause from the compound SELECT */
263653bed45eSdan   p->pOrderBy = 0;
263753bed45eSdan 
263834055854Sdrh   /* Figure out how many elements of the compound SELECT are part of the
263934055854Sdrh   ** recursive query.  Make sure no recursive elements use aggregate
264034055854Sdrh   ** functions.  Mark the recursive elements as UNION ALL even if they
264134055854Sdrh   ** are really UNION because the distinctness will be enforced by the
264234055854Sdrh   ** iDistinct table.  pFirstRec is left pointing to the left-most
264334055854Sdrh   ** recursive term of the CTE.
264434055854Sdrh   */
264534055854Sdrh   for(pFirstRec=p; ALWAYS(pFirstRec!=0); pFirstRec=pFirstRec->pPrior){
264634055854Sdrh     if( pFirstRec->selFlags & SF_Aggregate ){
264734055854Sdrh       sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
264834055854Sdrh       goto end_of_recursive_query;
264934055854Sdrh     }
265034055854Sdrh     pFirstRec->op = TK_ALL;
265134055854Sdrh     if( (pFirstRec->pPrior->selFlags & SF_Recursive)==0 ) break;
265234055854Sdrh   }
265334055854Sdrh 
2654781def29Sdrh   /* Store the results of the setup-query in Queue. */
265534055854Sdrh   pSetup = pFirstRec->pPrior;
2656d227a291Sdrh   pSetup->pNext = 0;
265784a01debSdrh   ExplainQueryPlan((pParse, 1, "SETUP"));
2658781def29Sdrh   rc = sqlite3Select(pParse, pSetup, &destQueue);
2659d227a291Sdrh   pSetup->pNext = p;
2660fe1c6bb9Sdrh   if( rc ) goto end_of_recursive_query;
2661781def29Sdrh 
2662781def29Sdrh   /* Find the next row in the Queue and output that row */
2663688852abSdrh   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
2664781def29Sdrh 
2665781def29Sdrh   /* Transfer the next row in Queue over to Current */
2666781def29Sdrh   sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
2667fe1c6bb9Sdrh   if( pOrderBy ){
2668fe1c6bb9Sdrh     sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
2669fe1c6bb9Sdrh   }else{
2670781def29Sdrh     sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
2671fe1c6bb9Sdrh   }
2672781def29Sdrh   sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
2673781def29Sdrh 
2674fe1c6bb9Sdrh   /* Output the single row in Current */
2675ec4ccdbcSdrh   addrCont = sqlite3VdbeMakeLabel(pParse);
2676aa9ce707Sdrh   codeOffset(v, regOffset, addrCont);
26772def2f7eSdrh   selectInnerLoop(pParse, p, iCurrent,
2678079a3072Sdrh       0, 0, pDest, addrCont, addrBreak);
2679688852abSdrh   if( regLimit ){
268016897072Sdrh     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
2681688852abSdrh     VdbeCoverage(v);
2682688852abSdrh   }
2683fe1c6bb9Sdrh   sqlite3VdbeResolveLabel(v, addrCont);
2684fe1c6bb9Sdrh 
2685781def29Sdrh   /* Execute the recursive SELECT taking the single row in Current as
2686781def29Sdrh   ** the value for the recursive-table. Store the results in the Queue.
2687781def29Sdrh   */
268834055854Sdrh   pFirstRec->pPrior = 0;
268984a01debSdrh   ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
2690781def29Sdrh   sqlite3Select(pParse, p, &destQueue);
269134055854Sdrh   assert( pFirstRec->pPrior==0 );
269234055854Sdrh   pFirstRec->pPrior = pSetup;
2693781def29Sdrh 
2694781def29Sdrh   /* Keep running the loop until the Queue is empty */
2695076e85f5Sdrh   sqlite3VdbeGoto(v, addrTop);
2696781def29Sdrh   sqlite3VdbeResolveLabel(v, addrBreak);
2697fe1c6bb9Sdrh 
2698fe1c6bb9Sdrh end_of_recursive_query:
26999afccba2Sdan   sqlite3ExprListDelete(pParse->db, p->pOrderBy);
2700fe1c6bb9Sdrh   p->pOrderBy = pOrderBy;
2701aa9ce707Sdrh   p->pLimit = pLimit;
2702fe1c6bb9Sdrh   return;
2703781def29Sdrh }
2704b68b9778Sdan #endif /* SQLITE_OMIT_CTE */
2705781def29Sdrh 
2706781def29Sdrh /* Forward references */
2707b21e7c70Sdrh static int multiSelectOrderBy(
2708b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
2709b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
2710a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
2711b21e7c70Sdrh );
2712b21e7c70Sdrh 
271345f54a57Sdrh /*
271445f54a57Sdrh ** Handle the special case of a compound-select that originates from a
271545f54a57Sdrh ** VALUES clause.  By handling this as a special case, we avoid deep
271645f54a57Sdrh ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
271745f54a57Sdrh ** on a VALUES clause.
271845f54a57Sdrh **
271945f54a57Sdrh ** Because the Select object originates from a VALUES clause:
2720b058d054Sdrh **   (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
272145f54a57Sdrh **   (2) All terms are UNION ALL
272245f54a57Sdrh **   (3) There is no ORDER BY clause
2723b058d054Sdrh **
2724b058d054Sdrh ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
2725b058d054Sdrh ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
2726b058d054Sdrh ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
2727d1f0a86cSdrh ** Since the limit is exactly 1, we only need to evaluate the left-most VALUES.
272845f54a57Sdrh */
multiSelectValues(Parse * pParse,Select * p,SelectDest * pDest)272945f54a57Sdrh static int multiSelectValues(
273045f54a57Sdrh   Parse *pParse,        /* Parsing context */
273145f54a57Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
273245f54a57Sdrh   SelectDest *pDest     /* What to do with query results */
273345f54a57Sdrh ){
273445f54a57Sdrh   int nRow = 1;
273545f54a57Sdrh   int rc = 0;
2736fa16f5d9Sdrh   int bShowAll = p->pLimit==0;
2737772460fdSdrh   assert( p->selFlags & SF_MultiValue );
273845f54a57Sdrh   do{
273945f54a57Sdrh     assert( p->selFlags & SF_Values );
274045f54a57Sdrh     assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
2741923cadb1Sdan     assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
2742ef9f719dSdrh #ifndef SQLITE_OMIT_WINDOWFUNC
274329cdbadfSdrh     if( p->pWin ) return -1;
2744ef9f719dSdrh #endif
274545f54a57Sdrh     if( p->pPrior==0 ) break;
274645f54a57Sdrh     assert( p->pPrior->pNext==p );
274745f54a57Sdrh     p = p->pPrior;
2748fa16f5d9Sdrh     nRow += bShowAll;
274945f54a57Sdrh   }while(1);
2750fa16f5d9Sdrh   ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
2751fa16f5d9Sdrh                     nRow==1 ? "" : "S"));
275245f54a57Sdrh   while( p ){
2753fa16f5d9Sdrh     selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
2754fa16f5d9Sdrh     if( !bShowAll ) break;
275545f54a57Sdrh     p->nSelectRow = nRow;
275645f54a57Sdrh     p = p->pNext;
275745f54a57Sdrh   }
275845f54a57Sdrh   return rc;
275945f54a57Sdrh }
2760b21e7c70Sdrh 
2761d3d39e93Sdrh /*
276234055854Sdrh ** Return true if the SELECT statement which is known to be the recursive
276334055854Sdrh ** part of a recursive CTE still has its anchor terms attached.  If the
276434055854Sdrh ** anchor terms have already been removed, then return false.
276534055854Sdrh */
hasAnchor(Select * p)276634055854Sdrh static int hasAnchor(Select *p){
276734055854Sdrh   while( p && (p->selFlags & SF_Recursive)!=0 ){ p = p->pPrior; }
276834055854Sdrh   return p!=0;
276934055854Sdrh }
277034055854Sdrh 
277134055854Sdrh /*
277216ee60ffSdrh ** This routine is called to process a compound query form from
277316ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
277416ee60ffSdrh ** INTERSECT
2775c926afbcSdrh **
2776e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
2777e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
2778e78e8284Sdrh ** in which case this routine will be called recursively.
2779e78e8284Sdrh **
2780e78e8284Sdrh ** The results of the total query are to be written into a destination
2781e78e8284Sdrh ** of type eDest with parameter iParm.
2782e78e8284Sdrh **
2783e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
2784e78e8284Sdrh **
2785e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
2786e78e8284Sdrh **
2787e78e8284Sdrh ** This statement is parsed up as follows:
2788e78e8284Sdrh **
2789e78e8284Sdrh **     SELECT c FROM t3
2790e78e8284Sdrh **      |
2791e78e8284Sdrh **      `----->  SELECT b FROM t2
2792e78e8284Sdrh **                |
27934b11c6d3Sjplyon **                `------>  SELECT a FROM t1
2794e78e8284Sdrh **
2795e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
2796e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
2797e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
2798e78e8284Sdrh **
2799e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
2800e78e8284Sdrh ** individual selects always group from left to right.
280182c3d636Sdrh */
multiSelect(Parse * pParse,Select * p,SelectDest * pDest)280284ac9d02Sdanielk1977 static int multiSelect(
2803fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
2804fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
2805a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
280684ac9d02Sdanielk1977 ){
280784ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
280810e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
280910e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
28101013c932Sdrh   SelectDest dest;      /* Alternative data destination */
2811eca7e01aSdanielk1977   Select *pDelete = 0;  /* Chain of simple selects to delete */
2812633e6d57Sdrh   sqlite3 *db;          /* Database connection */
281382c3d636Sdrh 
28147b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
2815fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
281682c3d636Sdrh   */
2817701bb3b4Sdrh   assert( p && p->pPrior );  /* Calling function guarantees this much */
2818eae73fbfSdan   assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
2819b0968b6bSdrh   assert( p->selFlags & SF_Compound );
2820633e6d57Sdrh   db = pParse->db;
2821d8bc7086Sdrh   pPrior = p->pPrior;
2822bc10377aSdrh   dest = *pDest;
2823aae0f74eSdrh   assert( pPrior->pOrderBy==0 );
2824aae0f74eSdrh   assert( pPrior->pLimit==0 );
282582c3d636Sdrh 
28264adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
2827701bb3b4Sdrh   assert( v!=0 );  /* The VDBE already created by calling function */
2828d8bc7086Sdrh 
28291cc3d75fSdrh   /* Create the destination temporary table if necessary
28301cc3d75fSdrh   */
28316c8c8ce0Sdanielk1977   if( dest.eDest==SRT_EphemTab ){
2832b4964b72Sdanielk1977     assert( p->pEList );
28332b596da8Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
28346c8c8ce0Sdanielk1977     dest.eDest = SRT_Table;
28351cc3d75fSdrh   }
28361cc3d75fSdrh 
283745f54a57Sdrh   /* Special handling for a compound-select that originates as a VALUES clause.
283845f54a57Sdrh   */
2839772460fdSdrh   if( p->selFlags & SF_MultiValue ){
284045f54a57Sdrh     rc = multiSelectValues(pParse, p, &dest);
284129cdbadfSdrh     if( rc>=0 ) goto multi_select_end;
284229cdbadfSdrh     rc = SQLITE_OK;
284345f54a57Sdrh   }
284445f54a57Sdrh 
2845f6e369a1Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
2846f6e369a1Sdrh   ** in their result sets.
2847f6e369a1Sdrh   */
2848f6e369a1Sdrh   assert( p->pEList && pPrior->pEList );
2849923cadb1Sdan   assert( p->pEList->nExpr==pPrior->pEList->nExpr );
2850f6e369a1Sdrh 
2851eede6a53Sdan #ifndef SQLITE_OMIT_CTE
285234055854Sdrh   if( (p->selFlags & SF_Recursive)!=0 && hasAnchor(p) ){
2853781def29Sdrh     generateWithRecursiveQuery(pParse, p, &dest);
28548ce7184bSdan   }else
28558ce7184bSdan #endif
2856f6e369a1Sdrh 
2857a9671a22Sdrh   /* Compound SELECTs that have an ORDER BY clause are handled separately.
2858a9671a22Sdrh   */
2859f6e369a1Sdrh   if( p->pOrderBy ){
2860a9671a22Sdrh     return multiSelectOrderBy(pParse, p, pDest);
286103c3905fSdrh   }else{
2862f6e369a1Sdrh 
2863c631ded5Sdrh #ifndef SQLITE_OMIT_EXPLAIN
286403c3905fSdrh     if( pPrior->pPrior==0 ){
28654d79983cSdrh       ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
2866c631ded5Sdrh       ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
2867c631ded5Sdrh     }
2868c631ded5Sdrh #endif
2869c631ded5Sdrh 
2870f46f905aSdrh     /* Generate code for the left and right SELECT statements.
2871d8bc7086Sdrh     */
287282c3d636Sdrh     switch( p->op ){
2873f46f905aSdrh       case TK_ALL: {
2874ec7429aeSdrh         int addr = 0;
2875252d582aSdrh         int nLimit = 0;  /* Initialize to suppress harmless compiler warning */
2876a2dc3b1aSdanielk1977         assert( !pPrior->pLimit );
2877547180baSdrh         pPrior->iLimit = p->iLimit;
2878547180baSdrh         pPrior->iOffset = p->iOffset;
2879a2dc3b1aSdanielk1977         pPrior->pLimit = p->pLimit;
288093ffb50fSdrh         SELECTTRACE(1, pParse, p, ("multiSelect UNION ALL left...\n"));
28817d10d5a6Sdrh         rc = sqlite3Select(pParse, pPrior, &dest);
2882bc7819d1Sdrh         pPrior->pLimit = 0;
288384ac9d02Sdanielk1977         if( rc ){
288484ac9d02Sdanielk1977           goto multi_select_end;
288584ac9d02Sdanielk1977         }
2886f46f905aSdrh         p->pPrior = 0;
28877b58daeaSdrh         p->iLimit = pPrior->iLimit;
28887b58daeaSdrh         p->iOffset = pPrior->iOffset;
288992b01d53Sdrh         if( p->iLimit ){
289016897072Sdrh           addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
2891d4e70ebdSdrh           VdbeComment((v, "Jump ahead if LIMIT reached"));
28929f1ef45fSdrh           if( p->iOffset ){
2893cc2fa4cfSdrh             sqlite3VdbeAddOp3(v, OP_OffsetLimit,
2894cc2fa4cfSdrh                               p->iLimit, p->iOffset+1, p->iOffset);
28959f1ef45fSdrh           }
2896ec7429aeSdrh         }
2897c631ded5Sdrh         ExplainQueryPlan((pParse, 1, "UNION ALL"));
289893ffb50fSdrh         SELECTTRACE(1, pParse, p, ("multiSelect UNION ALL right...\n"));
28997d10d5a6Sdrh         rc = sqlite3Select(pParse, p, &dest);
2900373cc2ddSdrh         testcase( rc!=SQLITE_OK );
2901eca7e01aSdanielk1977         pDelete = p->pPrior;
2902f46f905aSdrh         p->pPrior = pPrior;
2903c3489bbfSdrh         p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
2904bc7819d1Sdrh         if( p->pLimit
2905bc7819d1Sdrh          && sqlite3ExprIsInteger(p->pLimit->pLeft, &nLimit)
2906c3489bbfSdrh          && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
290795aa47b1Sdrh         ){
2908c3489bbfSdrh           p->nSelectRow = sqlite3LogEst((u64)nLimit);
290995aa47b1Sdrh         }
2910ec7429aeSdrh         if( addr ){
2911ec7429aeSdrh           sqlite3VdbeJumpHere(v, addr);
2912ec7429aeSdrh         }
2913f46f905aSdrh         break;
2914f46f905aSdrh       }
291582c3d636Sdrh       case TK_EXCEPT:
291682c3d636Sdrh       case TK_UNION: {
291703c3905fSdrh         int unionTab;    /* Cursor number of the temp table holding result */
2918ea678832Sdrh         u8 op = 0;       /* One of the SRT_ operations to apply to self */
2919d8bc7086Sdrh         int priorOp;     /* The SRT_ operation to apply to prior selects */
29208c0833fbSdrh         Expr *pLimit;    /* Saved values of p->nLimit  */
2921dc1bdc4fSdanielk1977         int addr;
29226c8c8ce0Sdanielk1977         SelectDest uniondest;
292382c3d636Sdrh 
2924373cc2ddSdrh         testcase( p->op==TK_EXCEPT );
2925373cc2ddSdrh         testcase( p->op==TK_UNION );
292693a960a0Sdrh         priorOp = SRT_Union;
2927d227a291Sdrh         if( dest.eDest==priorOp ){
2928d8bc7086Sdrh           /* We can reuse a temporary table generated by a SELECT to our
2929c926afbcSdrh           ** right.
2930d8bc7086Sdrh           */
2931e2f02bacSdrh           assert( p->pLimit==0 );      /* Not allowed on leftward elements */
29322b596da8Sdrh           unionTab = dest.iSDParm;
293382c3d636Sdrh         }else{
2934d8bc7086Sdrh           /* We will need to create our own temporary table to hold the
2935d8bc7086Sdrh           ** intermediate results.
2936d8bc7086Sdrh           */
293782c3d636Sdrh           unionTab = pParse->nTab++;
293893a960a0Sdrh           assert( p->pOrderBy==0 );
293966a5167bSdrh           addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
2940b9bb7c18Sdrh           assert( p->addrOpenEphm[0] == -1 );
2941b9bb7c18Sdrh           p->addrOpenEphm[0] = addr;
2942d227a291Sdrh           findRightmost(p)->selFlags |= SF_UsesEphemeral;
294384ac9d02Sdanielk1977           assert( p->pEList );
2944d8bc7086Sdrh         }
2945d8bc7086Sdrh 
294634055854Sdrh 
2947d8bc7086Sdrh         /* Code the SELECT statements to our left
2948d8bc7086Sdrh         */
2949b3bce662Sdanielk1977         assert( !pPrior->pOrderBy );
29501013c932Sdrh         sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
295193ffb50fSdrh         SELECTTRACE(1, pParse, p, ("multiSelect EXCEPT/UNION left...\n"));
29527d10d5a6Sdrh         rc = sqlite3Select(pParse, pPrior, &uniondest);
295384ac9d02Sdanielk1977         if( rc ){
295484ac9d02Sdanielk1977           goto multi_select_end;
295584ac9d02Sdanielk1977         }
2956d8bc7086Sdrh 
2957d8bc7086Sdrh         /* Code the current SELECT statement
2958d8bc7086Sdrh         */
29594cfb22f7Sdrh         if( p->op==TK_EXCEPT ){
29604cfb22f7Sdrh           op = SRT_Except;
29614cfb22f7Sdrh         }else{
29624cfb22f7Sdrh           assert( p->op==TK_UNION );
29634cfb22f7Sdrh           op = SRT_Union;
2964d8bc7086Sdrh         }
296582c3d636Sdrh         p->pPrior = 0;
2966a2dc3b1aSdanielk1977         pLimit = p->pLimit;
2967a2dc3b1aSdanielk1977         p->pLimit = 0;
29686c8c8ce0Sdanielk1977         uniondest.eDest = op;
2969c631ded5Sdrh         ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
2970aae0f74eSdrh                           sqlite3SelectOpName(p->op)));
297193ffb50fSdrh         SELECTTRACE(1, pParse, p, ("multiSelect EXCEPT/UNION right...\n"));
29727d10d5a6Sdrh         rc = sqlite3Select(pParse, p, &uniondest);
2973373cc2ddSdrh         testcase( rc!=SQLITE_OK );
2974b7cbf5c1Sdrh         assert( p->pOrderBy==0 );
2975eca7e01aSdanielk1977         pDelete = p->pPrior;
297682c3d636Sdrh         p->pPrior = pPrior;
2977a9671a22Sdrh         p->pOrderBy = 0;
2978c3489bbfSdrh         if( p->op==TK_UNION ){
2979c3489bbfSdrh           p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
2980c3489bbfSdrh         }
2981633e6d57Sdrh         sqlite3ExprDelete(db, p->pLimit);
2982a2dc3b1aSdanielk1977         p->pLimit = pLimit;
298392b01d53Sdrh         p->iLimit = 0;
298492b01d53Sdrh         p->iOffset = 0;
2985d8bc7086Sdrh 
2986d8bc7086Sdrh         /* Convert the data in the temporary table into whatever form
2987d8bc7086Sdrh         ** it is that we currently need.
2988d8bc7086Sdrh         */
29892b596da8Sdrh         assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
2990a9ebfe20Sdrh         assert( p->pEList || db->mallocFailed );
2991a9ebfe20Sdrh         if( dest.eDest!=priorOp && db->mallocFailed==0 ){
29926b56344dSdrh           int iCont, iBreak, iStart;
2993ec4ccdbcSdrh           iBreak = sqlite3VdbeMakeLabel(pParse);
2994ec4ccdbcSdrh           iCont = sqlite3VdbeMakeLabel(pParse);
2995ec7429aeSdrh           computeLimitRegisters(pParse, p, iBreak);
2996688852abSdrh           sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
29974adee20fSdanielk1977           iStart = sqlite3VdbeCurrentAddr(v);
29982def2f7eSdrh           selectInnerLoop(pParse, p, unionTab,
2999e8e4af76Sdrh                           0, 0, &dest, iCont, iBreak);
30004adee20fSdanielk1977           sqlite3VdbeResolveLabel(v, iCont);
3001688852abSdrh           sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
30024adee20fSdanielk1977           sqlite3VdbeResolveLabel(v, iBreak);
300366a5167bSdrh           sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
300482c3d636Sdrh         }
300582c3d636Sdrh         break;
300682c3d636Sdrh       }
3007373cc2ddSdrh       default: assert( p->op==TK_INTERSECT ); {
300882c3d636Sdrh         int tab1, tab2;
30096b56344dSdrh         int iCont, iBreak, iStart;
30108c0833fbSdrh         Expr *pLimit;
3011dc1bdc4fSdanielk1977         int addr;
30121013c932Sdrh         SelectDest intersectdest;
30139cbf3425Sdrh         int r1;
301482c3d636Sdrh 
3015d8bc7086Sdrh         /* INTERSECT is different from the others since it requires
30166206d50aSdrh         ** two temporary tables.  Hence it has its own case.  Begin
3017d8bc7086Sdrh         ** by allocating the tables we will need.
3018d8bc7086Sdrh         */
301982c3d636Sdrh         tab1 = pParse->nTab++;
302082c3d636Sdrh         tab2 = pParse->nTab++;
302193a960a0Sdrh         assert( p->pOrderBy==0 );
3022dc1bdc4fSdanielk1977 
302366a5167bSdrh         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
3024b9bb7c18Sdrh         assert( p->addrOpenEphm[0] == -1 );
3025b9bb7c18Sdrh         p->addrOpenEphm[0] = addr;
3026d227a291Sdrh         findRightmost(p)->selFlags |= SF_UsesEphemeral;
302784ac9d02Sdanielk1977         assert( p->pEList );
3028d8bc7086Sdrh 
3029d8bc7086Sdrh         /* Code the SELECTs to our left into temporary table "tab1".
3030d8bc7086Sdrh         */
30311013c932Sdrh         sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
303293ffb50fSdrh         SELECTTRACE(1, pParse, p, ("multiSelect INTERSECT left...\n"));
30337d10d5a6Sdrh         rc = sqlite3Select(pParse, pPrior, &intersectdest);
303484ac9d02Sdanielk1977         if( rc ){
303584ac9d02Sdanielk1977           goto multi_select_end;
303684ac9d02Sdanielk1977         }
3037d8bc7086Sdrh 
3038d8bc7086Sdrh         /* Code the current SELECT into temporary table "tab2"
3039d8bc7086Sdrh         */
304066a5167bSdrh         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
3041b9bb7c18Sdrh         assert( p->addrOpenEphm[1] == -1 );
3042b9bb7c18Sdrh         p->addrOpenEphm[1] = addr;
304382c3d636Sdrh         p->pPrior = 0;
3044a2dc3b1aSdanielk1977         pLimit = p->pLimit;
3045a2dc3b1aSdanielk1977         p->pLimit = 0;
30462b596da8Sdrh         intersectdest.iSDParm = tab2;
3047c631ded5Sdrh         ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
3048aae0f74eSdrh                           sqlite3SelectOpName(p->op)));
304993ffb50fSdrh         SELECTTRACE(1, pParse, p, ("multiSelect INTERSECT right...\n"));
30507d10d5a6Sdrh         rc = sqlite3Select(pParse, p, &intersectdest);
3051373cc2ddSdrh         testcase( rc!=SQLITE_OK );
3052eca7e01aSdanielk1977         pDelete = p->pPrior;
305382c3d636Sdrh         p->pPrior = pPrior;
305403c3905fSdrh         if( p->nSelectRow>pPrior->nSelectRow ){
305503c3905fSdrh           p->nSelectRow = pPrior->nSelectRow;
305603c3905fSdrh         }
3057633e6d57Sdrh         sqlite3ExprDelete(db, p->pLimit);
3058a2dc3b1aSdanielk1977         p->pLimit = pLimit;
3059d8bc7086Sdrh 
3060d8bc7086Sdrh         /* Generate code to take the intersection of the two temporary
3061d8bc7086Sdrh         ** tables.
3062d8bc7086Sdrh         */
30635f695124Sdrh         if( rc ) break;
306482c3d636Sdrh         assert( p->pEList );
3065ec4ccdbcSdrh         iBreak = sqlite3VdbeMakeLabel(pParse);
3066ec4ccdbcSdrh         iCont = sqlite3VdbeMakeLabel(pParse);
3067ec7429aeSdrh         computeLimitRegisters(pParse, p, iBreak);
3068688852abSdrh         sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
30699cbf3425Sdrh         r1 = sqlite3GetTempReg(pParse);
30709057fc7cSdrh         iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
307103c3905fSdrh         sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
307203c3905fSdrh         VdbeCoverage(v);
30739cbf3425Sdrh         sqlite3ReleaseTempReg(pParse, r1);
30742def2f7eSdrh         selectInnerLoop(pParse, p, tab1,
3075e8e4af76Sdrh                         0, 0, &dest, iCont, iBreak);
30764adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
3077688852abSdrh         sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
30784adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
307966a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
308066a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
308182c3d636Sdrh         break;
308282c3d636Sdrh       }
308382c3d636Sdrh     }
30848cdbf836Sdrh 
3085c631ded5Sdrh   #ifndef SQLITE_OMIT_EXPLAIN
3086c631ded5Sdrh     if( p->pNext==0 ){
3087e2ca99c9Sdrh       ExplainQueryPlanPop(pParse);
3088c631ded5Sdrh     }
3089c631ded5Sdrh   #endif
309003c3905fSdrh   }
30918428b3b4Sdrh   if( pParse->nErr ) goto multi_select_end;
30927f61e92cSdan 
3093a9671a22Sdrh   /* Compute collating sequences used by
3094a9671a22Sdrh   ** temporary tables needed to implement the compound select.
3095a9671a22Sdrh   ** Attach the KeyInfo structure to all temporary tables.
30968cdbf836Sdrh   **
30978cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
30988cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
30998cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
31008cdbf836Sdrh   ** no temp tables are required.
3101fbc4ee7bSdrh   */
31027d10d5a6Sdrh   if( p->selFlags & SF_UsesEphemeral ){
3103fbc4ee7bSdrh     int i;                        /* Loop counter */
3104fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
31050342b1f5Sdrh     Select *pLoop;                /* For looping through SELECT statements */
3106f68d7d17Sdrh     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
310793a960a0Sdrh     int nCol;                     /* Number of columns in result set */
3108fbc4ee7bSdrh 
3109d227a291Sdrh     assert( p->pNext==0 );
3110aa6fe5bfSdrh     assert( p->pEList!=0 );
311193a960a0Sdrh     nCol = p->pEList->nExpr;
3112ad124329Sdrh     pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
3113dc1bdc4fSdanielk1977     if( !pKeyInfo ){
3114fad3039cSmistachkin       rc = SQLITE_NOMEM_BKPT;
3115dc1bdc4fSdanielk1977       goto multi_select_end;
3116dc1bdc4fSdanielk1977     }
31170342b1f5Sdrh     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
31180342b1f5Sdrh       *apColl = multiSelectCollSeq(pParse, p, i);
31190342b1f5Sdrh       if( 0==*apColl ){
3120633e6d57Sdrh         *apColl = db->pDfltColl;
3121dc1bdc4fSdanielk1977       }
3122dc1bdc4fSdanielk1977     }
3123dc1bdc4fSdanielk1977 
31240342b1f5Sdrh     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
31250342b1f5Sdrh       for(i=0; i<2; i++){
3126b9bb7c18Sdrh         int addr = pLoop->addrOpenEphm[i];
31270342b1f5Sdrh         if( addr<0 ){
31280342b1f5Sdrh           /* If [0] is unused then [1] is also unused.  So we can
31290342b1f5Sdrh           ** always safely abort as soon as the first unused slot is found */
3130b9bb7c18Sdrh           assert( pLoop->addrOpenEphm[1]<0 );
31310342b1f5Sdrh           break;
31320342b1f5Sdrh         }
31330342b1f5Sdrh         sqlite3VdbeChangeP2(v, addr, nCol);
31342ec2fb22Sdrh         sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
31352ec2fb22Sdrh                             P4_KEYINFO);
31360ee5a1e7Sdrh         pLoop->addrOpenEphm[i] = -1;
31370342b1f5Sdrh       }
3138dc1bdc4fSdanielk1977     }
31392ec2fb22Sdrh     sqlite3KeyInfoUnref(pKeyInfo);
3140dc1bdc4fSdanielk1977   }
3141dc1bdc4fSdanielk1977 
3142dc1bdc4fSdanielk1977 multi_select_end:
31432b596da8Sdrh   pDest->iSdst = dest.iSdst;
31442b596da8Sdrh   pDest->nSdst = dest.nSdst;
3145ce68b6bfSdrh   if( pDelete ){
3146ce68b6bfSdrh     sqlite3ParserAddCleanup(pParse,
3147ce68b6bfSdrh         (void(*)(sqlite3*,void*))sqlite3SelectDelete,
3148ce68b6bfSdrh         pDelete);
3149ce68b6bfSdrh   }
315084ac9d02Sdanielk1977   return rc;
31512282792aSdrh }
3152b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
31532282792aSdrh 
3154b21e7c70Sdrh /*
315589b31d73Smistachkin ** Error message for when two or more terms of a compound select have different
315689b31d73Smistachkin ** size result sets.
315789b31d73Smistachkin */
sqlite3SelectWrongNumTermsError(Parse * pParse,Select * p)315889b31d73Smistachkin void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
315989b31d73Smistachkin   if( p->selFlags & SF_Values ){
316089b31d73Smistachkin     sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
316189b31d73Smistachkin   }else{
316289b31d73Smistachkin     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
3163aae0f74eSdrh       " do not have the same number of result columns",
3164aae0f74eSdrh       sqlite3SelectOpName(p->op));
316589b31d73Smistachkin   }
316689b31d73Smistachkin }
316789b31d73Smistachkin 
316889b31d73Smistachkin /*
3169b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a
3170b21e7c70Sdrh ** SELECT statment.
31710acb7e48Sdrh **
31722b596da8Sdrh ** The data to be output is contained in pIn->iSdst.  There are
31732b596da8Sdrh ** pIn->nSdst columns to be output.  pDest is where the output should
31740acb7e48Sdrh ** be sent.
31750acb7e48Sdrh **
31760acb7e48Sdrh ** regReturn is the number of the register holding the subroutine
31770acb7e48Sdrh ** return address.
31780acb7e48Sdrh **
3179f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that
31800acb7e48Sdrh ** records the previous output.  mem[regPrev] is a flag that is false
31810acb7e48Sdrh ** if there has been no previous output.  If regPrev>0 then code is
31820acb7e48Sdrh ** generated to suppress duplicates.  pKeyInfo is used for comparing
31830acb7e48Sdrh ** keys.
31840acb7e48Sdrh **
31850acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to
31860acb7e48Sdrh ** iBreak.
3187b21e7c70Sdrh */
generateOutputSubroutine(Parse * pParse,Select * p,SelectDest * pIn,SelectDest * pDest,int regReturn,int regPrev,KeyInfo * pKeyInfo,int iBreak)31880acb7e48Sdrh static int generateOutputSubroutine(
318992b01d53Sdrh   Parse *pParse,          /* Parsing context */
319092b01d53Sdrh   Select *p,              /* The SELECT statement */
319192b01d53Sdrh   SelectDest *pIn,        /* Coroutine supplying data */
319292b01d53Sdrh   SelectDest *pDest,      /* Where to send the data */
319392b01d53Sdrh   int regReturn,          /* The return address register */
31940acb7e48Sdrh   int regPrev,            /* Previous result register.  No uniqueness if 0 */
31950acb7e48Sdrh   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
319692b01d53Sdrh   int iBreak              /* Jump here if we hit the LIMIT */
3197b21e7c70Sdrh ){
3198b21e7c70Sdrh   Vdbe *v = pParse->pVdbe;
319992b01d53Sdrh   int iContinue;
320092b01d53Sdrh   int addr;
3201b21e7c70Sdrh 
320292b01d53Sdrh   addr = sqlite3VdbeCurrentAddr(v);
3203ec4ccdbcSdrh   iContinue = sqlite3VdbeMakeLabel(pParse);
32040acb7e48Sdrh 
32050acb7e48Sdrh   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
32060acb7e48Sdrh   */
32070acb7e48Sdrh   if( regPrev ){
3208728e0f91Sdrh     int addr1, addr2;
3209728e0f91Sdrh     addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
3210728e0f91Sdrh     addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
32112ec2fb22Sdrh                               (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
3212728e0f91Sdrh     sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
3213728e0f91Sdrh     sqlite3VdbeJumpHere(v, addr1);
3214e8e4af76Sdrh     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
3215ec86c724Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
32160acb7e48Sdrh   }
32171f9caa41Sdanielk1977   if( pParse->db->mallocFailed ) return 0;
32180acb7e48Sdrh 
3219d5578433Smistachkin   /* Suppress the first OFFSET entries if there is an OFFSET clause
32200acb7e48Sdrh   */
3221aa9ce707Sdrh   codeOffset(v, p->iOffset, iContinue);
3222b21e7c70Sdrh 
3223e2248cfdSdrh   assert( pDest->eDest!=SRT_Exists );
3224e2248cfdSdrh   assert( pDest->eDest!=SRT_Table );
3225b21e7c70Sdrh   switch( pDest->eDest ){
3226b21e7c70Sdrh     /* Store the result as data using a unique key.
3227b21e7c70Sdrh     */
3228b21e7c70Sdrh     case SRT_EphemTab: {
3229b21e7c70Sdrh       int r1 = sqlite3GetTempReg(pParse);
3230b21e7c70Sdrh       int r2 = sqlite3GetTempReg(pParse);
32312b596da8Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
32322b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
32332b596da8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
3234b21e7c70Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
3235b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r2);
3236b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
3237b21e7c70Sdrh       break;
3238b21e7c70Sdrh     }
3239b21e7c70Sdrh 
3240b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY
32411431807aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)".
3242b21e7c70Sdrh     */
3243b21e7c70Sdrh     case SRT_Set: {
32446fccc35aSdrh       int r1;
324563cecc41Sdrh       testcase( pIn->nSdst>1 );
3246b21e7c70Sdrh       r1 = sqlite3GetTempReg(pParse);
324771c57db0Sdan       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
32481431807aSdrh           r1, pDest->zAffSdst, pIn->nSdst);
32499b4eaebcSdrh       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
32509b4eaebcSdrh                            pIn->iSdst, pIn->nSdst);
3251b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
3252b21e7c70Sdrh       break;
3253b21e7c70Sdrh     }
3254b21e7c70Sdrh 
3255b21e7c70Sdrh     /* If this is a scalar select that is part of an expression, then
3256b21e7c70Sdrh     ** store the results in the appropriate memory cell and break out
3257cb99c57aSdrh     ** of the scan loop.  Note that the select might return multiple columns
3258cb99c57aSdrh     ** if it is the RHS of a row-value IN operator.
3259b21e7c70Sdrh     */
3260b21e7c70Sdrh     case SRT_Mem: {
3261cb99c57aSdrh       testcase( pIn->nSdst>1 );
3262cb99c57aSdrh       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst);
3263b21e7c70Sdrh       /* The LIMIT clause will jump out of the loop for us */
3264b21e7c70Sdrh       break;
3265b21e7c70Sdrh     }
3266b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
3267b21e7c70Sdrh 
32687d10d5a6Sdrh     /* The results are stored in a sequence of registers
32692b596da8Sdrh     ** starting at pDest->iSdst.  Then the co-routine yields.
3270b21e7c70Sdrh     */
327192b01d53Sdrh     case SRT_Coroutine: {
32722b596da8Sdrh       if( pDest->iSdst==0 ){
32732b596da8Sdrh         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
32742b596da8Sdrh         pDest->nSdst = pIn->nSdst;
3275b21e7c70Sdrh       }
32764b79bde7Sdan       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
32772b596da8Sdrh       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
327892b01d53Sdrh       break;
327992b01d53Sdrh     }
328092b01d53Sdrh 
3281ccfcbceaSdrh     /* If none of the above, then the result destination must be
3282ccfcbceaSdrh     ** SRT_Output.  This routine is never called with any other
3283ccfcbceaSdrh     ** destination other than the ones handled above or SRT_Output.
3284ccfcbceaSdrh     **
3285ccfcbceaSdrh     ** For SRT_Output, results are stored in a sequence of registers.
3286ccfcbceaSdrh     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
3287ccfcbceaSdrh     ** return the next row of result.
32887d10d5a6Sdrh     */
3289ccfcbceaSdrh     default: {
3290ccfcbceaSdrh       assert( pDest->eDest==SRT_Output );
32912b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
3292b21e7c70Sdrh       break;
3293b21e7c70Sdrh     }
3294b21e7c70Sdrh   }
329592b01d53Sdrh 
329692b01d53Sdrh   /* Jump to the end of the loop if the LIMIT is reached.
329792b01d53Sdrh   */
329892b01d53Sdrh   if( p->iLimit ){
329916897072Sdrh     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
330092b01d53Sdrh   }
330192b01d53Sdrh 
330292b01d53Sdrh   /* Generate the subroutine return
330392b01d53Sdrh   */
33040acb7e48Sdrh   sqlite3VdbeResolveLabel(v, iContinue);
330592b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
330692b01d53Sdrh 
330792b01d53Sdrh   return addr;
3308b21e7c70Sdrh }
3309b21e7c70Sdrh 
3310b21e7c70Sdrh /*
3311b21e7c70Sdrh ** Alternative compound select code generator for cases when there
3312b21e7c70Sdrh ** is an ORDER BY clause.
3313b21e7c70Sdrh **
3314b21e7c70Sdrh ** We assume a query of the following form:
3315b21e7c70Sdrh **
3316b21e7c70Sdrh **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
3317b21e7c70Sdrh **
3318b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
3319b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as
3320b21e7c70Sdrh ** co-routines.  Then run the co-routines in parallel and merge the results
3321b21e7c70Sdrh ** into the output.  In addition to the two coroutines (called selectA and
3322b21e7c70Sdrh ** selectB) there are 7 subroutines:
3323b21e7c70Sdrh **
3324b21e7c70Sdrh **    outA:    Move the output of the selectA coroutine into the output
3325b21e7c70Sdrh **             of the compound query.
3326b21e7c70Sdrh **
3327b21e7c70Sdrh **    outB:    Move the output of the selectB coroutine into the output
3328b21e7c70Sdrh **             of the compound query.  (Only generated for UNION and
3329b21e7c70Sdrh **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
3330b21e7c70Sdrh **             appears only in B.)
3331b21e7c70Sdrh **
3332b21e7c70Sdrh **    AltB:    Called when there is data from both coroutines and A<B.
3333b21e7c70Sdrh **
3334b21e7c70Sdrh **    AeqB:    Called when there is data from both coroutines and A==B.
3335b21e7c70Sdrh **
3336b21e7c70Sdrh **    AgtB:    Called when there is data from both coroutines and A>B.
3337b21e7c70Sdrh **
3338b21e7c70Sdrh **    EofA:    Called when data is exhausted from selectA.
3339b21e7c70Sdrh **
3340b21e7c70Sdrh **    EofB:    Called when data is exhausted from selectB.
3341b21e7c70Sdrh **
3342b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which
3343b21e7c70Sdrh ** <operator> is used:
3344b21e7c70Sdrh **
3345b21e7c70Sdrh **
3346b21e7c70Sdrh **             UNION ALL         UNION            EXCEPT          INTERSECT
3347b21e7c70Sdrh **          -------------  -----------------  --------------  -----------------
3348b21e7c70Sdrh **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
3349b21e7c70Sdrh **
33500acb7e48Sdrh **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
3351b21e7c70Sdrh **
3352b21e7c70Sdrh **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
3353b21e7c70Sdrh **
33540acb7e48Sdrh **   EofA:   outB, nextB      outB, nextB          halt             halt
3355b21e7c70Sdrh **
33560acb7e48Sdrh **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
33570acb7e48Sdrh **
33580acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
33590acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes
33600acb7e48Sdrh ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
33610acb7e48Sdrh ** following nextX causes a jump to the end of the select processing.
33620acb7e48Sdrh **
33630acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
33640acb7e48Sdrh ** within the output subroutine.  The regPrev register set holds the previously
33650acb7e48Sdrh ** output value.  A comparison is made against this value and the output
33660acb7e48Sdrh ** is skipped if the next results would be the same as the previous.
3367b21e7c70Sdrh **
3368b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven
3369b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom.  Like this:
3370b21e7c70Sdrh **
3371b21e7c70Sdrh **          goto Init
3372b21e7c70Sdrh **     coA: coroutine for left query (A)
3373b21e7c70Sdrh **     coB: coroutine for right query (B)
3374b21e7c70Sdrh **    outA: output one row of A
3375b21e7c70Sdrh **    outB: output one row of B (UNION and UNION ALL only)
3376b21e7c70Sdrh **    EofA: ...
3377b21e7c70Sdrh **    EofB: ...
3378b21e7c70Sdrh **    AltB: ...
3379b21e7c70Sdrh **    AeqB: ...
3380b21e7c70Sdrh **    AgtB: ...
3381b21e7c70Sdrh **    Init: initialize coroutine registers
3382b21e7c70Sdrh **          yield coA
3383b21e7c70Sdrh **          if eof(A) goto EofA
3384b21e7c70Sdrh **          yield coB
3385b21e7c70Sdrh **          if eof(B) goto EofB
3386b21e7c70Sdrh **    Cmpr: Compare A, B
3387b21e7c70Sdrh **          Jump AltB, AeqB, AgtB
3388b21e7c70Sdrh **     End: ...
3389b21e7c70Sdrh **
3390b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
3391b21e7c70Sdrh ** actually called using Gosub and they do not Return.  EofA and EofB loop
3392b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
3393b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB.
3394b21e7c70Sdrh */
3395de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
multiSelectOrderBy(Parse * pParse,Select * p,SelectDest * pDest)3396b21e7c70Sdrh static int multiSelectOrderBy(
3397b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
3398b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
3399a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
3400b21e7c70Sdrh ){
34010acb7e48Sdrh   int i, j;             /* Loop counters */
3402b21e7c70Sdrh   Select *pPrior;       /* Another SELECT immediately to our left */
340338cebe07Sdrh   Select *pSplit;       /* Left-most SELECT in the right-hand group */
340438cebe07Sdrh   int nSelect;          /* Number of SELECT statements in the compound */
3405b21e7c70Sdrh   Vdbe *v;              /* Generate code to this VDBE */
3406b21e7c70Sdrh   SelectDest destA;     /* Destination for coroutine A */
3407b21e7c70Sdrh   SelectDest destB;     /* Destination for coroutine B */
340892b01d53Sdrh   int regAddrA;         /* Address register for select-A coroutine */
340992b01d53Sdrh   int regAddrB;         /* Address register for select-B coroutine */
341092b01d53Sdrh   int addrSelectA;      /* Address of the select-A coroutine */
341192b01d53Sdrh   int addrSelectB;      /* Address of the select-B coroutine */
341292b01d53Sdrh   int regOutA;          /* Address register for the output-A subroutine */
341392b01d53Sdrh   int regOutB;          /* Address register for the output-B subroutine */
341492b01d53Sdrh   int addrOutA;         /* Address of the output-A subroutine */
3415b27b7f5dSdrh   int addrOutB = 0;     /* Address of the output-B subroutine */
341692b01d53Sdrh   int addrEofA;         /* Address of the select-A-exhausted subroutine */
341781cf13ecSdrh   int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
341892b01d53Sdrh   int addrEofB;         /* Address of the select-B-exhausted subroutine */
341992b01d53Sdrh   int addrAltB;         /* Address of the A<B subroutine */
342092b01d53Sdrh   int addrAeqB;         /* Address of the A==B subroutine */
342192b01d53Sdrh   int addrAgtB;         /* Address of the A>B subroutine */
342292b01d53Sdrh   int regLimitA;        /* Limit register for select-A */
342392b01d53Sdrh   int regLimitB;        /* Limit register for select-A */
34240acb7e48Sdrh   int regPrev;          /* A range of registers to hold previous output */
342592b01d53Sdrh   int savedLimit;       /* Saved value of p->iLimit */
342692b01d53Sdrh   int savedOffset;      /* Saved value of p->iOffset */
342792b01d53Sdrh   int labelCmpr;        /* Label for the start of the merge algorithm */
342892b01d53Sdrh   int labelEnd;         /* Label for the end of the overall SELECT stmt */
3429728e0f91Sdrh   int addr1;            /* Jump instructions that get retargetted */
343092b01d53Sdrh   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
343196067816Sdrh   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
34320acb7e48Sdrh   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
34330acb7e48Sdrh   sqlite3 *db;          /* Database connection */
34340acb7e48Sdrh   ExprList *pOrderBy;   /* The ORDER BY clause */
34350acb7e48Sdrh   int nOrderBy;         /* Number of terms in the ORDER BY clause */
3436abc38158Sdrh   u32 *aPermute;        /* Mapping from ORDER BY terms to result set columns */
3437b21e7c70Sdrh 
343892b01d53Sdrh   assert( p->pOrderBy!=0 );
343996067816Sdrh   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
34400acb7e48Sdrh   db = pParse->db;
344192b01d53Sdrh   v = pParse->pVdbe;
3442ccfcbceaSdrh   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
3443ec4ccdbcSdrh   labelEnd = sqlite3VdbeMakeLabel(pParse);
3444ec4ccdbcSdrh   labelCmpr = sqlite3VdbeMakeLabel(pParse);
34450acb7e48Sdrh 
3446b21e7c70Sdrh 
344792b01d53Sdrh   /* Patch up the ORDER BY clause
344892b01d53Sdrh   */
344992b01d53Sdrh   op = p->op;
345038cebe07Sdrh   assert( p->pPrior->pOrderBy==0 );
34510acb7e48Sdrh   pOrderBy = p->pOrderBy;
345293a960a0Sdrh   assert( pOrderBy );
34530acb7e48Sdrh   nOrderBy = pOrderBy->nExpr;
345493a960a0Sdrh 
34550acb7e48Sdrh   /* For operators other than UNION ALL we have to make sure that
34560acb7e48Sdrh   ** the ORDER BY clause covers every term of the result set.  Add
34570acb7e48Sdrh   ** terms to the ORDER BY clause as necessary.
34580acb7e48Sdrh   */
34590acb7e48Sdrh   if( op!=TK_ALL ){
34600acb7e48Sdrh     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
34617d10d5a6Sdrh       struct ExprList_item *pItem;
34627d10d5a6Sdrh       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
34637d4c94bcSdrh         assert( pItem!=0 );
3464c2acc4e4Sdrh         assert( pItem->u.x.iOrderByCol>0 );
3465c2acc4e4Sdrh         if( pItem->u.x.iOrderByCol==i ) break;
34660acb7e48Sdrh       }
34670acb7e48Sdrh       if( j==nOrderBy ){
3468b7916a78Sdrh         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
3469fad3039cSmistachkin         if( pNew==0 ) return SQLITE_NOMEM_BKPT;
34700acb7e48Sdrh         pNew->flags |= EP_IntValue;
347133e619fcSdrh         pNew->u.iValue = i;
347243606175Sdrh         p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
3473c2acc4e4Sdrh         if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
34740acb7e48Sdrh       }
34750acb7e48Sdrh     }
34760acb7e48Sdrh   }
34770acb7e48Sdrh 
34780acb7e48Sdrh   /* Compute the comparison permutation and keyinfo that is used with
347910c081adSdrh   ** the permutation used to determine if the next
34800acb7e48Sdrh   ** row of results comes from selectA or selectB.  Also add explicit
34810acb7e48Sdrh   ** collations to the ORDER BY clause terms so that when the subqueries
34820acb7e48Sdrh   ** to the right and the left are evaluated, they use the correct
34830acb7e48Sdrh   ** collation.
34840acb7e48Sdrh   */
3485abc38158Sdrh   aPermute = sqlite3DbMallocRawNN(db, sizeof(u32)*(nOrderBy + 1));
34860acb7e48Sdrh   if( aPermute ){
34877d10d5a6Sdrh     struct ExprList_item *pItem;
3488b1702026Sdrh     aPermute[0] = nOrderBy;
3489b1702026Sdrh     for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
34907d4c94bcSdrh       assert( pItem!=0 );
34916736618aSdrh       assert( pItem->u.x.iOrderByCol>0 );
34922ec18a3cSdrh       assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
3493c2acc4e4Sdrh       aPermute[i] = pItem->u.x.iOrderByCol - 1;
34940acb7e48Sdrh     }
349553bed45eSdan     pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
34960acb7e48Sdrh   }else{
34970acb7e48Sdrh     pKeyMerge = 0;
34980acb7e48Sdrh   }
34990acb7e48Sdrh 
35000acb7e48Sdrh   /* Allocate a range of temporary registers and the KeyInfo needed
35010acb7e48Sdrh   ** for the logic that removes duplicate result rows when the
35020acb7e48Sdrh   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
35030acb7e48Sdrh   */
35040acb7e48Sdrh   if( op==TK_ALL ){
35050acb7e48Sdrh     regPrev = 0;
35060acb7e48Sdrh   }else{
35070acb7e48Sdrh     int nExpr = p->pEList->nExpr;
35081c0dc825Sdrh     assert( nOrderBy>=nExpr || db->mallocFailed );
3509c8ac0d16Sdrh     regPrev = pParse->nMem+1;
3510c8ac0d16Sdrh     pParse->nMem += nExpr+1;
35110acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
3512ad124329Sdrh     pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
35130acb7e48Sdrh     if( pKeyDup ){
35142ec2fb22Sdrh       assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
35150acb7e48Sdrh       for(i=0; i<nExpr; i++){
35160acb7e48Sdrh         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
35176e11892dSdan         pKeyDup->aSortFlags[i] = 0;
35180acb7e48Sdrh       }
35190acb7e48Sdrh     }
35200acb7e48Sdrh   }
352192b01d53Sdrh 
352292b01d53Sdrh   /* Separate the left and the right query from one another
352392b01d53Sdrh   */
352438cebe07Sdrh   nSelect = 1;
352538cebe07Sdrh   if( (op==TK_ALL || op==TK_UNION)
352638cebe07Sdrh    && OptimizationEnabled(db, SQLITE_BalancedMerge)
352738cebe07Sdrh   ){
352838cebe07Sdrh     for(pSplit=p; pSplit->pPrior!=0 && pSplit->op==op; pSplit=pSplit->pPrior){
352938cebe07Sdrh       nSelect++;
353038cebe07Sdrh       assert( pSplit->pPrior->pNext==pSplit );
353138cebe07Sdrh     }
353238cebe07Sdrh   }
353338cebe07Sdrh   if( nSelect<=3 ){
353438cebe07Sdrh     pSplit = p;
353538cebe07Sdrh   }else{
353638cebe07Sdrh     pSplit = p;
353738cebe07Sdrh     for(i=2; i<nSelect; i+=2){ pSplit = pSplit->pPrior; }
353838cebe07Sdrh   }
353938cebe07Sdrh   pPrior = pSplit->pPrior;
354098bb34c5Sdrh   assert( pPrior!=0 );
354138cebe07Sdrh   pSplit->pPrior = 0;
3542d227a291Sdrh   pPrior->pNext = 0;
354338cebe07Sdrh   assert( p->pOrderBy == pOrderBy );
354438cebe07Sdrh   assert( pOrderBy!=0 || db->mallocFailed );
354538cebe07Sdrh   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
35467d10d5a6Sdrh   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
35477d10d5a6Sdrh   sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
354892b01d53Sdrh 
354992b01d53Sdrh   /* Compute the limit registers */
355092b01d53Sdrh   computeLimitRegisters(pParse, p, labelEnd);
35510acb7e48Sdrh   if( p->iLimit && op==TK_ALL ){
355292b01d53Sdrh     regLimitA = ++pParse->nMem;
355392b01d53Sdrh     regLimitB = ++pParse->nMem;
355492b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
355592b01d53Sdrh                                   regLimitA);
355692b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
355792b01d53Sdrh   }else{
355892b01d53Sdrh     regLimitA = regLimitB = 0;
355992b01d53Sdrh   }
3560633e6d57Sdrh   sqlite3ExprDelete(db, p->pLimit);
35610acb7e48Sdrh   p->pLimit = 0;
356292b01d53Sdrh 
3563b21e7c70Sdrh   regAddrA = ++pParse->nMem;
3564b21e7c70Sdrh   regAddrB = ++pParse->nMem;
3565b21e7c70Sdrh   regOutA = ++pParse->nMem;
3566b21e7c70Sdrh   regOutB = ++pParse->nMem;
3567b21e7c70Sdrh   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
3568b21e7c70Sdrh   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
3569e2ca99c9Sdrh 
3570aae0f74eSdrh   ExplainQueryPlan((pParse, 1, "MERGE (%s)", sqlite3SelectOpName(p->op)));
3571b21e7c70Sdrh 
357292b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement to the
35730acb7e48Sdrh   ** left of the compound operator - the "A" select.
35740acb7e48Sdrh   */
3575ed71a839Sdrh   addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
3576728e0f91Sdrh   addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
3577ed71a839Sdrh   VdbeComment((v, "left SELECT"));
357892b01d53Sdrh   pPrior->iLimit = regLimitA;
3579c631ded5Sdrh   ExplainQueryPlan((pParse, 1, "LEFT"));
35807d10d5a6Sdrh   sqlite3Select(pParse, pPrior, &destA);
35812fade2f7Sdrh   sqlite3VdbeEndCoroutine(v, regAddrA);
3582728e0f91Sdrh   sqlite3VdbeJumpHere(v, addr1);
3583b21e7c70Sdrh 
358492b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement on
358592b01d53Sdrh   ** the right - the "B" select
358692b01d53Sdrh   */
3587ed71a839Sdrh   addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
3588728e0f91Sdrh   addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
3589ed71a839Sdrh   VdbeComment((v, "right SELECT"));
359092b01d53Sdrh   savedLimit = p->iLimit;
359192b01d53Sdrh   savedOffset = p->iOffset;
359292b01d53Sdrh   p->iLimit = regLimitB;
359392b01d53Sdrh   p->iOffset = 0;
3594c631ded5Sdrh   ExplainQueryPlan((pParse, 1, "RIGHT"));
35957d10d5a6Sdrh   sqlite3Select(pParse, p, &destB);
359692b01d53Sdrh   p->iLimit = savedLimit;
359792b01d53Sdrh   p->iOffset = savedOffset;
35982fade2f7Sdrh   sqlite3VdbeEndCoroutine(v, regAddrB);
3599b21e7c70Sdrh 
360092b01d53Sdrh   /* Generate a subroutine that outputs the current row of the A
36010acb7e48Sdrh   ** select as the next output row of the compound select.
360292b01d53Sdrh   */
3603b21e7c70Sdrh   VdbeNoopComment((v, "Output routine for A"));
36040acb7e48Sdrh   addrOutA = generateOutputSubroutine(pParse,
36050acb7e48Sdrh                  p, &destA, pDest, regOutA,
36062ec2fb22Sdrh                  regPrev, pKeyDup, labelEnd);
3607b21e7c70Sdrh 
360892b01d53Sdrh   /* Generate a subroutine that outputs the current row of the B
36090acb7e48Sdrh   ** select as the next output row of the compound select.
361092b01d53Sdrh   */
36110acb7e48Sdrh   if( op==TK_ALL || op==TK_UNION ){
3612b21e7c70Sdrh     VdbeNoopComment((v, "Output routine for B"));
36130acb7e48Sdrh     addrOutB = generateOutputSubroutine(pParse,
36140acb7e48Sdrh                  p, &destB, pDest, regOutB,
36152ec2fb22Sdrh                  regPrev, pKeyDup, labelEnd);
36160acb7e48Sdrh   }
36172ec2fb22Sdrh   sqlite3KeyInfoUnref(pKeyDup);
3618b21e7c70Sdrh 
361992b01d53Sdrh   /* Generate a subroutine to run when the results from select A
362092b01d53Sdrh   ** are exhausted and only data in select B remains.
362192b01d53Sdrh   */
362292b01d53Sdrh   if( op==TK_EXCEPT || op==TK_INTERSECT ){
362381cf13ecSdrh     addrEofA_noB = addrEofA = labelEnd;
362492b01d53Sdrh   }else{
362581cf13ecSdrh     VdbeNoopComment((v, "eof-A subroutine"));
362681cf13ecSdrh     addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
362781cf13ecSdrh     addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
3628688852abSdrh                                      VdbeCoverage(v);
3629076e85f5Sdrh     sqlite3VdbeGoto(v, addrEofA);
3630c3489bbfSdrh     p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
3631b21e7c70Sdrh   }
3632b21e7c70Sdrh 
363392b01d53Sdrh   /* Generate a subroutine to run when the results from select B
363492b01d53Sdrh   ** are exhausted and only data in select A remains.
363592b01d53Sdrh   */
3636b21e7c70Sdrh   if( op==TK_INTERSECT ){
363792b01d53Sdrh     addrEofB = addrEofA;
363895aa47b1Sdrh     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
3639b21e7c70Sdrh   }else{
364092b01d53Sdrh     VdbeNoopComment((v, "eof-B subroutine"));
364181cf13ecSdrh     addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
3642688852abSdrh     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
3643076e85f5Sdrh     sqlite3VdbeGoto(v, addrEofB);
3644b21e7c70Sdrh   }
3645b21e7c70Sdrh 
364692b01d53Sdrh   /* Generate code to handle the case of A<B
364792b01d53Sdrh   */
3648b21e7c70Sdrh   VdbeNoopComment((v, "A-lt-B subroutine"));
36490acb7e48Sdrh   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
3650688852abSdrh   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
3651076e85f5Sdrh   sqlite3VdbeGoto(v, labelCmpr);
3652b21e7c70Sdrh 
365392b01d53Sdrh   /* Generate code to handle the case of A==B
365492b01d53Sdrh   */
3655b21e7c70Sdrh   if( op==TK_ALL ){
3656b21e7c70Sdrh     addrAeqB = addrAltB;
36570acb7e48Sdrh   }else if( op==TK_INTERSECT ){
36580acb7e48Sdrh     addrAeqB = addrAltB;
36590acb7e48Sdrh     addrAltB++;
366092b01d53Sdrh   }else{
3661b21e7c70Sdrh     VdbeNoopComment((v, "A-eq-B subroutine"));
36620acb7e48Sdrh     addrAeqB =
3663688852abSdrh     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
3664076e85f5Sdrh     sqlite3VdbeGoto(v, labelCmpr);
366592b01d53Sdrh   }
3666b21e7c70Sdrh 
366792b01d53Sdrh   /* Generate code to handle the case of A>B
366892b01d53Sdrh   */
3669b21e7c70Sdrh   VdbeNoopComment((v, "A-gt-B subroutine"));
3670b21e7c70Sdrh   addrAgtB = sqlite3VdbeCurrentAddr(v);
3671b21e7c70Sdrh   if( op==TK_ALL || op==TK_UNION ){
3672b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
367392b01d53Sdrh   }
3674688852abSdrh   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
3675076e85f5Sdrh   sqlite3VdbeGoto(v, labelCmpr);
3676b21e7c70Sdrh 
367792b01d53Sdrh   /* This code runs once to initialize everything.
367892b01d53Sdrh   */
3679728e0f91Sdrh   sqlite3VdbeJumpHere(v, addr1);
3680688852abSdrh   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
3681688852abSdrh   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
368292b01d53Sdrh 
368392b01d53Sdrh   /* Implement the main merge loop
368492b01d53Sdrh   */
368592b01d53Sdrh   sqlite3VdbeResolveLabel(v, labelCmpr);
36860acb7e48Sdrh   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
36872b596da8Sdrh   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
36882ec2fb22Sdrh                          (char*)pKeyMerge, P4_KEYINFO);
3689953f7611Sdrh   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
3690688852abSdrh   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
369192b01d53Sdrh 
369292b01d53Sdrh   /* Jump to the this point in order to terminate the query.
369392b01d53Sdrh   */
3694b21e7c70Sdrh   sqlite3VdbeResolveLabel(v, labelEnd);
3695b21e7c70Sdrh 
3696*54422235Sdrh   /* Make arrangements to free the 2nd and subsequent arms of the compound
3697*54422235Sdrh   ** after the parse has finished */
369838cebe07Sdrh   if( pSplit->pPrior ){
369944132244Sdrh     sqlite3ParserAddCleanup(pParse,
370044132244Sdrh        (void(*)(sqlite3*,void*))sqlite3SelectDelete, pSplit->pPrior);
37015e7ad508Sdanielk1977   }
370238cebe07Sdrh   pSplit->pPrior = pPrior;
370338cebe07Sdrh   pPrior->pNext = pSplit;
3704cd0b2459Sdan   sqlite3ExprListDelete(db, pPrior->pOrderBy);
3705cd0b2459Sdan   pPrior->pOrderBy = 0;
3706cd0b2459Sdan 
370792b01d53Sdrh   /*** TBD:  Insert subroutine calls to close cursors on incomplete
370892b01d53Sdrh   **** subqueries ****/
3709e2ca99c9Sdrh   ExplainQueryPlanPop(pParse);
37103dc4cc66Sdrh   return pParse->nErr!=0;
371192b01d53Sdrh }
3712de3e41e3Sdanielk1977 #endif
3713b21e7c70Sdrh 
37143514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
371546967de2Sdrh 
371646967de2Sdrh /* An instance of the SubstContext object describes an substitution edit
371746967de2Sdrh ** to be performed on a parse tree.
371846967de2Sdrh **
371946967de2Sdrh ** All references to columns in table iTable are to be replaced by corresponding
372046967de2Sdrh ** expressions in pEList.
3721c133bab7Sdrh **
3722c133bab7Sdrh ** ## About "isOuterJoin":
3723c133bab7Sdrh **
3724c133bab7Sdrh ** The isOuterJoin column indicates that the replacement will occur into a
3725c133bab7Sdrh ** position in the parent that NULL-able due to an OUTER JOIN.  Either the
3726c133bab7Sdrh ** target slot in the parent is the right operand of a LEFT JOIN, or one of
3727c133bab7Sdrh ** the left operands of a RIGHT JOIN.  In either case, we need to potentially
3728c133bab7Sdrh ** bypass the substituted expression with OP_IfNullRow.
3729c133bab7Sdrh **
373040c9beccSdrh ** Suppose the original expression is an integer constant. Even though the table
3731c133bab7Sdrh ** has the nullRow flag set, because the expression is an integer constant,
3732c133bab7Sdrh ** it will not be NULLed out.  So instead, we insert an OP_IfNullRow opcode
3733c133bab7Sdrh ** that checks to see if the nullRow flag is set on the table.  If the nullRow
3734c133bab7Sdrh ** flag is set, then the value in the register is set to NULL and the original
3735c133bab7Sdrh ** expression is bypassed.  If the nullRow flag is not set, then the original
3736c133bab7Sdrh ** expression runs to populate the register.
3737c133bab7Sdrh **
3738c133bab7Sdrh ** Example where this is needed:
3739c133bab7Sdrh **
3740c133bab7Sdrh **      CREATE TABLE t1(a INTEGER PRIMARY KEY, b INT);
3741c133bab7Sdrh **      CREATE TABLE t2(x INT UNIQUE);
3742c133bab7Sdrh **
3743c133bab7Sdrh **      SELECT a,b,m,x FROM t1 LEFT JOIN (SELECT 59 AS m,x FROM t2) ON b=x;
3744c133bab7Sdrh **
3745c133bab7Sdrh ** When the subquery on the right side of the LEFT JOIN is flattened, we
3746c133bab7Sdrh ** have to add OP_IfNullRow in front of the OP_Integer that implements the
3747c133bab7Sdrh ** "m" value of the subquery so that a NULL will be loaded instead of 59
3748c133bab7Sdrh ** when processing a non-matched row of the left.
374946967de2Sdrh */
375046967de2Sdrh typedef struct SubstContext {
375146967de2Sdrh   Parse *pParse;            /* The parsing context */
375246967de2Sdrh   int iTable;               /* Replace references to this table */
375331d6fd55Sdrh   int iNewTable;            /* New table number */
3754c133bab7Sdrh   int isOuterJoin;          /* Add TK_IF_NULL_ROW opcodes on each replacement */
375546967de2Sdrh   ExprList *pEList;         /* Replacement expressions */
3756879164edSdan   ExprList *pCList;         /* Collation sequences for replacement expr */
375746967de2Sdrh } SubstContext;
375846967de2Sdrh 
375917435752Sdrh /* Forward Declarations */
376046967de2Sdrh static void substExprList(SubstContext*, ExprList*);
376146967de2Sdrh static void substSelect(SubstContext*, Select*, int);
376217435752Sdrh 
37632282792aSdrh /*
3764832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
37656a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
376684e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
37676a3ea0e6Sdrh ** unchanged.)
3768832508b7Sdrh **
3769832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
3770832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
3771832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
3772aca19e19Sdrh ** FORM clause entry is iTable.  This routine makes the necessary
3773832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
3774832508b7Sdrh ** of the subquery rather the result set of the subquery.
3775832508b7Sdrh */
substExpr(SubstContext * pSubst,Expr * pExpr)3776b7916a78Sdrh static Expr *substExpr(
377746967de2Sdrh   SubstContext *pSubst,  /* Description of the substitution */
377846967de2Sdrh   Expr *pExpr            /* Expr in which substitution occurs */
377917435752Sdrh ){
3780b7916a78Sdrh   if( pExpr==0 ) return 0;
378133b2cb9aSdrh   if( ExprHasProperty(pExpr, EP_OuterON|EP_InnerON)
3782d1985262Sdrh    && pExpr->w.iJoin==pSubst->iTable
37833d240d21Sdrh   ){
378433b2cb9aSdrh     testcase( ExprHasProperty(pExpr, EP_InnerON) );
3785d1985262Sdrh     pExpr->w.iJoin = pSubst->iNewTable;
3786399c7e21Sdrh   }
37872e52a9c6Sdrh   if( pExpr->op==TK_COLUMN
37882e52a9c6Sdrh    && pExpr->iTable==pSubst->iTable
37892e52a9c6Sdrh    && !ExprHasProperty(pExpr, EP_FixedCol)
37902e52a9c6Sdrh   ){
37916e5020e8Sdrh #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
379250350a15Sdrh     if( pExpr->iColumn<0 ){
379350350a15Sdrh       pExpr->op = TK_NULL;
37946e5020e8Sdrh     }else
37956e5020e8Sdrh #endif
37966e5020e8Sdrh     {
3797832508b7Sdrh       Expr *pNew;
3798879164edSdan       int iColumn = pExpr->iColumn;
3799879164edSdan       Expr *pCopy = pSubst->pEList->a[iColumn].pExpr;
380031d6fd55Sdrh       Expr ifNullRow;
3801879164edSdan       assert( pSubst->pEList!=0 && iColumn<pSubst->pEList->nExpr );
38021fd4e7bbSdrh       assert( pExpr->pRight==0 );
380344c5604cSdan       if( sqlite3ExprIsVector(pCopy) ){
380446967de2Sdrh         sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
380544c5604cSdan       }else{
380646967de2Sdrh         sqlite3 *db = pSubst->pParse->db;
3807c133bab7Sdrh         if( pSubst->isOuterJoin && pCopy->op!=TK_COLUMN ){
380831d6fd55Sdrh           memset(&ifNullRow, 0, sizeof(ifNullRow));
380931d6fd55Sdrh           ifNullRow.op = TK_IF_NULL_ROW;
381031d6fd55Sdrh           ifNullRow.pLeft = pCopy;
381131d6fd55Sdrh           ifNullRow.iTable = pSubst->iNewTable;
38124b1b65caSdrh           ifNullRow.iColumn = -99;
381346fe138dSdrh           ifNullRow.flags = EP_IfNullRow;
381431d6fd55Sdrh           pCopy = &ifNullRow;
381531d6fd55Sdrh         }
381611df7d28Sdrh         testcase( ExprHasProperty(pCopy, EP_Subquery) );
381744c5604cSdan         pNew = sqlite3ExprDup(db, pCopy, 0);
38188c6cb1bcSdrh         if( db->mallocFailed ){
38198c6cb1bcSdrh           sqlite3ExprDelete(db, pNew);
38208c6cb1bcSdrh           return pExpr;
38218c6cb1bcSdrh         }
3822c133bab7Sdrh         if( pSubst->isOuterJoin ){
3823bd11a2acSdan           ExprSetProperty(pNew, EP_CanBeNull);
3824bd11a2acSdan         }
382567a99dbeSdrh         if( ExprHasProperty(pExpr,EP_OuterON|EP_InnerON) ){
38263a6e4c59Sdrh           sqlite3SetJoinExpr(pNew, pExpr->w.iJoin,
382767a99dbeSdrh                              pExpr->flags & (EP_OuterON|EP_InnerON));
382892ddb3bdSdan         }
3829b7916a78Sdrh         sqlite3ExprDelete(db, pExpr);
3830b7916a78Sdrh         pExpr = pNew;
3831410fac35Sdan         if( pExpr->op==TK_TRUEFALSE ){
3832410fac35Sdan           pExpr->u.iValue = sqlite3ExprTruthValue(pExpr);
3833410fac35Sdan           pExpr->op = TK_INTEGER;
3834410fac35Sdan           ExprSetProperty(pExpr, EP_IntValue);
3835410fac35Sdan         }
3836e0866394Sdan 
3837fa508349Sdan         /* Ensure that the expression now has an implicit collation sequence,
3838fa508349Sdan         ** just as it did when it was a column of a view or sub-query. */
3839879164edSdan         {
3840879164edSdan           CollSeq *pNat = sqlite3ExprCollSeq(pSubst->pParse, pExpr);
3841879164edSdan           CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse,
3842879164edSdan                 pSubst->pCList->a[iColumn].pExpr
3843879164edSdan           );
3844879164edSdan           if( pNat!=pColl || (pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE) ){
3845e0866394Sdan             pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr,
3846e0866394Sdan                 (pColl ? pColl->zName : "BINARY")
3847e0866394Sdan             );
3848e0866394Sdan           }
3849879164edSdan         }
3850e0866394Sdan         ExprClearProperty(pExpr, EP_Collate);
3851e0866394Sdan       }
385250350a15Sdrh     }
3853832508b7Sdrh   }else{
38547c1544e0Sdrh     if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
38557c1544e0Sdrh       pExpr->iTable = pSubst->iNewTable;
38567c1544e0Sdrh     }
385746967de2Sdrh     pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
385846967de2Sdrh     pExpr->pRight = substExpr(pSubst, pExpr->pRight);
3859a4eeccdfSdrh     if( ExprUseXSelect(pExpr) ){
386046967de2Sdrh       substSelect(pSubst, pExpr->x.pSelect, 1);
38616ab3a2ecSdanielk1977     }else{
386246967de2Sdrh       substExprList(pSubst, pExpr->x.pList);
38636ab3a2ecSdanielk1977     }
38643703edf1Sdan #ifndef SQLITE_OMIT_WINDOWFUNC
38653703edf1Sdan     if( ExprHasProperty(pExpr, EP_WinFunc) ){
38663703edf1Sdan       Window *pWin = pExpr->y.pWin;
38673703edf1Sdan       pWin->pFilter = substExpr(pSubst, pWin->pFilter);
38683703edf1Sdan       substExprList(pSubst, pWin->pPartition);
38693703edf1Sdan       substExprList(pSubst, pWin->pOrderBy);
38703703edf1Sdan     }
38713703edf1Sdan #endif
3872832508b7Sdrh   }
3873b7916a78Sdrh   return pExpr;
3874832508b7Sdrh }
substExprList(SubstContext * pSubst,ExprList * pList)387517435752Sdrh static void substExprList(
387646967de2Sdrh   SubstContext *pSubst, /* Description of the substitution */
387746967de2Sdrh   ExprList *pList       /* List to scan and in which to make substitutes */
387817435752Sdrh ){
3879832508b7Sdrh   int i;
3880832508b7Sdrh   if( pList==0 ) return;
3881832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
388246967de2Sdrh     pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
3883832508b7Sdrh   }
3884832508b7Sdrh }
substSelect(SubstContext * pSubst,Select * p,int doPrior)388517435752Sdrh static void substSelect(
388646967de2Sdrh   SubstContext *pSubst, /* Description of the substitution */
388717435752Sdrh   Select *p,            /* SELECT statement in which to make substitutions */
3888d12b6363Sdrh   int doPrior           /* Do substitutes on p->pPrior too */
388917435752Sdrh ){
3890588a9a1aSdrh   SrcList *pSrc;
38917601294aSdrh   SrcItem *pItem;
3892588a9a1aSdrh   int i;
3893b3bce662Sdanielk1977   if( !p ) return;
3894d12b6363Sdrh   do{
389546967de2Sdrh     substExprList(pSubst, p->pEList);
389646967de2Sdrh     substExprList(pSubst, p->pGroupBy);
389746967de2Sdrh     substExprList(pSubst, p->pOrderBy);
389846967de2Sdrh     p->pHaving = substExpr(pSubst, p->pHaving);
389946967de2Sdrh     p->pWhere = substExpr(pSubst, p->pWhere);
3900588a9a1aSdrh     pSrc = p->pSrc;
39012906490bSdrh     assert( pSrc!=0 );
3902588a9a1aSdrh     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
390346967de2Sdrh       substSelect(pSubst, pItem->pSelect, 1);
3904d12b6363Sdrh       if( pItem->fg.isTabFunc ){
390546967de2Sdrh         substExprList(pSubst, pItem->u1.pFuncArg);
3906588a9a1aSdrh       }
3907588a9a1aSdrh     }
3908d12b6363Sdrh   }while( doPrior && (p = p->pPrior)!=0 );
3909b3bce662Sdanielk1977 }
39103514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
3911832508b7Sdrh 
39123514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3913832508b7Sdrh /*
39142aee514bSdrh ** pSelect is a SELECT statement and pSrcItem is one item in the FROM
39152aee514bSdrh ** clause of that SELECT.
39162aee514bSdrh **
39172aee514bSdrh ** This routine scans the entire SELECT statement and recomputes the
39182aee514bSdrh ** pSrcItem->colUsed mask.
39192aee514bSdrh */
recomputeColumnsUsedExpr(Walker * pWalker,Expr * pExpr)39202aee514bSdrh static int recomputeColumnsUsedExpr(Walker *pWalker, Expr *pExpr){
39217601294aSdrh   SrcItem *pItem;
39222aee514bSdrh   if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
39232aee514bSdrh   pItem = pWalker->u.pSrcItem;
39242aee514bSdrh   if( pItem->iCursor!=pExpr->iTable ) return WRC_Continue;
392574a07986Sdrh   if( pExpr->iColumn<0 ) return WRC_Continue;
392674a07986Sdrh   pItem->colUsed |= sqlite3ExprColUsed(pExpr);
39272aee514bSdrh   return WRC_Continue;
39282aee514bSdrh }
recomputeColumnsUsed(Select * pSelect,SrcItem * pSrcItem)39292aee514bSdrh static void recomputeColumnsUsed(
39302aee514bSdrh   Select *pSelect,                 /* The complete SELECT statement */
39317601294aSdrh   SrcItem *pSrcItem                /* Which FROM clause item to recompute */
39322aee514bSdrh ){
39332aee514bSdrh   Walker w;
39342aee514bSdrh   if( NEVER(pSrcItem->pTab==0) ) return;
39352aee514bSdrh   memset(&w, 0, sizeof(w));
39362aee514bSdrh   w.xExprCallback = recomputeColumnsUsedExpr;
39372aee514bSdrh   w.xSelectCallback = sqlite3SelectWalkNoop;
39382aee514bSdrh   w.u.pSrcItem = pSrcItem;
39392aee514bSdrh   pSrcItem->colUsed = 0;
39402aee514bSdrh   sqlite3WalkSelect(&w, pSelect);
39412aee514bSdrh }
39422aee514bSdrh #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
39432aee514bSdrh 
39442aee514bSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
39452aee514bSdrh /*
3946964fa26eSdan ** Assign new cursor numbers to each of the items in pSrc. For each
3947964fa26eSdan ** new cursor number assigned, set an entry in the aCsrMap[] array
3948964fa26eSdan ** to map the old cursor number to the new:
3949964fa26eSdan **
3950c8d21471Sdrh **     aCsrMap[iOld+1] = iNew;
3951964fa26eSdan **
3952964fa26eSdan ** The array is guaranteed by the caller to be large enough for all
3953c8d21471Sdrh ** existing cursor numbers in pSrc.  aCsrMap[0] is the array size.
3954964fa26eSdan **
3955964fa26eSdan ** If pSrc contains any sub-selects, call this routine recursively
3956964fa26eSdan ** on the FROM clause of each such sub-select, with iExcept set to -1.
3957964fa26eSdan */
srclistRenumberCursors(Parse * pParse,int * aCsrMap,SrcList * pSrc,int iExcept)3958964fa26eSdan static void srclistRenumberCursors(
3959964fa26eSdan   Parse *pParse,                  /* Parse context */
3960964fa26eSdan   int *aCsrMap,                   /* Array to store cursor mappings in */
3961964fa26eSdan   SrcList *pSrc,                  /* FROM clause to renumber */
3962964fa26eSdan   int iExcept                     /* FROM clause item to skip */
3963964fa26eSdan ){
3964964fa26eSdan   int i;
39657601294aSdrh   SrcItem *pItem;
3966964fa26eSdan   for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
3967964fa26eSdan     if( i!=iExcept ){
3968d131b51cSdan       Select *p;
3969c8d21471Sdrh       assert( pItem->iCursor < aCsrMap[0] );
3970c8d21471Sdrh       if( !pItem->fg.isRecursive || aCsrMap[pItem->iCursor+1]==0 ){
3971c8d21471Sdrh         aCsrMap[pItem->iCursor+1] = pParse->nTab++;
3972c7f5077eSdrh       }
3973c8d21471Sdrh       pItem->iCursor = aCsrMap[pItem->iCursor+1];
3974d131b51cSdan       for(p=pItem->pSelect; p; p=p->pPrior){
3975d131b51cSdan         srclistRenumberCursors(pParse, aCsrMap, p->pSrc, -1);
3976964fa26eSdan       }
3977964fa26eSdan     }
3978964fa26eSdan   }
3979964fa26eSdan }
3980964fa26eSdan 
3981964fa26eSdan /*
3982c8d21471Sdrh ** *piCursor is a cursor number.  Change it if it needs to be mapped.
3983c8d21471Sdrh */
renumberCursorDoMapping(Walker * pWalker,int * piCursor)3984c8d21471Sdrh static void renumberCursorDoMapping(Walker *pWalker, int *piCursor){
3985c8d21471Sdrh   int *aCsrMap = pWalker->u.aiCol;
3986c8d21471Sdrh   int iCsr = *piCursor;
3987c8d21471Sdrh   if( iCsr < aCsrMap[0] && aCsrMap[iCsr+1]>0 ){
3988c8d21471Sdrh     *piCursor = aCsrMap[iCsr+1];
3989c8d21471Sdrh   }
3990c8d21471Sdrh }
3991c8d21471Sdrh 
3992c8d21471Sdrh /*
3993964fa26eSdan ** Expression walker callback used by renumberCursors() to update
3994964fa26eSdan ** Expr objects to match newly assigned cursor numbers.
3995964fa26eSdan */
renumberCursorsCb(Walker * pWalker,Expr * pExpr)3996964fa26eSdan static int renumberCursorsCb(Walker *pWalker, Expr *pExpr){
3997e8f1490fSdan   int op = pExpr->op;
3998c8d21471Sdrh   if( op==TK_COLUMN || op==TK_IF_NULL_ROW ){
3999c8d21471Sdrh     renumberCursorDoMapping(pWalker, &pExpr->iTable);
4000964fa26eSdan   }
400167a99dbeSdrh   if( ExprHasProperty(pExpr, EP_OuterON) ){
4002d1985262Sdrh     renumberCursorDoMapping(pWalker, &pExpr->w.iJoin);
4003961a7260Sdan   }
4004964fa26eSdan   return WRC_Continue;
4005964fa26eSdan }
4006964fa26eSdan 
4007964fa26eSdan /*
4008964fa26eSdan ** Assign a new cursor number to each cursor in the FROM clause (Select.pSrc)
4009964fa26eSdan ** of the SELECT statement passed as the second argument, and to each
4010964fa26eSdan ** cursor in the FROM clause of any FROM clause sub-selects, recursively.
4011964fa26eSdan ** Except, do not assign a new cursor number to the iExcept'th element in
4012964fa26eSdan ** the FROM clause of (*p). Update all expressions and other references
4013964fa26eSdan ** to refer to the new cursor numbers.
4014964fa26eSdan **
4015964fa26eSdan ** Argument aCsrMap is an array that may be used for temporary working
4016964fa26eSdan ** space. Two guarantees are made by the caller:
4017964fa26eSdan **
4018964fa26eSdan **   * the array is larger than the largest cursor number used within the
4019964fa26eSdan **     select statement passed as an argument, and
4020964fa26eSdan **
4021964fa26eSdan **   * the array entries for all cursor numbers that do *not* appear in
4022964fa26eSdan **     FROM clauses of the select statement as described above are
4023964fa26eSdan **     initialized to zero.
4024964fa26eSdan */
renumberCursors(Parse * pParse,Select * p,int iExcept,int * aCsrMap)4025964fa26eSdan static void renumberCursors(
4026964fa26eSdan   Parse *pParse,                  /* Parse context */
4027964fa26eSdan   Select *p,                      /* Select to renumber cursors within */
4028964fa26eSdan   int iExcept,                    /* FROM clause item to skip */
4029964fa26eSdan   int *aCsrMap                    /* Working space */
4030964fa26eSdan ){
4031964fa26eSdan   Walker w;
4032964fa26eSdan   srclistRenumberCursors(pParse, aCsrMap, p->pSrc, iExcept);
4033964fa26eSdan   memset(&w, 0, sizeof(w));
4034964fa26eSdan   w.u.aiCol = aCsrMap;
4035964fa26eSdan   w.xExprCallback = renumberCursorsCb;
4036964fa26eSdan   w.xSelectCallback = sqlite3SelectWalkNoop;
4037964fa26eSdan   sqlite3WalkSelect(&w, p);
4038964fa26eSdan }
4039964fa26eSdan #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
4040964fa26eSdan 
4041879164edSdan /*
4042879164edSdan ** If pSel is not part of a compound SELECT, return a pointer to its
4043879164edSdan ** expression list. Otherwise, return a pointer to the expression list
4044879164edSdan ** of the leftmost SELECT in the compound.
4045879164edSdan */
findLeftmostExprlist(Select * pSel)4046879164edSdan static ExprList *findLeftmostExprlist(Select *pSel){
4047879164edSdan   while( pSel->pPrior ){
4048879164edSdan     pSel = pSel->pPrior;
4049879164edSdan   }
4050879164edSdan   return pSel->pEList;
4051879164edSdan }
4052879164edSdan 
4053964fa26eSdan #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4054964fa26eSdan /*
4055630d296cSdrh ** This routine attempts to flatten subqueries as a performance optimization.
4056630d296cSdrh ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
40571350b030Sdrh **
40581350b030Sdrh ** To understand the concept of flattening, consider the following
40591350b030Sdrh ** query:
40601350b030Sdrh **
40611350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
40621350b030Sdrh **
40631350b030Sdrh ** The default way of implementing this query is to execute the
40641350b030Sdrh ** subquery first and store the results in a temporary table, then
40651350b030Sdrh ** run the outer query on that temporary table.  This requires two
40661350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
40671350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
4068832508b7Sdrh ** optimized.
40691350b030Sdrh **
4070832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
40711350b030Sdrh ** a single flat select, like this:
40721350b030Sdrh **
40731350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
40741350b030Sdrh **
407560ec914cSpeter.d.reid ** The code generated for this simplification gives the same result
4076832508b7Sdrh ** but only has to scan the data once.  And because indices might
4077832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
4078832508b7Sdrh ** avoided.
40791350b030Sdrh **
4080d981e828Sdrh ** Flattening is subject to the following constraints:
40811350b030Sdrh **
408225c221ebSdrh **  (**)  We no longer attempt to flatten aggregate subqueries. Was:
408325c221ebSdrh **        The subquery and the outer query cannot both be aggregates.
40841350b030Sdrh **
408525c221ebSdrh **  (**)  We no longer attempt to flatten aggregate subqueries. Was:
4086d981e828Sdrh **        (2) If the subquery is an aggregate then
4087d981e828Sdrh **        (2a) the outer query must not be a join and
4088d981e828Sdrh **        (2b) the outer query must not use subqueries
4089d981e828Sdrh **             other than the one FROM-clause subquery that is a candidate
4090d981e828Sdrh **             for flattening.  (This is due to ticket [2f7170d73bf9abf80]
4091d981e828Sdrh **             from 2015-02-09.)
4092832508b7Sdrh **
4093d981e828Sdrh **   (3)  If the subquery is the right operand of a LEFT JOIN then
4094d981e828Sdrh **        (3a) the subquery may not be a join and
4095d981e828Sdrh **        (3b) the FROM clause of the subquery may not contain a virtual
4096d981e828Sdrh **             table and
4097ee373020Sdrh **        (**) Was: "The outer query may not have a GROUP BY." This case
4098ee373020Sdrh **             is now managed correctly
4099396afe6fSdrh **        (3d) the outer query may not be DISTINCT.
410041798d5bSdrh **        See also (26) for restrictions on RIGHT JOIN.
4101832508b7Sdrh **
4102d981e828Sdrh **   (4)  The subquery can not be DISTINCT.
4103832508b7Sdrh **
410449ad330dSdan **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
410549ad330dSdan **        sub-queries that were excluded from this optimization. Restriction
410649ad330dSdan **        (4) has since been expanded to exclude all DISTINCT subqueries.
4107832508b7Sdrh **
410825c221ebSdrh **  (**)  We no longer attempt to flatten aggregate subqueries.  Was:
410925c221ebSdrh **        If the subquery is aggregate, the outer query may not be DISTINCT.
4110832508b7Sdrh **
4111d981e828Sdrh **   (7)  The subquery must have a FROM clause.  TODO:  For subqueries without
411231d6fd55Sdrh **        A FROM clause, consider adding a FROM clause with the special
4113630d296cSdrh **        table sqlite_once that consists of a single row containing a
4114630d296cSdrh **        single NULL.
411508192d5fSdrh **
4116d981e828Sdrh **   (8)  If the subquery uses LIMIT then the outer query may not be a join.
4117df199a25Sdrh **
4118d981e828Sdrh **   (9)  If the subquery uses LIMIT then the outer query may not be aggregate.
4119df199a25Sdrh **
41206092d2bcSdrh **  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
41216092d2bcSdrh **        accidently carried the comment forward until 2014-09-15.  Original
4122d981e828Sdrh **        constraint: "If the subquery is aggregate then the outer query
4123d981e828Sdrh **        may not use LIMIT."
4124df199a25Sdrh **
4125d981e828Sdrh **  (11)  The subquery and the outer query may not both have ORDER BY clauses.
4126174b6195Sdrh **
41277b688edeSdrh **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
41282b300d5dSdrh **        a separate restriction deriving from ticket #350.
41293fc673e6Sdrh **
4130d981e828Sdrh **  (13)  The subquery and outer query may not both use LIMIT.
4131ac83963aSdrh **
4132d981e828Sdrh **  (14)  The subquery may not use OFFSET.
4133ac83963aSdrh **
4134d981e828Sdrh **  (15)  If the outer query is part of a compound select, then the
4135d981e828Sdrh **        subquery may not use LIMIT.
4136f3913278Sdrh **        (See ticket #2339 and ticket [02a8e81d44]).
4137ad91c6cdSdrh **
4138d981e828Sdrh **  (16)  If the outer query is aggregate, then the subquery may not
4139d981e828Sdrh **        use ORDER BY.  (Ticket #2942)  This used to not matter
4140c52e355dSdrh **        until we introduced the group_concat() function.
4141c52e355dSdrh **
4142d981e828Sdrh **  (17)  If the subquery is a compound select, then
4143d981e828Sdrh **        (17a) all compound operators must be a UNION ALL, and
4144d981e828Sdrh **        (17b) no terms within the subquery compound may be aggregate
4145e76acc65Sdrh **              or DISTINCT, and
4146d981e828Sdrh **        (17c) every term within the subquery compound must have a FROM clause
4147d981e828Sdrh **        (17d) the outer query may not be
4148d981e828Sdrh **              (17d1) aggregate, or
41498daf5ae2Sdan **              (17d2) DISTINCT
41508daf5ae2Sdan **        (17e) the subquery may not contain window functions, and
41518daf5ae2Sdan **        (17f) the subquery must not be the RHS of a LEFT JOIN.
4152b88bf865Sdrh **        (17g) either the subquery is the first element of the outer
4153b88bf865Sdrh **              query or there are no RIGHT or FULL JOINs in any arm
4154b88bf865Sdrh **              of the subquery.  (This is a duplicate of condition (27b).)
4155b6d91679Sdrh **        (17h) The corresponding result set expressions in all arms of the
4156b6d91679Sdrh **              compound must have the same affinity.
4157f23329a2Sdanielk1977 **
41584914cf92Sdanielk1977 **        The parent and sub-query may contain WHERE clauses. Subject to
41594914cf92Sdanielk1977 **        rules (11), (13) and (14), they may also contain ORDER BY,
4160630d296cSdrh **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
4161630d296cSdrh **        operator other than UNION ALL because all the other compound
4162630d296cSdrh **        operators have an implied DISTINCT which is disallowed by
4163630d296cSdrh **        restriction (4).
4164f23329a2Sdanielk1977 **
416567c70142Sdan **        Also, each component of the sub-query must return the same number
416667c70142Sdan **        of result columns. This is actually a requirement for any compound
416767c70142Sdan **        SELECT statement, but all the code here does is make sure that no
416867c70142Sdan **        such (illegal) sub-query is flattened. The caller will detect the
416967c70142Sdan **        syntax error and return a detailed message.
417067c70142Sdan **
417149fc1f60Sdanielk1977 **  (18)  If the sub-query is a compound select, then all terms of the
41729353beafSdan **        ORDER BY clause of the parent must be copies of a term returned
41739353beafSdan **        by the parent query.
417449fc1f60Sdanielk1977 **
4175d981e828Sdrh **  (19)  If the subquery uses LIMIT then the outer query may not
4176229cf702Sdrh **        have a WHERE clause.
4177229cf702Sdrh **
4178fca23557Sdrh **  (20)  If the sub-query is a compound select, then it must not use
4179fca23557Sdrh **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
4180fca23557Sdrh **        somewhat by saying that the terms of the ORDER BY clause must
4181fca23557Sdrh **        appear as unmodified result columns in the outer query.  But we
4182fca23557Sdrh **        have other optimizations in mind to deal with that case.
4183e8902a70Sdrh **
4184d981e828Sdrh **  (21)  If the subquery uses LIMIT then the outer query may not be
4185a91491e5Sshaneh **        DISTINCT.  (See ticket [752e1646fc]).
4186a91491e5Sshaneh **
4187d981e828Sdrh **  (22)  The subquery may not be a recursive CTE.
41888290c2adSdan **
41898daf5ae2Sdan **  (23)  If the outer query is a recursive CTE, then the sub-query may not be
41908daf5ae2Sdan **        a compound query.  This restriction is because transforming the
41918290c2adSdan **        parent to a compound query confuses the code that handles
41928290c2adSdan **        recursive queries in multiSelect().
41938290c2adSdan **
4194508e2d00Sdrh **  (**)  We no longer attempt to flatten aggregate subqueries.  Was:
4195508e2d00Sdrh **        The subquery may not be an aggregate that uses the built-in min() or
41969588ad95Sdrh **        or max() functions.  (Without this restriction, a query like:
41979588ad95Sdrh **        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
41989588ad95Sdrh **        return the value X for which Y was maximal.)
41999588ad95Sdrh **
42009a94722dSdan **  (25)  If either the subquery or the parent query contains a window
42019a94722dSdan **        function in the select list or ORDER BY clause, flattening
42029a94722dSdan **        is not attempted.
42039a94722dSdan **
420441798d5bSdrh **  (26)  The subquery may not be the right operand of a RIGHT JOIN.
420541798d5bSdrh **        See also (3) for restrictions on LEFT JOIN.
420641798d5bSdrh **
42071c2bf41aSdrh **  (27)  The subquery may not contain a FULL or RIGHT JOIN unless it
4208b22b4933Sdrh **        is the first element of the parent query.  Two subcases:
4209b22b4933Sdrh **        (27a) the subquery is not a compound query.
4210b88bf865Sdrh **        (27b) the subquery is a compound query and the RIGHT JOIN occurs
4211b88bf865Sdrh **              in any arm of the compound query.  (See also (17g).)
42121c2bf41aSdrh **
421367f70beaSdrh **  (28)  The subquery is not a MATERIALIZED CTE.
421467f70beaSdrh **
42158290c2adSdan **
4216832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
4217832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
421825c221ebSdrh ** uses aggregates.
4219832508b7Sdrh **
4220665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
4221832508b7Sdrh ** If flattening is attempted this routine returns 1.
4222832508b7Sdrh **
4223832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
4224832508b7Sdrh ** the subquery before this routine runs.
42251350b030Sdrh */
flattenSubquery(Parse * pParse,Select * p,int iFrom,int isAgg)42268c74a8caSdrh static int flattenSubquery(
4227524cc21eSdanielk1977   Parse *pParse,       /* Parsing context */
42288c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
42298c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
423025c221ebSdrh   int isAgg            /* True if outer SELECT uses aggregate functions */
42318c74a8caSdrh ){
4232524cc21eSdanielk1977   const char *zSavedAuthContext = pParse->zAuthContext;
4233d12b6363Sdrh   Select *pParent;    /* Current UNION ALL term of the other query */
42340bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
4235f23329a2Sdanielk1977   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
4236ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
4237ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
42386a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
4239399c7e21Sdrh   int iNewParent = -1;/* Replacement table for iParent */
4240c133bab7Sdrh   int isOuterJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
424191bb0eedSdrh   int i;              /* Loop counter */
424291bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
42437601294aSdrh   SrcItem *pSubitem;               /* The subquery */
4244524cc21eSdanielk1977   sqlite3 *db = pParse->db;
424589636628Sdrh   Walker w;                        /* Walker to persist agginfo data */
4246964fa26eSdan   int *aCsrMap = 0;
42471350b030Sdrh 
4248832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
4249832508b7Sdrh   */
4250a78c22c4Sdrh   assert( p!=0 );
4251d981e828Sdrh   assert( p->pPrior==0 );
42527e5418e4Sdrh   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
4253832508b7Sdrh   pSrc = p->pSrc;
4254ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
425591bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
425649fc1f60Sdanielk1977   iParent = pSubitem->iCursor;
425791bb0eedSdrh   pSub = pSubitem->pSelect;
4258832508b7Sdrh   assert( pSub!=0 );
4259885a5b03Sdrh 
426067a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
42619a94722dSdan   if( p->pWin || pSub->pWin ) return 0;                  /* Restriction (25) */
426267a9b8edSdan #endif
426386fb6e17Sdan 
4264832508b7Sdrh   pSubSrc = pSub->pSrc;
4265832508b7Sdrh   assert( pSubSrc );
4266ac83963aSdrh   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
426760ec914cSpeter.d.reid   ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
4268ac83963aSdrh   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
4269ac83963aSdrh   ** became arbitrary expressions, we were forced to add restrictions (13)
4270ac83963aSdrh   ** and (14). */
4271ac83963aSdrh   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
42728c0833fbSdrh   if( pSub->pLimit && pSub->pLimit->pRight ) return 0;   /* Restriction (14) */
4273d227a291Sdrh   if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
4274ad91c6cdSdrh     return 0;                                            /* Restriction (15) */
4275ad91c6cdSdrh   }
4276ac83963aSdrh   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
4277d981e828Sdrh   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (4)  */
427849ad330dSdan   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
427949ad330dSdan      return 0;         /* Restrictions (8)(9) */
4280df199a25Sdrh   }
42817d10d5a6Sdrh   if( p->pOrderBy && pSub->pOrderBy ){
4282ac83963aSdrh      return 0;                                           /* Restriction (11) */
4283ac83963aSdrh   }
4284c52e355dSdrh   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
4285229cf702Sdrh   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
4286a91491e5Sshaneh   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
4287a91491e5Sshaneh      return 0;         /* Restriction (21) */
4288a91491e5Sshaneh   }
4289508e2d00Sdrh   if( pSub->selFlags & (SF_Recursive) ){
4290508e2d00Sdrh     return 0; /* Restrictions (22) */
42919588ad95Sdrh   }
4292832508b7Sdrh 
4293399c7e21Sdrh   /*
4294399c7e21Sdrh   ** If the subquery is the right operand of a LEFT JOIN, then the
4295d981e828Sdrh   ** subquery may not be a join itself (3a). Example of why this is not
4296d981e828Sdrh   ** allowed:
42978af4d3acSdrh   **
42988af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
42998af4d3acSdrh   **
43008af4d3acSdrh   ** If we flatten the above, we would get
43018af4d3acSdrh   **
43028af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
43038af4d3acSdrh   **
43048af4d3acSdrh   ** which is not at all the same thing.
43052b300d5dSdrh   **
430631d6fd55Sdrh   ** See also tickets #306, #350, and #3300.
43073fc673e6Sdrh   */
4308c133bab7Sdrh   if( (pSubitem->fg.jointype & (JT_OUTER|JT_LTORJ))!=0 ){
4309396afe6fSdrh     if( pSubSrc->nSrc>1                        /* (3a) */
43109efc6186Sdrh      || IsVirtual(pSubSrc->a[0].pTab)          /* (3b) */
4311396afe6fSdrh      || (p->selFlags & SF_Distinct)!=0         /* (3d) */
431241798d5bSdrh      || (pSubitem->fg.jointype & JT_RIGHT)!=0  /* (26) */
4313396afe6fSdrh     ){
4314d981e828Sdrh       return 0;
4315399c7e21Sdrh     }
4316c133bab7Sdrh     isOuterJoin = 1;
43173fc673e6Sdrh   }
43183fc673e6Sdrh 
43191c2bf41aSdrh   assert( pSubSrc->nSrc>0 );  /* True by restriction (7) */
43201c2bf41aSdrh   if( iFrom>0 && (pSubSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
4321b88bf865Sdrh     return 0;   /* Restriction (27a) */
43221c2bf41aSdrh   }
432367f70beaSdrh   if( pSubitem->fg.isCte && pSubitem->u2.pCteUse->eM10d==M10d_Yes ){
432467f70beaSdrh     return 0;       /* (28) */
432567f70beaSdrh   }
43261c2bf41aSdrh 
4327d981e828Sdrh   /* Restriction (17): If the sub-query is a compound SELECT, then it must
4328f23329a2Sdanielk1977   ** use only the UNION ALL operator. And none of the simple select queries
4329f23329a2Sdanielk1977   ** that make up the compound SELECT are allowed to be aggregate or distinct
4330f23329a2Sdanielk1977   ** queries.
4331f23329a2Sdanielk1977   */
4332f23329a2Sdanielk1977   if( pSub->pPrior ){
4333b6d91679Sdrh     int ii;
4334fca23557Sdrh     if( pSub->pOrderBy ){
4335fca23557Sdrh       return 0;  /* Restriction (20) */
4336fca23557Sdrh     }
4337c133bab7Sdrh     if( isAgg || (p->selFlags & SF_Distinct)!=0 || isOuterJoin>0 ){
43388daf5ae2Sdan       return 0; /* (17d1), (17d2), or (17f) */
4339f23329a2Sdanielk1977     }
4340f23329a2Sdanielk1977     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
4341ccfcbceaSdrh       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
4342ccfcbceaSdrh       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
43434b3ac73cSdrh       assert( pSub->pSrc!=0 );
43448daf5ae2Sdan       assert( (pSub->selFlags & SF_Recursive)==0 );
43452ec18a3cSdrh       assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
4346d981e828Sdrh       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0    /* (17b) */
4347d981e828Sdrh        || (pSub1->pPrior && pSub1->op!=TK_ALL)                 /* (17a) */
4348d981e828Sdrh        || pSub1->pSrc->nSrc<1                                  /* (17c) */
4349ef9f719dSdrh #ifndef SQLITE_OMIT_WINDOWFUNC
43508d95ed78Sdrh        || pSub1->pWin                                          /* (17e) */
4351ef9f719dSdrh #endif
435280b3c548Sdanielk1977       ){
4353f23329a2Sdanielk1977         return 0;
4354f23329a2Sdanielk1977       }
4355b88bf865Sdrh       if( iFrom>0 && (pSub1->pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
4356b88bf865Sdrh         /* Without this restriction, the JT_LTORJ flag would end up being
4357b88bf865Sdrh         ** omitted on left-hand tables of the right join that is being
4358b88bf865Sdrh         ** flattened. */
4359b88bf865Sdrh         return 0;   /* Restrictions (17g), (27b) */
4360b88bf865Sdrh       }
43614b3ac73cSdrh       testcase( pSub1->pSrc->nSrc>1 );
4362f23329a2Sdanielk1977     }
436349fc1f60Sdanielk1977 
4364d981e828Sdrh     /* Restriction (18). */
436549fc1f60Sdanielk1977     if( p->pOrderBy ){
436649fc1f60Sdanielk1977       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
4367c2acc4e4Sdrh         if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
436849fc1f60Sdanielk1977       }
436949fc1f60Sdanielk1977     }
4370f23329a2Sdanielk1977 
4371de9ed629Sdan     /* Restriction (23) */
4372de9ed629Sdan     if( (p->selFlags & SF_Recursive) ) return 0;
4373964fa26eSdan 
4374b6d91679Sdrh     /* Restriction (17h) */
4375b6d91679Sdrh     for(ii=0; ii<pSub->pEList->nExpr; ii++){
4376b6d91679Sdrh       char aff;
4377b6d91679Sdrh       assert( pSub->pEList->a[ii].pExpr!=0 );
4378b6d91679Sdrh       aff = sqlite3ExprAffinity(pSub->pEList->a[ii].pExpr);
4379b6d91679Sdrh       for(pSub1=pSub->pPrior; pSub1; pSub1=pSub1->pPrior){
4380b6d91679Sdrh         assert( pSub1->pEList!=0 );
4381b6d91679Sdrh         assert( pSub1->pEList->nExpr>ii );
4382b6d91679Sdrh         assert( pSub1->pEList->a[ii].pExpr!=0 );
4383b6d91679Sdrh         if( sqlite3ExprAffinity(pSub1->pEList->a[ii].pExpr)!=aff ){
4384b6d91679Sdrh           return 0;
4385b6d91679Sdrh         }
4386b6d91679Sdrh       }
4387b6d91679Sdrh     }
4388b6d91679Sdrh 
4389964fa26eSdan     if( pSrc->nSrc>1 ){
439051ddfef7Sdan       if( pParse->nSelect>500 ) return 0;
439195fe38f2Sdrh       if( OptimizationDisabled(db, SQLITE_FlttnUnionAll) ) return 0;
4392913306a5Sdrh       aCsrMap = sqlite3DbMallocZero(db, ((i64)pParse->nTab+1)*sizeof(int));
4393c8d21471Sdrh       if( aCsrMap ) aCsrMap[0] = pParse->nTab;
4394964fa26eSdan     }
4395de9ed629Sdan   }
4396cdb2f607Sdrh 
43977d10d5a6Sdrh   /***** If we reach this point, flattening is permitted. *****/
4398fef37760Sdrh   SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n",
4399fef37760Sdrh                    pSub->selId, pSub, iFrom));
44007d10d5a6Sdrh 
44017d10d5a6Sdrh   /* Authorize the subquery */
4402524cc21eSdanielk1977   pParse->zAuthContext = pSubitem->zName;
4403a2acb0d7Sdrh   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
4404a2acb0d7Sdrh   testcase( i==SQLITE_DENY );
4405524cc21eSdanielk1977   pParse->zAuthContext = zSavedAuthContext;
4406524cc21eSdanielk1977 
4407de9ed629Sdan   /* Delete the transient structures associated with thesubquery */
4408de9ed629Sdan   pSub1 = pSubitem->pSelect;
4409de9ed629Sdan   sqlite3DbFree(db, pSubitem->zDatabase);
4410de9ed629Sdan   sqlite3DbFree(db, pSubitem->zName);
4411de9ed629Sdan   sqlite3DbFree(db, pSubitem->zAlias);
4412de9ed629Sdan   pSubitem->zDatabase = 0;
4413de9ed629Sdan   pSubitem->zName = 0;
4414de9ed629Sdan   pSubitem->zAlias = 0;
4415de9ed629Sdan   pSubitem->pSelect = 0;
4416d44f8b23Sdrh   assert( pSubitem->fg.isUsing!=0 || pSubitem->u3.pOn==0 );
4417de9ed629Sdan 
44187d10d5a6Sdrh   /* If the sub-query is a compound SELECT statement, then (by restrictions
44197d10d5a6Sdrh   ** 17 and 18 above) it must be a UNION ALL and the parent query must
44207d10d5a6Sdrh   ** be of the form:
4421f23329a2Sdanielk1977   **
4422f23329a2Sdanielk1977   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
4423f23329a2Sdanielk1977   **
4424f23329a2Sdanielk1977   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
4425a78c22c4Sdrh   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
4426f23329a2Sdanielk1977   ** OFFSET clauses and joins them to the left-hand-side of the original
4427f23329a2Sdanielk1977   ** using UNION ALL operators. In this case N is the number of simple
4428f23329a2Sdanielk1977   ** select statements in the compound sub-query.
4429a78c22c4Sdrh   **
4430a78c22c4Sdrh   ** Example:
4431a78c22c4Sdrh   **
4432a78c22c4Sdrh   **     SELECT a+1 FROM (
4433a78c22c4Sdrh   **        SELECT x FROM tab
4434a78c22c4Sdrh   **        UNION ALL
4435a78c22c4Sdrh   **        SELECT y FROM tab
4436a78c22c4Sdrh   **        UNION ALL
4437a78c22c4Sdrh   **        SELECT abs(z*2) FROM tab2
4438a78c22c4Sdrh   **     ) WHERE a!=5 ORDER BY 1
4439a78c22c4Sdrh   **
4440a78c22c4Sdrh   ** Transformed into:
4441a78c22c4Sdrh   **
4442a78c22c4Sdrh   **     SELECT x+1 FROM tab WHERE x+1!=5
4443a78c22c4Sdrh   **     UNION ALL
4444a78c22c4Sdrh   **     SELECT y+1 FROM tab WHERE y+1!=5
4445a78c22c4Sdrh   **     UNION ALL
4446a78c22c4Sdrh   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
4447a78c22c4Sdrh   **     ORDER BY 1
4448a78c22c4Sdrh   **
4449a78c22c4Sdrh   ** We call this the "compound-subquery flattening".
4450f23329a2Sdanielk1977   */
4451f23329a2Sdanielk1977   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
4452f23329a2Sdanielk1977     Select *pNew;
4453f23329a2Sdanielk1977     ExprList *pOrderBy = p->pOrderBy;
44544b86ef1dSdanielk1977     Expr *pLimit = p->pLimit;
4455f23329a2Sdanielk1977     Select *pPrior = p->pPrior;
4456de9ed629Sdan     Table *pItemTab = pSubitem->pTab;
4457de9ed629Sdan     pSubitem->pTab = 0;
4458f23329a2Sdanielk1977     p->pOrderBy = 0;
4459f23329a2Sdanielk1977     p->pPrior = 0;
44604b86ef1dSdanielk1977     p->pLimit = 0;
44616ab3a2ecSdanielk1977     pNew = sqlite3SelectDup(db, p, 0);
44624b86ef1dSdanielk1977     p->pLimit = pLimit;
4463a78c22c4Sdrh     p->pOrderBy = pOrderBy;
4464a78c22c4Sdrh     p->op = TK_ALL;
4465de9ed629Sdan     pSubitem->pTab = pItemTab;
4466a78c22c4Sdrh     if( pNew==0 ){
4467d227a291Sdrh       p->pPrior = pPrior;
4468a78c22c4Sdrh     }else{
446951ddfef7Sdan       pNew->selId = ++pParse->nSelect;
44709da977f1Sdrh       if( aCsrMap && ALWAYS(db->mallocFailed==0) ){
4471964fa26eSdan         renumberCursors(pParse, pNew, iFrom, aCsrMap);
4472964fa26eSdan       }
4473a78c22c4Sdrh       pNew->pPrior = pPrior;
4474d227a291Sdrh       if( pPrior ) pPrior->pNext = pNew;
4475d227a291Sdrh       pNew->pNext = p;
4476a78c22c4Sdrh       p->pPrior = pNew;
4477e2243d26Sdrh       SELECTTRACE(2,pParse,p,("compound-subquery flattener"
4478fef37760Sdrh                               " creates %u as peer\n",pNew->selId));
4479d227a291Sdrh     }
4480de9ed629Sdan     assert( pSubitem->pSelect==0 );
4481964fa26eSdan   }
4482964fa26eSdan   sqlite3DbFree(db, aCsrMap);
4483de9ed629Sdan   if( db->mallocFailed ){
4484de9ed629Sdan     pSubitem->pSelect = pSub1;
4485de9ed629Sdan     return 1;
4486a78c22c4Sdrh   }
4487a78c22c4Sdrh 
4488a78c22c4Sdrh   /* Defer deleting the Table object associated with the
4489a78c22c4Sdrh   ** subquery until code generation is
4490a78c22c4Sdrh   ** complete, since there may still exist Expr.pTab entries that
4491a78c22c4Sdrh   ** refer to the subquery even after flattening.  Ticket #3346.
4492ccfcbceaSdrh   **
4493ccfcbceaSdrh   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
4494a78c22c4Sdrh   */
4495ccfcbceaSdrh   if( ALWAYS(pSubitem->pTab!=0) ){
4496a78c22c4Sdrh     Table *pTabToDel = pSubitem->pTab;
449779df7782Sdrh     if( pTabToDel->nTabRef==1 ){
449865a7cd16Sdan       Parse *pToplevel = sqlite3ParseToplevel(pParse);
4499cf3c078fSdrh       sqlite3ParserAddCleanup(pToplevel,
4500cf3c078fSdrh          (void(*)(sqlite3*,void*))sqlite3DeleteTable,
4501cf3c078fSdrh          pTabToDel);
450221d4f5b5Sdrh       testcase( pToplevel->earlyCleanup );
4503a78c22c4Sdrh     }else{
450479df7782Sdrh       pTabToDel->nTabRef--;
4505a78c22c4Sdrh     }
4506a78c22c4Sdrh     pSubitem->pTab = 0;
4507a78c22c4Sdrh   }
4508a78c22c4Sdrh 
4509a78c22c4Sdrh   /* The following loop runs once for each term in a compound-subquery
4510a78c22c4Sdrh   ** flattening (as described above).  If we are doing a different kind
4511a78c22c4Sdrh   ** of flattening - a flattening other than a compound-subquery flattening -
4512a78c22c4Sdrh   ** then this loop only runs once.
4513a78c22c4Sdrh   **
4514a78c22c4Sdrh   ** This loop moves all of the FROM elements of the subquery into the
4515c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
4516c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
4517c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
4518c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
4519c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
4520c31c2eb8Sdrh   ** elements we are now copying in.
4521c31c2eb8Sdrh   */
4522de9ed629Sdan   pSub = pSub1;
4523a78c22c4Sdrh   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
4524a78c22c4Sdrh     int nSubSrc;
4525ea678832Sdrh     u8 jointype = 0;
452679d26586Sdrh     u8 ltorj = pSrc->a[iFrom].fg.jointype & JT_LTORJ;
452755f66b34Sdrh     assert( pSub!=0 );
4528a78c22c4Sdrh     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
4529a78c22c4Sdrh     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
4530a78c22c4Sdrh     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
4531588a9a1aSdrh 
4532de9ed629Sdan     if( pParent==p ){
4533de9ed629Sdan       jointype = pSubitem->fg.jointype;     /* First time through the loop */
4534c31c2eb8Sdrh     }
4535a78c22c4Sdrh 
4536a78c22c4Sdrh     /* The subquery uses a single slot of the FROM clause of the outer
4537a78c22c4Sdrh     ** query.  If the subquery has more than one element in its FROM clause,
4538a78c22c4Sdrh     ** then expand the outer query to make space for it to hold all elements
4539a78c22c4Sdrh     ** of the subquery.
4540a78c22c4Sdrh     **
4541a78c22c4Sdrh     ** Example:
4542a78c22c4Sdrh     **
4543a78c22c4Sdrh     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
4544a78c22c4Sdrh     **
4545a78c22c4Sdrh     ** The outer query has 3 slots in its FROM clause.  One slot of the
4546a78c22c4Sdrh     ** outer query (the middle slot) is used by the subquery.  The next
4547d12b6363Sdrh     ** block of code will expand the outer query FROM clause to 4 slots.
4548d12b6363Sdrh     ** The middle slot is expanded to two slots in order to make space
4549d12b6363Sdrh     ** for the two elements in the FROM clause of the subquery.
4550a78c22c4Sdrh     */
4551a78c22c4Sdrh     if( nSubSrc>1 ){
455229c992cbSdrh       pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
455329c992cbSdrh       if( pSrc==0 ) break;
455429c992cbSdrh       pParent->pSrc = pSrc;
4555c31c2eb8Sdrh     }
4556a78c22c4Sdrh 
4557a78c22c4Sdrh     /* Transfer the FROM clause terms from the subquery into the
4558a78c22c4Sdrh     ** outer query.
4559a78c22c4Sdrh     */
4560c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
4561d44f8b23Sdrh       SrcItem *pItem = &pSrc->a[i+iFrom];
4562d44f8b23Sdrh       if( pItem->fg.isUsing ) sqlite3IdListDelete(db, pItem->u3.pUsing);
4563d44f8b23Sdrh       assert( pItem->fg.isTabFunc==0 );
4564d44f8b23Sdrh       *pItem = pSubSrc->a[i];
456579d26586Sdrh       pItem->fg.jointype |= ltorj;
4566399c7e21Sdrh       iNewParent = pSubSrc->a[i].iCursor;
4567c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
4568c31c2eb8Sdrh     }
4569f7309bceSdrh     pSrc->a[iFrom].fg.jointype &= JT_LTORJ;
4570f7309bceSdrh     pSrc->a[iFrom].fg.jointype |= jointype | ltorj;
4571c31c2eb8Sdrh 
4572c31c2eb8Sdrh     /* Now begin substituting subquery result set expressions for
4573c31c2eb8Sdrh     ** references to the iParent in the outer query.
4574c31c2eb8Sdrh     **
4575c31c2eb8Sdrh     ** Example:
4576c31c2eb8Sdrh     **
4577c31c2eb8Sdrh     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
4578c31c2eb8Sdrh     **   \                     \_____________ subquery __________/          /
4579c31c2eb8Sdrh     **    \_____________________ outer query ______________________________/
4580c31c2eb8Sdrh     **
4581c31c2eb8Sdrh     ** We look at every expression in the outer query and every place we see
4582c31c2eb8Sdrh     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
4583c31c2eb8Sdrh     */
4584b7cbf5c1Sdrh     if( pSub->pOrderBy && (pParent->selFlags & SF_NoopOrderBy)==0 ){
45857c0a4720Sdan       /* At this point, any non-zero iOrderByCol values indicate that the
45867c0a4720Sdan       ** ORDER BY column expression is identical to the iOrderByCol'th
45877c0a4720Sdan       ** expression returned by SELECT statement pSub. Since these values
45887c0a4720Sdan       ** do not necessarily correspond to columns in SELECT statement pParent,
45897c0a4720Sdan       ** zero them before transfering the ORDER BY clause.
45907c0a4720Sdan       **
45917c0a4720Sdan       ** Not doing this may cause an error if a subsequent call to this
45927c0a4720Sdan       ** function attempts to flatten a compound sub-query into pParent
45937c0a4720Sdan       ** (the only way this can happen is if the compound sub-query is
45947c0a4720Sdan       ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
45957c0a4720Sdan       ExprList *pOrderBy = pSub->pOrderBy;
45967c0a4720Sdan       for(i=0; i<pOrderBy->nExpr; i++){
45977c0a4720Sdan         pOrderBy->a[i].u.x.iOrderByCol = 0;
45987c0a4720Sdan       }
4599f23329a2Sdanielk1977       assert( pParent->pOrderBy==0 );
46007c0a4720Sdan       pParent->pOrderBy = pOrderBy;
4601174b6195Sdrh       pSub->pOrderBy = 0;
4602174b6195Sdrh     }
460311df7d28Sdrh     pWhere = pSub->pWhere;
460411df7d28Sdrh     pSub->pWhere = 0;
4605c133bab7Sdrh     if( isOuterJoin>0 ){
460667a99dbeSdrh       sqlite3SetJoinExpr(pWhere, iNewParent, EP_OuterON);
4607399c7e21Sdrh     }
4608cd653a32Sdan     if( pWhere ){
4609cd653a32Sdan       if( pParent->pWhere ){
4610cd653a32Sdan         pParent->pWhere = sqlite3PExpr(pParse, TK_AND, pWhere, pParent->pWhere);
4611cd653a32Sdan       }else{
4612cd653a32Sdan         pParent->pWhere = pWhere;
4613cd653a32Sdan       }
4614cd653a32Sdan     }
4615c3becddbSdan     if( db->mallocFailed==0 ){
461646967de2Sdrh       SubstContext x;
461746967de2Sdrh       x.pParse = pParse;
461846967de2Sdrh       x.iTable = iParent;
4619399c7e21Sdrh       x.iNewTable = iNewParent;
4620c133bab7Sdrh       x.isOuterJoin = isOuterJoin;
462146967de2Sdrh       x.pEList = pSub->pEList;
4622879164edSdan       x.pCList = findLeftmostExprlist(pSub);
462346967de2Sdrh       substSelect(&x, pParent, 0);
4624c3becddbSdan     }
4625c31c2eb8Sdrh 
46267cd5e856Sdrh     /* The flattened query is a compound if either the inner or the
46277cd5e856Sdrh     ** outer query is a compound. */
46287cd5e856Sdrh     pParent->selFlags |= pSub->selFlags & SF_Compound;
46297cd5e856Sdrh     assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
46308c74a8caSdrh 
4631a58fdfb1Sdanielk1977     /*
4632a58fdfb1Sdanielk1977     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
4633ac83963aSdrh     **
4634ac83963aSdrh     ** One is tempted to try to add a and b to combine the limits.  But this
4635ac83963aSdrh     ** does not work if either limit is negative.
4636a58fdfb1Sdanielk1977     */
4637a2dc3b1aSdanielk1977     if( pSub->pLimit ){
4638f23329a2Sdanielk1977       pParent->pLimit = pSub->pLimit;
4639a2dc3b1aSdanielk1977       pSub->pLimit = 0;
4640df199a25Sdrh     }
46412aee514bSdrh 
46423b88065dSdrh     /* Recompute the SrcItem.colUsed masks for the flattened
46432aee514bSdrh     ** tables. */
46442aee514bSdrh     for(i=0; i<nSubSrc; i++){
46452aee514bSdrh       recomputeColumnsUsed(pParent, &pSrc->a[i+iFrom]);
46462aee514bSdrh     }
4647f23329a2Sdanielk1977   }
46488c74a8caSdrh 
4649c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
4650c31c2eb8Sdrh   ** success.
4651c31c2eb8Sdrh   */
465289636628Sdrh   sqlite3AggInfoPersistWalkerInit(&w, pParse);
465389636628Sdrh   sqlite3WalkSelect(&w,pSub1);
4654633e6d57Sdrh   sqlite3SelectDelete(db, pSub1);
4655f23329a2Sdanielk1977 
46565e431beaSdrh #if TREETRACE_ENABLED
46575e431beaSdrh   if( sqlite3TreeTrace & 0x100 ){
4658bc8edba1Sdrh     SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
4659c90713d3Sdrh     sqlite3TreeViewSelect(0, p, 0);
4660c90713d3Sdrh   }
4661c90713d3Sdrh #endif
4662c90713d3Sdrh 
4663832508b7Sdrh   return 1;
46641350b030Sdrh }
46653514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
46661350b030Sdrh 
4667660ee556Sdrh /*
46688e5bfeddSdrh ** A structure to keep track of all of the column values that are fixed to
4669efad2e23Sdrh ** a known value due to WHERE clause constraints of the form COLUMN=VALUE.
4670660ee556Sdrh */
4671660ee556Sdrh typedef struct WhereConst WhereConst;
4672660ee556Sdrh struct WhereConst {
4673efad2e23Sdrh   Parse *pParse;   /* Parsing context */
467475016050Sdrh   u8 *pOomFault;   /* Pointer to pParse->db->mallocFailed */
4675660ee556Sdrh   int nConst;      /* Number for COLUMN=CONSTANT terms */
4676660ee556Sdrh   int nChng;       /* Number of times a constant is propagated */
467740b82f9dSdan   int bHasAffBlob; /* At least one column in apExpr[] as affinity BLOB */
4678ae8776e0Sdrh   u32 mExcludeOn;  /* Which ON expressions to exclude from considertion.
4679ae8776e0Sdrh                    ** Either EP_OuterON or EP_InnerON|EP_OuterON */
4680efad2e23Sdrh   Expr **apExpr;   /* [i*2] is COLUMN and [i*2+1] is VALUE */
4681660ee556Sdrh };
468269b72d5aSdrh 
4683660ee556Sdrh /*
46848e5bfeddSdrh ** Add a new entry to the pConst object.  Except, do not add duplicate
4685f8f76d67Sdrh ** pColumn entires.  Also, do not add if doing so would not be appropriate.
4686f8f76d67Sdrh **
4687f8f76d67Sdrh ** The caller guarantees the pColumn is a column and pValue is a constant.
4688f8f76d67Sdrh ** This routine has to do some additional checks before completing the
4689f8f76d67Sdrh ** insert.
4690660ee556Sdrh */
constInsert(WhereConst * pConst,Expr * pColumn,Expr * pValue,Expr * pExpr)4691660ee556Sdrh static void constInsert(
46928e5bfeddSdrh   WhereConst *pConst,  /* The WhereConst into which we are inserting */
46938e5bfeddSdrh   Expr *pColumn,       /* The COLUMN part of the constraint */
4694f8f76d67Sdrh   Expr *pValue,        /* The VALUE part of the constraint */
4695f8f76d67Sdrh   Expr *pExpr          /* Overall expression: COLUMN=VALUE or VALUE=COLUMN */
4696660ee556Sdrh ){
46978e5bfeddSdrh   int i;
46988e5bfeddSdrh   assert( pColumn->op==TK_COLUMN );
4699f8f76d67Sdrh   assert( sqlite3ExprIsConstant(pValue) );
4700f8f76d67Sdrh 
4701fdfd45aeSdrh   if( ExprHasProperty(pColumn, EP_FixedCol) ) return;
4702fdfd45aeSdrh   if( sqlite3ExprAffinity(pValue)!=0 ) return;
4703f8f76d67Sdrh   if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){
4704f8f76d67Sdrh     return;
4705f8f76d67Sdrh   }
47068e5bfeddSdrh 
47078e5bfeddSdrh   /* 2018-10-25 ticket [cf5ed20f]
47088e5bfeddSdrh   ** Make sure the same pColumn is not inserted more than once */
47098e5bfeddSdrh   for(i=0; i<pConst->nConst; i++){
47107be5e3ddSdrh     const Expr *pE2 = pConst->apExpr[i*2];
47117be5e3ddSdrh     assert( pE2->op==TK_COLUMN );
47127be5e3ddSdrh     if( pE2->iTable==pColumn->iTable
47137be5e3ddSdrh      && pE2->iColumn==pColumn->iColumn
47148e5bfeddSdrh     ){
47158e5bfeddSdrh       return;  /* Already present.  Return without doing anything. */
47168e5bfeddSdrh     }
47178e5bfeddSdrh   }
471840b82f9dSdan   if( sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){
471940b82f9dSdan     pConst->bHasAffBlob = 1;
472040b82f9dSdan   }
47219cbf4f35Sdrh 
4722660ee556Sdrh   pConst->nConst++;
4723efad2e23Sdrh   pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
4724660ee556Sdrh                          pConst->nConst*2*sizeof(Expr*));
4725660ee556Sdrh   if( pConst->apExpr==0 ){
4726660ee556Sdrh     pConst->nConst = 0;
4727660ee556Sdrh   }else{
4728660ee556Sdrh     pConst->apExpr[pConst->nConst*2-2] = pColumn;
4729660ee556Sdrh     pConst->apExpr[pConst->nConst*2-1] = pValue;
4730660ee556Sdrh   }
4731660ee556Sdrh }
4732660ee556Sdrh 
4733660ee556Sdrh /*
4734efad2e23Sdrh ** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE
4735efad2e23Sdrh ** is a constant expression and where the term must be true because it
4736efad2e23Sdrh ** is part of the AND-connected terms of the expression.  For each term
4737efad2e23Sdrh ** found, add it to the pConst structure.
4738660ee556Sdrh */
findConstInWhere(WhereConst * pConst,Expr * pExpr)4739660ee556Sdrh static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
4740efad2e23Sdrh   Expr *pRight, *pLeft;
4741b775c976Sdrh   if( NEVER(pExpr==0) ) return;
4742ae8776e0Sdrh   if( ExprHasProperty(pExpr, pConst->mExcludeOn) ){
4743958fcd41Sdrh     testcase( ExprHasProperty(pExpr, EP_OuterON) );
4744958fcd41Sdrh     testcase( ExprHasProperty(pExpr, EP_InnerON) );
4745958fcd41Sdrh     return;
4746958fcd41Sdrh   }
4747660ee556Sdrh   if( pExpr->op==TK_AND ){
4748660ee556Sdrh     findConstInWhere(pConst, pExpr->pRight);
4749660ee556Sdrh     findConstInWhere(pConst, pExpr->pLeft);
4750660ee556Sdrh     return;
4751660ee556Sdrh   }
4752660ee556Sdrh   if( pExpr->op!=TK_EQ ) return;
4753efad2e23Sdrh   pRight = pExpr->pRight;
4754efad2e23Sdrh   pLeft = pExpr->pLeft;
4755efad2e23Sdrh   assert( pRight!=0 );
4756efad2e23Sdrh   assert( pLeft!=0 );
4757f8f76d67Sdrh   if( pRight->op==TK_COLUMN && sqlite3ExprIsConstant(pLeft) ){
4758f8f76d67Sdrh     constInsert(pConst,pRight,pLeft,pExpr);
4759f8f76d67Sdrh   }
4760f8f76d67Sdrh   if( pLeft->op==TK_COLUMN && sqlite3ExprIsConstant(pRight) ){
4761f8f76d67Sdrh     constInsert(pConst,pLeft,pRight,pExpr);
4762660ee556Sdrh   }
4763660ee556Sdrh }
4764660ee556Sdrh 
4765660ee556Sdrh /*
476640b82f9dSdan ** This is a helper function for Walker callback propagateConstantExprRewrite().
476740b82f9dSdan **
476840b82f9dSdan ** Argument pExpr is a candidate expression to be replaced by a value. If
476940b82f9dSdan ** pExpr is equivalent to one of the columns named in pWalker->u.pConst,
477040b82f9dSdan ** then overwrite it with the corresponding value. Except, do not do so
477140b82f9dSdan ** if argument bIgnoreAffBlob is non-zero and the affinity of pExpr
477240b82f9dSdan ** is SQLITE_AFF_BLOB.
4773660ee556Sdrh */
propagateConstantExprRewriteOne(WhereConst * pConst,Expr * pExpr,int bIgnoreAffBlob)477440b82f9dSdan static int propagateConstantExprRewriteOne(
477540b82f9dSdan   WhereConst *pConst,
477640b82f9dSdan   Expr *pExpr,
477740b82f9dSdan   int bIgnoreAffBlob
477840b82f9dSdan ){
4779660ee556Sdrh   int i;
478075016050Sdrh   if( pConst->pOomFault[0] ) return WRC_Prune;
4781660ee556Sdrh   if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
4782ae8776e0Sdrh   if( ExprHasProperty(pExpr, EP_FixedCol|pConst->mExcludeOn) ){
4783be0330e8Sdrh     testcase( ExprHasProperty(pExpr, EP_FixedCol) );
478467a99dbeSdrh     testcase( ExprHasProperty(pExpr, EP_OuterON) );
4785ae8776e0Sdrh     testcase( ExprHasProperty(pExpr, EP_InnerON) );
4786be0330e8Sdrh     return WRC_Continue;
4787be0330e8Sdrh   }
4788660ee556Sdrh   for(i=0; i<pConst->nConst; i++){
4789660ee556Sdrh     Expr *pColumn = pConst->apExpr[i*2];
4790660ee556Sdrh     if( pColumn==pExpr ) continue;
4791660ee556Sdrh     if( pColumn->iTable!=pExpr->iTable ) continue;
4792660ee556Sdrh     if( pColumn->iColumn!=pExpr->iColumn ) continue;
479340b82f9dSdan     if( bIgnoreAffBlob && sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){
479440b82f9dSdan       break;
479540b82f9dSdan     }
4796efad2e23Sdrh     /* A match is found.  Add the EP_FixedCol property */
4797660ee556Sdrh     pConst->nChng++;
4798660ee556Sdrh     ExprClearProperty(pExpr, EP_Leaf);
4799efad2e23Sdrh     ExprSetProperty(pExpr, EP_FixedCol);
4800efad2e23Sdrh     assert( pExpr->pLeft==0 );
4801efad2e23Sdrh     pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
480275016050Sdrh     if( pConst->pParse->db->mallocFailed ) return WRC_Prune;
4803660ee556Sdrh     break;
4804660ee556Sdrh   }
4805660ee556Sdrh   return WRC_Prune;
4806660ee556Sdrh }
4807660ee556Sdrh 
4808660ee556Sdrh /*
480940b82f9dSdan ** This is a Walker expression callback. pExpr is a node from the WHERE
481040b82f9dSdan ** clause of a SELECT statement. This function examines pExpr to see if
481140b82f9dSdan ** any substitutions based on the contents of pWalker->u.pConst should
481240b82f9dSdan ** be made to pExpr or its immediate children.
481340b82f9dSdan **
481440b82f9dSdan ** A substitution is made if:
481540b82f9dSdan **
481640b82f9dSdan **   + pExpr is a column with an affinity other than BLOB that matches
481740b82f9dSdan **     one of the columns in pWalker->u.pConst, or
481840b82f9dSdan **
481940b82f9dSdan **   + pExpr is a binary comparison operator (=, <=, >=, <, >) that
482040b82f9dSdan **     uses an affinity other than TEXT and one of its immediate
482140b82f9dSdan **     children is a column that matches one of the columns in
482240b82f9dSdan **     pWalker->u.pConst.
482340b82f9dSdan */
propagateConstantExprRewrite(Walker * pWalker,Expr * pExpr)482440b82f9dSdan static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
482540b82f9dSdan   WhereConst *pConst = pWalker->u.pConst;
4826a8ed5154Sdrh   assert( TK_GT==TK_EQ+1 );
4827a8ed5154Sdrh   assert( TK_LE==TK_EQ+2 );
4828a8ed5154Sdrh   assert( TK_LT==TK_EQ+3 );
4829a8ed5154Sdrh   assert( TK_GE==TK_EQ+4 );
483040b82f9dSdan   if( pConst->bHasAffBlob ){
4831a8ed5154Sdrh     if( (pExpr->op>=TK_EQ && pExpr->op<=TK_GE)
483240b82f9dSdan      || pExpr->op==TK_IS
483340b82f9dSdan     ){
483440b82f9dSdan       propagateConstantExprRewriteOne(pConst, pExpr->pLeft, 0);
483575016050Sdrh       if( pConst->pOomFault[0] ) return WRC_Prune;
483640b82f9dSdan       if( sqlite3ExprAffinity(pExpr->pLeft)!=SQLITE_AFF_TEXT ){
483740b82f9dSdan         propagateConstantExprRewriteOne(pConst, pExpr->pRight, 0);
483840b82f9dSdan       }
483940b82f9dSdan     }
484040b82f9dSdan   }
484140b82f9dSdan   return propagateConstantExprRewriteOne(pConst, pExpr, pConst->bHasAffBlob);
484240b82f9dSdan }
484340b82f9dSdan 
484440b82f9dSdan /*
4845660ee556Sdrh ** The WHERE-clause constant propagation optimization.
4846660ee556Sdrh **
4847660ee556Sdrh ** If the WHERE clause contains terms of the form COLUMN=CONSTANT or
484897bffe67Sdrh ** CONSTANT=COLUMN that are top-level AND-connected terms that are not
484997bffe67Sdrh ** part of a ON clause from a LEFT JOIN, then throughout the query
485097bffe67Sdrh ** replace all other occurrences of COLUMN with CONSTANT.
4851660ee556Sdrh **
4852660ee556Sdrh ** For example, the query:
4853660ee556Sdrh **
4854660ee556Sdrh **      SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b
4855660ee556Sdrh **
4856660ee556Sdrh ** Is transformed into
4857660ee556Sdrh **
4858660ee556Sdrh **      SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39
4859660ee556Sdrh **
4860660ee556Sdrh ** Return true if any transformations where made and false if not.
4861efad2e23Sdrh **
4862efad2e23Sdrh ** Implementation note:  Constant propagation is tricky due to affinity
4863efad2e23Sdrh ** and collating sequence interactions.  Consider this example:
4864efad2e23Sdrh **
4865efad2e23Sdrh **    CREATE TABLE t1(a INT,b TEXT);
4866efad2e23Sdrh **    INSERT INTO t1 VALUES(123,'0123');
4867efad2e23Sdrh **    SELECT * FROM t1 WHERE a=123 AND b=a;
4868efad2e23Sdrh **    SELECT * FROM t1 WHERE a=123 AND b=123;
4869efad2e23Sdrh **
4870efad2e23Sdrh ** The two SELECT statements above should return different answers.  b=a
4871efad2e23Sdrh ** is alway true because the comparison uses numeric affinity, but b=123
4872efad2e23Sdrh ** is false because it uses text affinity and '0123' is not the same as '123'.
4873efad2e23Sdrh ** To work around this, the expression tree is not actually changed from
4874efad2e23Sdrh ** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol
4875efad2e23Sdrh ** and the "123" value is hung off of the pLeft pointer.  Code generator
4876efad2e23Sdrh ** routines know to generate the constant "123" instead of looking up the
4877efad2e23Sdrh ** column value.  Also, to avoid collation problems, this optimization is
4878efad2e23Sdrh ** only attempted if the "a=123" term uses the default BINARY collation.
4879342cb33bSdrh **
4880342cb33bSdrh ** 2021-05-25 forum post 6a06202608: Another troublesome case is...
4881342cb33bSdrh **
4882342cb33bSdrh **    CREATE TABLE t1(x);
4883342cb33bSdrh **    INSERT INTO t1 VALUES(10.0);
4884342cb33bSdrh **    SELECT 1 FROM t1 WHERE x=10 AND x LIKE 10;
4885342cb33bSdrh **
4886342cb33bSdrh ** The query should return no rows, because the t1.x value is '10.0' not '10'
4887342cb33bSdrh ** and '10.0' is not LIKE '10'.  But if we are not careful, the first WHERE
4888342cb33bSdrh ** term "x=10" will cause the second WHERE term to become "10 LIKE 10",
4889342cb33bSdrh ** resulting in a false positive.  To avoid this, constant propagation for
4890342cb33bSdrh ** columns with BLOB affinity is only allowed if the constant is used with
4891342cb33bSdrh ** operators ==, <=, <, >=, >, or IS in a way that will cause the correct
4892342cb33bSdrh ** type conversions to occur.  See logic associated with the bHasAffBlob flag
4893342cb33bSdrh ** for details.
4894660ee556Sdrh */
propagateConstants(Parse * pParse,Select * p)4895660ee556Sdrh static int propagateConstants(
4896660ee556Sdrh   Parse *pParse,   /* The parsing context */
4897660ee556Sdrh   Select *p        /* The query in which to propagate constants */
4898660ee556Sdrh ){
4899660ee556Sdrh   WhereConst x;
4900660ee556Sdrh   Walker w;
4901660ee556Sdrh   int nChng = 0;
4902efad2e23Sdrh   x.pParse = pParse;
490375016050Sdrh   x.pOomFault = &pParse->db->mallocFailed;
4904660ee556Sdrh   do{
4905660ee556Sdrh     x.nConst = 0;
4906660ee556Sdrh     x.nChng = 0;
4907660ee556Sdrh     x.apExpr = 0;
490840b82f9dSdan     x.bHasAffBlob = 0;
4909ae8776e0Sdrh     if( ALWAYS(p->pSrc!=0)
4910ae8776e0Sdrh      && p->pSrc->nSrc>0
4911ae8776e0Sdrh      && (p->pSrc->a[0].fg.jointype & JT_LTORJ)!=0
4912ae8776e0Sdrh     ){
4913ae8776e0Sdrh       /* Do not propagate constants on any ON clause if there is a
4914ae8776e0Sdrh       ** RIGHT JOIN anywhere in the query */
4915ae8776e0Sdrh       x.mExcludeOn = EP_InnerON | EP_OuterON;
4916ae8776e0Sdrh     }else{
4917ae8776e0Sdrh       /* Do not propagate constants through the ON clause of a LEFT JOIN */
4918ae8776e0Sdrh       x.mExcludeOn = EP_OuterON;
4919ae8776e0Sdrh     }
4920660ee556Sdrh     findConstInWhere(&x, p->pWhere);
4921660ee556Sdrh     if( x.nConst ){
4922660ee556Sdrh       memset(&w, 0, sizeof(w));
4923660ee556Sdrh       w.pParse = pParse;
4924660ee556Sdrh       w.xExprCallback = propagateConstantExprRewrite;
4925660ee556Sdrh       w.xSelectCallback = sqlite3SelectWalkNoop;
4926660ee556Sdrh       w.xSelectCallback2 = 0;
4927660ee556Sdrh       w.walkerDepth = 0;
4928660ee556Sdrh       w.u.pConst = &x;
4929efad2e23Sdrh       sqlite3WalkExpr(&w, p->pWhere);
4930efad2e23Sdrh       sqlite3DbFree(x.pParse->db, x.apExpr);
4931660ee556Sdrh       nChng += x.nChng;
4932660ee556Sdrh     }
4933660ee556Sdrh   }while( x.nChng );
4934660ee556Sdrh   return nChng;
4935660ee556Sdrh }
493669b72d5aSdrh 
493769b72d5aSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4938903fdd48Sdan # if !defined(SQLITE_OMIT_WINDOWFUNC)
4939903fdd48Sdan /*
4940903fdd48Sdan ** This function is called to determine whether or not it is safe to
4941903fdd48Sdan ** push WHERE clause expression pExpr down to FROM clause sub-query
4942903fdd48Sdan ** pSubq, which contains at least one window function. Return 1
4943903fdd48Sdan ** if it is safe and the expression should be pushed down, or 0
4944903fdd48Sdan ** otherwise.
4945903fdd48Sdan **
4946903fdd48Sdan ** It is only safe to push the expression down if it consists only
4947903fdd48Sdan ** of constants and copies of expressions that appear in the PARTITION
4948903fdd48Sdan ** BY clause of all window function used by the sub-query. It is safe
4949903fdd48Sdan ** to filter out entire partitions, but not rows within partitions, as
4950903fdd48Sdan ** this may change the results of the window functions.
4951903fdd48Sdan **
4952903fdd48Sdan ** At the time this function is called it is guaranteed that
4953903fdd48Sdan **
4954903fdd48Sdan **   * the sub-query uses only one distinct window frame, and
4955903fdd48Sdan **   * that the window frame has a PARTITION BY clase.
4956903fdd48Sdan */
pushDownWindowCheck(Parse * pParse,Select * pSubq,Expr * pExpr)4957903fdd48Sdan static int pushDownWindowCheck(Parse *pParse, Select *pSubq, Expr *pExpr){
4958903fdd48Sdan   assert( pSubq->pWin->pPartition );
4959903fdd48Sdan   assert( (pSubq->selFlags & SF_MultiPart)==0 );
4960903fdd48Sdan   assert( pSubq->pPrior==0 );
4961903fdd48Sdan   return sqlite3ExprIsConstantOrGroupBy(pParse, pExpr, pSubq->pWin->pPartition);
4962903fdd48Sdan }
4963903fdd48Sdan # endif /* SQLITE_OMIT_WINDOWFUNC */
4964903fdd48Sdan #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
4965903fdd48Sdan 
4966903fdd48Sdan #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
496769b72d5aSdrh /*
496869b72d5aSdrh ** Make copies of relevant WHERE clause terms of the outer query into
496969b72d5aSdrh ** the WHERE clause of subquery.  Example:
497069b72d5aSdrh **
497169b72d5aSdrh **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
497269b72d5aSdrh **
497369b72d5aSdrh ** Transformed into:
497469b72d5aSdrh **
497569b72d5aSdrh **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
497669b72d5aSdrh **     WHERE x=5 AND y=10;
497769b72d5aSdrh **
497869b72d5aSdrh ** The hope is that the terms added to the inner query will make it more
497969b72d5aSdrh ** efficient.
498069b72d5aSdrh **
498169b72d5aSdrh ** Do not attempt this optimization if:
498269b72d5aSdrh **
498325c221ebSdrh **   (1) (** This restriction was removed on 2017-09-29.  We used to
498425c221ebSdrh **           disallow this optimization for aggregate subqueries, but now
498567cc51a4Sdrh **           it is allowed by putting the extra terms on the HAVING clause.
498667cc51a4Sdrh **           The added HAVING clause is pointless if the subquery lacks
498767cc51a4Sdrh **           a GROUP BY clause.  But such a HAVING clause is also harmless
498867cc51a4Sdrh **           so there does not appear to be any reason to add extra logic
498967cc51a4Sdrh **           to suppress it. **)
499069b72d5aSdrh **
499169b72d5aSdrh **   (2) The inner query is the recursive part of a common table expression.
499269b72d5aSdrh **
499369b72d5aSdrh **   (3) The inner query has a LIMIT clause (since the changes to the WHERE
4994ce103735Sdan **       clause would change the meaning of the LIMIT).
499569b72d5aSdrh **
49966a9b9527Sdrh **   (4) The inner query is the right operand of a LEFT JOIN and the
49976a9b9527Sdrh **       expression to be pushed down does not come from the ON clause
49986a9b9527Sdrh **       on that LEFT JOIN.
499969b72d5aSdrh **
500038978dd4Sdrh **   (5) The WHERE clause expression originates in the ON or USING clause
50017fbb101cSdrh **       of a LEFT JOIN where iCursor is not the right-hand table of that
50027fbb101cSdrh **       left join.  An example:
50037fbb101cSdrh **
50047fbb101cSdrh **           SELECT *
50057fbb101cSdrh **           FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
50067fbb101cSdrh **           JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
50077fbb101cSdrh **           LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
50087fbb101cSdrh **
50097fbb101cSdrh **       The correct answer is three rows:  (1,1,NULL),(2,2,8),(2,2,9).
50107fbb101cSdrh **       But if the (b2=2) term were to be pushed down into the bb subquery,
50117fbb101cSdrh **       then the (1,1,NULL) row would be suppressed.
501238978dd4Sdrh **
5013903fdd48Sdan **   (6) Window functions make things tricky as changes to the WHERE clause
5014903fdd48Sdan **       of the inner query could change the window over which window
5015903fdd48Sdan **       functions are calculated. Therefore, do not attempt the optimization
5016903fdd48Sdan **       if:
5017903fdd48Sdan **
5018903fdd48Sdan **     (6a) The inner query uses multiple incompatible window partitions.
5019903fdd48Sdan **
5020903fdd48Sdan **     (6b) The inner query is a compound and uses window-functions.
5021903fdd48Sdan **
5022903fdd48Sdan **     (6c) The WHERE clause does not consist entirely of constants and
5023903fdd48Sdan **          copies of expressions found in the PARTITION BY clause of
5024903fdd48Sdan **          all window-functions used by the sub-query. It is safe to
5025903fdd48Sdan **          filter out entire partitions, as this does not change the
5026903fdd48Sdan **          window over which any window-function is calculated.
5027ce103735Sdan **
5028745912efSdrh **   (7) The inner query is a Common Table Expression (CTE) that should
5029745912efSdrh **       be materialized.  (This restriction is implemented in the calling
5030745912efSdrh **       routine.)
5031745912efSdrh **
5032195687f1Sdan **   (8) The subquery may not be a compound that uses UNION, INTERSECT,
5033195687f1Sdan **       or EXCEPT.  (We could, perhaps, relax this restriction to allow
5034195687f1Sdan **       this case if none of the comparisons operators between left and
5035195687f1Sdan **       right arms of the compound use a collation other than BINARY.
5036195687f1Sdan **       But it is a lot of work to check that case for an obscure and
5037195687f1Sdan **       minor optimization, so we omit it for now.)
5038195687f1Sdan **
503969b72d5aSdrh ** Return 0 if no changes are made and non-zero if one or more WHERE clause
504069b72d5aSdrh ** terms are duplicated into the subquery.
504169b72d5aSdrh */
pushDownWhereTerms(Parse * pParse,Select * pSubq,Expr * pWhere,SrcItem * pSrc)504269b72d5aSdrh static int pushDownWhereTerms(
504344c5604cSdan   Parse *pParse,        /* Parse context (for malloc() and error reporting) */
504469b72d5aSdrh   Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
504569b72d5aSdrh   Expr *pWhere,         /* The WHERE clause of the outer query */
5046a9cdb904Sdrh   SrcItem *pSrc         /* The subquery term of the outer FROM clause */
504769b72d5aSdrh ){
504869b72d5aSdrh   Expr *pNew;
504969b72d5aSdrh   int nChng = 0;
505069b72d5aSdrh   if( pWhere==0 ) return 0;
5051903fdd48Sdan   if( pSubq->selFlags & (SF_Recursive|SF_MultiPart) ) return 0;
50520e464b5fSdrh   if( pSrc->fg.jointype & (JT_LTORJ|JT_RIGHT) ) return 0;
5053508e2d00Sdrh 
5054ce103735Sdan #ifndef SQLITE_OMIT_WINDOWFUNC
5055903fdd48Sdan   if( pSubq->pPrior ){
5056903fdd48Sdan     Select *pSel;
5057f65e3799Sdan     for(pSel=pSubq; pSel; pSel=pSel->pPrior){
5058195687f1Sdan       u8 op = pSel->op;
5059195687f1Sdan       assert( op==TK_ALL || op==TK_SELECT
5060195687f1Sdan            || op==TK_UNION || op==TK_INTERSECT || op==TK_EXCEPT );
5061195687f1Sdan       if( op!=TK_ALL && op!=TK_SELECT ) return 0;  /* restriction (8) */
5062903fdd48Sdan       if( pSel->pWin ) return 0;    /* restriction (6b) */
5063903fdd48Sdan     }
5064903fdd48Sdan   }else{
5065903fdd48Sdan     if( pSubq->pWin && pSubq->pWin->pPartition==0 ) return 0;
5066f65e3799Sdan   }
5067ce103735Sdan #endif
5068ce103735Sdan 
5069508e2d00Sdrh #ifdef SQLITE_DEBUG
5070508e2d00Sdrh   /* Only the first term of a compound can have a WITH clause.  But make
5071508e2d00Sdrh   ** sure no other terms are marked SF_Recursive in case something changes
5072508e2d00Sdrh   ** in the future.
5073508e2d00Sdrh   */
5074508e2d00Sdrh   {
5075508e2d00Sdrh     Select *pX;
5076b1ec87afSdrh     for(pX=pSubq; pX; pX=pX->pPrior){
5077508e2d00Sdrh       assert( (pX->selFlags & (SF_Recursive))==0 );
507869b72d5aSdrh     }
5079b1ec87afSdrh   }
5080508e2d00Sdrh #endif
5081508e2d00Sdrh 
508269b72d5aSdrh   if( pSubq->pLimit!=0 ){
508369b72d5aSdrh     return 0; /* restriction (3) */
508469b72d5aSdrh   }
508569b72d5aSdrh   while( pWhere->op==TK_AND ){
5086a9cdb904Sdrh     nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, pSrc);
508769b72d5aSdrh     pWhere = pWhere->pLeft;
508869b72d5aSdrh   }
5089a9cdb904Sdrh 
5090a9cdb904Sdrh #if 0  /* Legacy code. Checks now done by sqlite3ExprIsTableConstraint() */
50916a9b9527Sdrh   if( isLeftJoin
509267a99dbeSdrh    && (ExprHasProperty(pWhere,EP_OuterON)==0
5093d1985262Sdrh          || pWhere->w.iJoin!=iCursor)
50946a9b9527Sdrh   ){
50956a9b9527Sdrh     return 0; /* restriction (4) */
50966a9b9527Sdrh   }
509767a99dbeSdrh   if( ExprHasProperty(pWhere,EP_OuterON)
5098d1985262Sdrh    && pWhere->w.iJoin!=iCursor
5099796588aeSdrh   ){
51007fbb101cSdrh     return 0; /* restriction (5) */
51017fbb101cSdrh   }
5102a9cdb904Sdrh #endif
5103a9cdb904Sdrh 
51045eb6e097Sdrh   if( sqlite3ExprIsTableConstraint(pWhere, pSrc) ){
510569b72d5aSdrh     nChng++;
51068794c68aSdrh     pSubq->selFlags |= SF_PushDown;
510769b72d5aSdrh     while( pSubq ){
510846967de2Sdrh       SubstContext x;
510944c5604cSdan       pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
511092d1afbaSdrh       unsetJoinExpr(pNew, -1, 1);
511146967de2Sdrh       x.pParse = pParse;
5112a9cdb904Sdrh       x.iTable = pSrc->iCursor;
5113a9cdb904Sdrh       x.iNewTable = pSrc->iCursor;
5114c133bab7Sdrh       x.isOuterJoin = 0;
511546967de2Sdrh       x.pEList = pSubq->pEList;
5116879164edSdan       x.pCList = findLeftmostExprlist(pSubq);
511746967de2Sdrh       pNew = substExpr(&x, pNew);
5118903fdd48Sdan #ifndef SQLITE_OMIT_WINDOWFUNC
5119903fdd48Sdan       if( pSubq->pWin && 0==pushDownWindowCheck(pParse, pSubq, pNew) ){
5120903fdd48Sdan         /* Restriction 6c has prevented push-down in this case */
5121903fdd48Sdan         sqlite3ExprDelete(pParse->db, pNew);
5122903fdd48Sdan         nChng--;
5123903fdd48Sdan         break;
5124903fdd48Sdan       }
5125903fdd48Sdan #endif
512625c221ebSdrh       if( pSubq->selFlags & SF_Aggregate ){
5127d5c851c1Sdrh         pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew);
512825c221ebSdrh       }else{
5129d5c851c1Sdrh         pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew);
513025c221ebSdrh       }
513169b72d5aSdrh       pSubq = pSubq->pPrior;
513269b72d5aSdrh     }
513369b72d5aSdrh   }
513469b72d5aSdrh   return nChng;
513569b72d5aSdrh }
513669b72d5aSdrh #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
513769b72d5aSdrh 
51381350b030Sdrh /*
513947d9f839Sdrh ** The pFunc is the only aggregate function in the query.  Check to see
514047d9f839Sdrh ** if the query is a candidate for the min/max optimization.
5141a9d1ccb9Sdanielk1977 **
514247d9f839Sdrh ** If the query is a candidate for the min/max optimization, then set
514347d9f839Sdrh ** *ppMinMax to be an ORDER BY clause to be used for the optimization
514447d9f839Sdrh ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
514547d9f839Sdrh ** whether pFunc is a min() or max() function.
5146738bdcfbSdanielk1977 **
514747d9f839Sdrh ** If the query is not a candidate for the min/max optimization, return
514847d9f839Sdrh ** WHERE_ORDERBY_NORMAL (which must be zero).
51494ac391fcSdan **
515047d9f839Sdrh ** This routine must be called after aggregate functions have been
515147d9f839Sdrh ** located but before their arguments have been subjected to aggregate
515247d9f839Sdrh ** analysis.
5153a9d1ccb9Sdanielk1977 */
minMaxQuery(sqlite3 * db,Expr * pFunc,ExprList ** ppMinMax)515447d9f839Sdrh static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
51554ac391fcSdan   int eRet = WHERE_ORDERBY_NORMAL;      /* Return value */
5156a4eeccdfSdrh   ExprList *pEList;                     /* Arguments to agg function */
515747d9f839Sdrh   const char *zFunc;                    /* Name of aggregate function pFunc */
515847d9f839Sdrh   ExprList *pOrderBy;
5159be284e4eSdrh   u8 sortFlags = 0;
5160a9d1ccb9Sdanielk1977 
516147d9f839Sdrh   assert( *ppMinMax==0 );
516247d9f839Sdrh   assert( pFunc->op==TK_AGG_FUNCTION );
51634f9adee2Sdan   assert( !IsWindowFunc(pFunc) );
5164a4eeccdfSdrh   assert( ExprUseXList(pFunc) );
5165a4eeccdfSdrh   pEList = pFunc->x.pList;
5166af7b7653Sdrh   if( pEList==0
5167af7b7653Sdrh    || pEList->nExpr!=1
5168af7b7653Sdrh    || ExprHasProperty(pFunc, EP_WinFunc)
5169af7b7653Sdrh    || OptimizationDisabled(db, SQLITE_MinMaxOpt)
5170af7b7653Sdrh   ){
51716ba7ab0dSdan     return eRet;
51726ba7ab0dSdan   }
5173f9751074Sdrh   assert( !ExprHasProperty(pFunc, EP_IntValue) );
517447d9f839Sdrh   zFunc = pFunc->u.zToken;
51754ac391fcSdan   if( sqlite3StrICmp(zFunc, "min")==0 ){
51764ac391fcSdan     eRet = WHERE_ORDERBY_MIN;
517767e2bb92Sdan     if( sqlite3ExprCanBeNull(pEList->a[0].pExpr) ){
51785b32bdffSdan       sortFlags = KEYINFO_ORDER_BIGNULL;
517967e2bb92Sdan     }
51804ac391fcSdan   }else if( sqlite3StrICmp(zFunc, "max")==0 ){
51814ac391fcSdan     eRet = WHERE_ORDERBY_MAX;
51825b32bdffSdan     sortFlags = KEYINFO_ORDER_DESC;
518347d9f839Sdrh   }else{
518447d9f839Sdrh     return eRet;
5185a9d1ccb9Sdanielk1977   }
518647d9f839Sdrh   *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
518747d9f839Sdrh   assert( pOrderBy!=0 || db->mallocFailed );
5188d88fd539Sdrh   if( pOrderBy ) pOrderBy->a[0].fg.sortFlags = sortFlags;
51894ac391fcSdan   return eRet;
5190a9d1ccb9Sdanielk1977 }
5191a9d1ccb9Sdanielk1977 
5192a9d1ccb9Sdanielk1977 /*
5193a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query.
519460ec914cSpeter.d.reid ** The second argument is the associated aggregate-info object. This
5195a5533162Sdanielk1977 ** function tests if the SELECT is of the form:
5196a5533162Sdanielk1977 **
5197a5533162Sdanielk1977 **   SELECT count(*) FROM <tbl>
5198a5533162Sdanielk1977 **
5199a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query
5200a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing
5201a1c4c3c1Sdrh ** <tbl> is returned. Otherwise, NULL is returned.
5202a1c4c3c1Sdrh **
5203e574a923Sdrh ** This routine checks to see if it is safe to use the count optimization.
5204e574a923Sdrh ** A correct answer is still obtained (though perhaps more slowly) if
5205e574a923Sdrh ** this routine returns NULL when it could have returned a table pointer.
5206e574a923Sdrh ** But returning the pointer when NULL should have been returned can
5207e574a923Sdrh ** result in incorrect answers and/or crashes.  So, when in doubt, return NULL.
5208a5533162Sdanielk1977 */
isSimpleCount(Select * p,AggInfo * pAggInfo)5209a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
5210a5533162Sdanielk1977   Table *pTab;
5211a5533162Sdanielk1977   Expr *pExpr;
5212a5533162Sdanielk1977 
5213a5533162Sdanielk1977   assert( !p->pGroupBy );
5214a5533162Sdanielk1977 
5215a1c4c3c1Sdrh   if( p->pWhere
5216a1c4c3c1Sdrh    || p->pEList->nExpr!=1
5217a1c4c3c1Sdrh    || p->pSrc->nSrc!=1
5218a1c4c3c1Sdrh    || p->pSrc->a[0].pSelect
5219a1c4c3c1Sdrh    || pAggInfo->nFunc!=1
52202c1b1ddcSdan    || p->pHaving
5221a5533162Sdanielk1977   ){
5222a5533162Sdanielk1977     return 0;
5223a5533162Sdanielk1977   }
5224a5533162Sdanielk1977   pTab = p->pSrc->a[0].pTab;
5225a1c4c3c1Sdrh   assert( pTab!=0 );
5226a1c4c3c1Sdrh   assert( !IsView(pTab) );
5227a1c4c3c1Sdrh   if( !IsOrdinaryTable(pTab) ) return 0;
5228a5533162Sdanielk1977   pExpr = p->pEList->a[0].pExpr;
5229a1c4c3c1Sdrh   assert( pExpr!=0 );
5230a5533162Sdanielk1977   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
52318745f8a3Sdan   if( pExpr->pAggInfo!=pAggInfo ) return 0;
5232d36e1041Sdrh   if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
5233a1c4c3c1Sdrh   assert( pAggInfo->aFunc[0].pFExpr==pExpr );
5234a1c4c3c1Sdrh   testcase( ExprHasProperty(pExpr, EP_Distinct) );
5235a1c4c3c1Sdrh   testcase( ExprHasProperty(pExpr, EP_WinFunc) );
52364f9adee2Sdan   if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0;
5237a5533162Sdanielk1977 
5238a5533162Sdanielk1977   return pTab;
5239a5533162Sdanielk1977 }
5240a5533162Sdanielk1977 
5241a5533162Sdanielk1977 /*
5242b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an
5243b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there
5244b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return
5245b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
5246b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK.
5247b1c685b0Sdanielk1977 */
sqlite3IndexedByLookup(Parse * pParse,SrcItem * pFrom)52487601294aSdrh int sqlite3IndexedByLookup(Parse *pParse, SrcItem *pFrom){
5249b1c685b0Sdanielk1977   Table *pTab = pFrom->pTab;
52508a48b9c0Sdrh   char *zIndexedBy = pFrom->u1.zIndexedBy;
5251b1c685b0Sdanielk1977   Index *pIdx;
52521862271fSdrh   assert( pTab!=0 );
52531862271fSdrh   assert( pFrom->fg.isIndexedBy!=0 );
52541862271fSdrh 
5255b1c685b0Sdanielk1977   for(pIdx=pTab->pIndex;
5256d62fbb50Sdrh       pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
5257b1c685b0Sdanielk1977       pIdx=pIdx->pNext
5258b1c685b0Sdanielk1977   );
5259b1c685b0Sdanielk1977   if( !pIdx ){
5260d62fbb50Sdrh     sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
52611db95106Sdan     pParse->checkSchema = 1;
5262b1c685b0Sdanielk1977     return SQLITE_ERROR;
5263b1c685b0Sdanielk1977   }
5264dbfbb5a0Sdrh   assert( pFrom->fg.isCte==0 );
5265a79e2a2dSdrh   pFrom->u2.pIBIndex = pIdx;
5266b1c685b0Sdanielk1977   return SQLITE_OK;
5267b1c685b0Sdanielk1977 }
52681862271fSdrh 
5269c01b7306Sdrh /*
5270c01b7306Sdrh ** Detect compound SELECT statements that use an ORDER BY clause with
5271c01b7306Sdrh ** an alternative collating sequence.
5272c01b7306Sdrh **
5273c01b7306Sdrh **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
5274c01b7306Sdrh **
5275c01b7306Sdrh ** These are rewritten as a subquery:
5276c01b7306Sdrh **
5277c01b7306Sdrh **    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
5278c01b7306Sdrh **     ORDER BY ... COLLATE ...
5279c01b7306Sdrh **
5280c01b7306Sdrh ** This transformation is necessary because the multiSelectOrderBy() routine
5281c01b7306Sdrh ** above that generates the code for a compound SELECT with an ORDER BY clause
5282c01b7306Sdrh ** uses a merge algorithm that requires the same collating sequence on the
5283c01b7306Sdrh ** result columns as on the ORDER BY clause.  See ticket
5284c01b7306Sdrh ** http://www.sqlite.org/src/info/6709574d2a
5285c01b7306Sdrh **
5286c01b7306Sdrh ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
5287c01b7306Sdrh ** The UNION ALL operator works fine with multiSelectOrderBy() even when
5288c01b7306Sdrh ** there are COLLATE terms in the ORDER BY.
5289c01b7306Sdrh */
convertCompoundSelectToSubquery(Walker * pWalker,Select * p)5290c01b7306Sdrh static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
5291c01b7306Sdrh   int i;
5292c01b7306Sdrh   Select *pNew;
5293c01b7306Sdrh   Select *pX;
5294c01b7306Sdrh   sqlite3 *db;
5295c01b7306Sdrh   struct ExprList_item *a;
5296c01b7306Sdrh   SrcList *pNewSrc;
5297c01b7306Sdrh   Parse *pParse;
5298c01b7306Sdrh   Token dummy;
5299c01b7306Sdrh 
5300c01b7306Sdrh   if( p->pPrior==0 ) return WRC_Continue;
5301c01b7306Sdrh   if( p->pOrderBy==0 ) return WRC_Continue;
5302c01b7306Sdrh   for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
5303c01b7306Sdrh   if( pX==0 ) return WRC_Continue;
5304c01b7306Sdrh   a = p->pOrderBy->a;
530546daa99bSdan #ifndef SQLITE_OMIT_WINDOWFUNC
530646daa99bSdan   /* If iOrderByCol is already non-zero, then it has already been matched
530746daa99bSdan   ** to a result column of the SELECT statement. This occurs when the
530846daa99bSdan   ** SELECT is rewritten for window-functions processing and then passed
530946daa99bSdan   ** to sqlite3SelectPrep() and similar a second time. The rewriting done
531046daa99bSdan   ** by this function is not required in this case. */
531146daa99bSdan   if( a[0].u.x.iOrderByCol ) return WRC_Continue;
531246daa99bSdan #endif
5313c01b7306Sdrh   for(i=p->pOrderBy->nExpr-1; i>=0; i--){
5314c01b7306Sdrh     if( a[i].pExpr->flags & EP_Collate ) break;
5315c01b7306Sdrh   }
5316c01b7306Sdrh   if( i<0 ) return WRC_Continue;
5317c01b7306Sdrh 
5318c01b7306Sdrh   /* If we reach this point, that means the transformation is required. */
5319c01b7306Sdrh 
5320c01b7306Sdrh   pParse = pWalker->pParse;
5321c01b7306Sdrh   db = pParse->db;
5322c01b7306Sdrh   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
5323c01b7306Sdrh   if( pNew==0 ) return WRC_Abort;
5324c01b7306Sdrh   memset(&dummy, 0, sizeof(dummy));
5325d44f8b23Sdrh   pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0);
5326c01b7306Sdrh   if( pNewSrc==0 ) return WRC_Abort;
5327c01b7306Sdrh   *pNew = *p;
5328c01b7306Sdrh   p->pSrc = pNewSrc;
53291a1d3cd2Sdrh   p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
5330c01b7306Sdrh   p->op = TK_SELECT;
5331c01b7306Sdrh   p->pWhere = 0;
5332c01b7306Sdrh   pNew->pGroupBy = 0;
5333c01b7306Sdrh   pNew->pHaving = 0;
5334c01b7306Sdrh   pNew->pOrderBy = 0;
5335c01b7306Sdrh   p->pPrior = 0;
53368af9ad95Sdrh   p->pNext = 0;
5337f932f714Sdrh   p->pWith = 0;
5338fcc057dbSdan #ifndef SQLITE_OMIT_WINDOWFUNC
5339fcc057dbSdan   p->pWinDefn = 0;
5340fcc057dbSdan #endif
53418af9ad95Sdrh   p->selFlags &= ~SF_Compound;
5342b33c50f2Sdan   assert( (p->selFlags & SF_Converted)==0 );
5343b33c50f2Sdan   p->selFlags |= SF_Converted;
5344a6e3a8c9Sdrh   assert( pNew->pPrior!=0 );
5345a6e3a8c9Sdrh   pNew->pPrior->pNext = pNew;
5346c01b7306Sdrh   pNew->pLimit = 0;
5347c01b7306Sdrh   return WRC_Continue;
5348c01b7306Sdrh }
5349b1c685b0Sdanielk1977 
535020292310Sdrh /*
535120292310Sdrh ** Check to see if the FROM clause term pFrom has table-valued function
535220292310Sdrh ** arguments.  If it does, leave an error message in pParse and return
535320292310Sdrh ** non-zero, since pFrom is not allowed to be a table-valued function.
535420292310Sdrh */
cannotBeFunction(Parse * pParse,SrcItem * pFrom)53557601294aSdrh static int cannotBeFunction(Parse *pParse, SrcItem *pFrom){
535620292310Sdrh   if( pFrom->fg.isTabFunc ){
535720292310Sdrh     sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
535820292310Sdrh     return 1;
535920292310Sdrh   }
536020292310Sdrh   return 0;
536120292310Sdrh }
536220292310Sdrh 
5363eede6a53Sdan #ifndef SQLITE_OMIT_CTE
5364eede6a53Sdan /*
5365eede6a53Sdan ** Argument pWith (which may be NULL) points to a linked list of nested
5366eede6a53Sdan ** WITH contexts, from inner to outermost. If the table identified by
5367eede6a53Sdan ** FROM clause element pItem is really a common-table-expression (CTE)
5368eede6a53Sdan ** then return a pointer to the CTE definition for that table. Otherwise
5369eede6a53Sdan ** return NULL.
537098f45e53Sdan **
537198f45e53Sdan ** If a non-NULL value is returned, set *ppContext to point to the With
537298f45e53Sdan ** object that the returned CTE belongs to.
537360c1a2f0Sdrh */
searchWith(With * pWith,SrcItem * pItem,With ** ppContext)537498f45e53Sdan static struct Cte *searchWith(
53752476a6f2Sdrh   With *pWith,                    /* Current innermost WITH clause */
53767601294aSdrh   SrcItem *pItem,                 /* FROM clause element to resolve */
537798f45e53Sdan   With **ppContext                /* OUT: WITH clause return value belongs to */
537898f45e53Sdan ){
53795abe1d3dSdrh   const char *zName = pItem->zName;
5380eede6a53Sdan   With *p;
53815abe1d3dSdrh   assert( pItem->zDatabase==0 );
53825abe1d3dSdrh   assert( zName!=0 );
5383eede6a53Sdan   for(p=pWith; p; p=p->pOuter){
53844e9119d9Sdan     int i;
5385eede6a53Sdan     for(i=0; i<p->nCte; i++){
5386eede6a53Sdan       if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
538798f45e53Sdan         *ppContext = p;
5388eede6a53Sdan         return &p->a[i];
53894e9119d9Sdan       }
53904e9119d9Sdan     }
539190bc36fbSdan     if( p->bView ) break;
53924e9119d9Sdan   }
53934e9119d9Sdan   return 0;
53944e9119d9Sdan }
53954e9119d9Sdan 
5396c49832c2Sdrh /* The code generator maintains a stack of active WITH clauses
5397c49832c2Sdrh ** with the inner-most WITH clause being at the top of the stack.
5398c49832c2Sdrh **
5399b290f117Sdan ** This routine pushes the WITH clause passed as the second argument
5400b290f117Sdan ** onto the top of the stack. If argument bFree is true, then this
54017cc73b39Sdrh ** WITH clause will never be popped from the stack but should instead
54027cc73b39Sdrh ** be freed along with the Parse object. In other cases, when
5403b290f117Sdan ** bFree==0, the With object will be freed along with the SELECT
5404b290f117Sdan ** statement with which it is associated.
540524ce9446Sdrh **
540624ce9446Sdrh ** This routine returns a copy of pWith.  Or, if bFree is true and
540724ce9446Sdrh ** the pWith object is destroyed immediately due to an OOM condition,
540824ce9446Sdrh ** then this routine return NULL.
540924ce9446Sdrh **
541024ce9446Sdrh ** If bFree is true, do not continue to use the pWith pointer after
541124ce9446Sdrh ** calling this routine,  Instead, use only the return value.
5412c49832c2Sdrh */
sqlite3WithPush(Parse * pParse,With * pWith,u8 bFree)541324ce9446Sdrh With *sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
54144e9119d9Sdan   if( pWith ){
541524ce9446Sdrh     if( bFree ){
541624ce9446Sdrh       pWith = (With*)sqlite3ParserAddCleanup(pParse,
541724ce9446Sdrh                       (void(*)(sqlite3*,void*))sqlite3WithDelete,
541824ce9446Sdrh                       pWith);
541924ce9446Sdrh       if( pWith==0 ) return 0;
542024ce9446Sdrh     }
54217cc73b39Sdrh     if( pParse->nErr==0 ){
54222476a6f2Sdrh       assert( pParse->pWith!=pWith );
54234e9119d9Sdan       pWith->pOuter = pParse->pWith;
54244e9119d9Sdan       pParse->pWith = pWith;
54257cc73b39Sdrh     }
5426cf3c078fSdrh   }
542724ce9446Sdrh   return pWith;
54284e9119d9Sdan }
54294e9119d9Sdan 
5430eede6a53Sdan /*
5431eede6a53Sdan ** This function checks if argument pFrom refers to a CTE declared by
54325abe1d3dSdrh ** a WITH clause on the stack currently maintained by the parser (on the
54335abe1d3dSdrh ** pParse->pWith linked list).  And if currently processing a CTE
54345abe1d3dSdrh ** CTE expression, through routine checks to see if the reference is
54355abe1d3dSdrh ** a recursive reference to the CTE.
5436eede6a53Sdan **
54375abe1d3dSdrh ** If pFrom matches a CTE according to either of these two above, pFrom->pTab
54385abe1d3dSdrh ** and other fields are populated accordingly.
5439eede6a53Sdan **
54405abe1d3dSdrh ** Return 0 if no match is found.
54415abe1d3dSdrh ** Return 1 if a match is found.
54425abe1d3dSdrh ** Return 2 if an error condition is detected.
5443eede6a53Sdan */
resolveFromTermToCte(Parse * pParse,Walker * pWalker,SrcItem * pFrom)54445abe1d3dSdrh static int resolveFromTermToCte(
54455abe1d3dSdrh   Parse *pParse,                  /* The parsing context */
54465abe1d3dSdrh   Walker *pWalker,                /* Current tree walker */
54477601294aSdrh   SrcItem *pFrom                  /* The FROM clause term to check */
54488ce7184bSdan ){
54495abe1d3dSdrh   Cte *pCte;               /* Matched CTE (or NULL if no match) */
54505abe1d3dSdrh   With *pWith;             /* The matching WITH */
54518ce7184bSdan 
54528ce7184bSdan   assert( pFrom->pTab==0 );
54535abe1d3dSdrh   if( pParse->pWith==0 ){
54545abe1d3dSdrh     /* There are no WITH clauses in the stack.  No match is possible */
54555abe1d3dSdrh     return 0;
545646a31cdfSdrh   }
545793c8139cSdrh   if( pParse->nErr ){
545893c8139cSdrh     /* Prior errors might have left pParse->pWith in a goofy state, so
545993c8139cSdrh     ** go no further. */
546093c8139cSdrh     return 0;
546193c8139cSdrh   }
54625abe1d3dSdrh   if( pFrom->zDatabase!=0 ){
54635abe1d3dSdrh     /* The FROM term contains a schema qualifier (ex: main.t1) and so
54645abe1d3dSdrh     ** it cannot possibly be a CTE reference. */
54655abe1d3dSdrh     return 0;
54665abe1d3dSdrh   }
5467cd1499f4Sdrh   if( pFrom->fg.notCte ){
5468cd1499f4Sdrh     /* The FROM term is specifically excluded from matching a CTE.
5469cd1499f4Sdrh     **   (1)  It is part of a trigger that used to have zDatabase but had
5470cd1499f4Sdrh     **        zDatabase removed by sqlite3FixTriggerStep().
5471cd1499f4Sdrh     **   (2)  This is the first term in the FROM clause of an UPDATE.
5472cd1499f4Sdrh     */
5473cd1499f4Sdrh     return 0;
5474cd1499f4Sdrh   }
547598f45e53Sdan   pCte = searchWith(pParse->pWith, pFrom, &pWith);
5476eae73fbfSdan   if( pCte ){
54775abe1d3dSdrh     sqlite3 *db = pParse->db;
547898f45e53Sdan     Table *pTab;
54798ce7184bSdan     ExprList *pEList;
54808ce7184bSdan     Select *pSel;
548160e7068dSdan     Select *pLeft;                /* Left-most SELECT statement */
548234055854Sdrh     Select *pRecTerm;             /* Left-most recursive term */
5483f2655fe8Sdan     int bMayRecursive;            /* True if compound joined by UNION [ALL] */
548498f45e53Sdan     With *pSavedWith;             /* Initial value of pParse->pWith */
548534055854Sdrh     int iRecTab = -1;             /* Cursor for recursive table */
5486745912efSdrh     CteUse *pCteUse;
5487f2655fe8Sdan 
54880576bc59Sdrh     /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
5489f2655fe8Sdan     ** recursive reference to CTE pCte. Leave an error in pParse and return
54900576bc59Sdrh     ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
5491f2655fe8Sdan     ** In this case, proceed.  */
54920576bc59Sdrh     if( pCte->zCteErr ){
54930576bc59Sdrh       sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
54945abe1d3dSdrh       return 2;
5495f2655fe8Sdan     }
54965abe1d3dSdrh     if( cannotBeFunction(pParse, pFrom) ) return 2;
54978ce7184bSdan 
5498c25e2ebcSdrh     assert( pFrom->pTab==0 );
5499a79e2a2dSdrh     pTab = sqlite3DbMallocZero(db, sizeof(Table));
55005abe1d3dSdrh     if( pTab==0 ) return 2;
5501745912efSdrh     pCteUse = pCte->pUse;
5502745912efSdrh     if( pCteUse==0 ){
5503745912efSdrh       pCte->pUse = pCteUse = sqlite3DbMallocZero(db, sizeof(pCteUse[0]));
5504745912efSdrh       if( pCteUse==0
5505745912efSdrh        || sqlite3ParserAddCleanup(pParse,sqlite3DbFree,pCteUse)==0
5506a79e2a2dSdrh       ){
5507a79e2a2dSdrh         sqlite3DbFree(db, pTab);
5508a79e2a2dSdrh         return 2;
5509a79e2a2dSdrh       }
5510745912efSdrh       pCteUse->eM10d = pCte->eM10d;
5511a79e2a2dSdrh     }
5512a79e2a2dSdrh     pFrom->pTab = pTab;
551379df7782Sdrh     pTab->nTabRef = 1;
55142d4dc5fcSdan     pTab->zName = sqlite3DbStrDup(db, pCte->zName);
55158ce7184bSdan     pTab->iPKey = -1;
5516cfc9df76Sdan     pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
5517fccda8a1Sdrh     pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
55188ce7184bSdan     pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
55195abe1d3dSdrh     if( db->mallocFailed ) return 2;
5520ac67f567Sdan     pFrom->pSelect->selFlags |= SF_CopyCte;
55218ce7184bSdan     assert( pFrom->pSelect );
55220c1da689Sdrh     if( pFrom->fg.isIndexedBy ){
55230c1da689Sdrh       sqlite3ErrorMsg(pParse, "no such index: \"%s\"", pFrom->u1.zIndexedBy);
55240c1da689Sdrh       return 2;
55250c1da689Sdrh     }
5526a79e2a2dSdrh     pFrom->fg.isCte = 1;
5527745912efSdrh     pFrom->u2.pCteUse = pCteUse;
5528745912efSdrh     pCteUse->nUse++;
5529745912efSdrh     if( pCteUse->nUse>=2 && pCteUse->eM10d==M10d_Any ){
5530745912efSdrh       pCteUse->eM10d = M10d_Yes;
5531745912efSdrh     }
55328ce7184bSdan 
5533eae73fbfSdan     /* Check if this is a recursive CTE. */
553434055854Sdrh     pRecTerm = pSel = pFrom->pSelect;
5535f2655fe8Sdan     bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
553634055854Sdrh     while( bMayRecursive && pRecTerm->op==pSel->op ){
5537eae73fbfSdan       int i;
553834055854Sdrh       SrcList *pSrc = pRecTerm->pSrc;
553934055854Sdrh       assert( pRecTerm->pPrior!=0 );
5540eae73fbfSdan       for(i=0; i<pSrc->nSrc; i++){
55417601294aSdrh         SrcItem *pItem = &pSrc->a[i];
5542eae73fbfSdan         if( pItem->zDatabase==0
5543eae73fbfSdan          && pItem->zName!=0
5544eae73fbfSdan          && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
5545eae73fbfSdan         ){
5546eae73fbfSdan           pItem->pTab = pTab;
554794d6f3f8Sdrh           pTab->nTabRef++;
55488a48b9c0Sdrh           pItem->fg.isRecursive = 1;
554934055854Sdrh           if( pRecTerm->selFlags & SF_Recursive ){
555034055854Sdrh             sqlite3ErrorMsg(pParse,
555134055854Sdrh                "multiple references to recursive table: %s", pCte->zName
5552eae73fbfSdan             );
55535abe1d3dSdrh             return 2;
5554eae73fbfSdan           }
555534055854Sdrh           pRecTerm->selFlags |= SF_Recursive;
555634055854Sdrh           if( iRecTab<0 ) iRecTab = pParse->nTab++;
555734055854Sdrh           pItem->iCursor = iRecTab;
555834055854Sdrh         }
555934055854Sdrh       }
556034055854Sdrh       if( (pRecTerm->selFlags & SF_Recursive)==0 ) break;
556134055854Sdrh       pRecTerm = pRecTerm->pPrior;
556234055854Sdrh     }
5563eae73fbfSdan 
55640576bc59Sdrh     pCte->zCteErr = "circular reference: %s";
556598f45e53Sdan     pSavedWith = pParse->pWith;
556698f45e53Sdan     pParse->pWith = pWith;
556734055854Sdrh     if( pSel->selFlags & SF_Recursive ){
5568ca237a8bSdan       int rc;
556934055854Sdrh       assert( pRecTerm!=0 );
557034055854Sdrh       assert( (pRecTerm->selFlags & SF_Recursive)==0 );
557134055854Sdrh       assert( pRecTerm->pNext!=0 );
557234055854Sdrh       assert( (pRecTerm->pNext->selFlags & SF_Recursive)!=0 );
557334055854Sdrh       assert( pRecTerm->pWith==0 );
557434055854Sdrh       pRecTerm->pWith = pSel->pWith;
5575ca237a8bSdan       rc = sqlite3WalkSelect(pWalker, pRecTerm);
557634055854Sdrh       pRecTerm->pWith = 0;
5577ca237a8bSdan       if( rc ){
5578ca237a8bSdan         pParse->pWith = pSavedWith;
5579ca237a8bSdan         return 2;
5580ca237a8bSdan       }
5581067cd837Sdan     }else{
5582ca237a8bSdan       if( sqlite3WalkSelect(pWalker, pSel) ){
5583ca237a8bSdan         pParse->pWith = pSavedWith;
5584ca237a8bSdan         return 2;
5585ca237a8bSdan       }
5586067cd837Sdan     }
55876e772266Sdrh     pParse->pWith = pWith;
55888ce7184bSdan 
55898ce7184bSdan     for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
55908ce7184bSdan     pEList = pLeft->pEList;
559160e7068dSdan     if( pCte->pCols ){
55928f9d0b2bSdrh       if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
5593727a99f1Sdrh         sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
559460e7068dSdan             pCte->zName, pEList->nExpr, pCte->pCols->nExpr
559560e7068dSdan         );
559698f45e53Sdan         pParse->pWith = pSavedWith;
55975abe1d3dSdrh         return 2;
55988ce7184bSdan       }
559960e7068dSdan       pEList = pCte->pCols;
560060e7068dSdan     }
56018ce7184bSdan 
56028981b904Sdrh     sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
5603f2655fe8Sdan     if( bMayRecursive ){
5604f2655fe8Sdan       if( pSel->selFlags & SF_Recursive ){
56050576bc59Sdrh         pCte->zCteErr = "multiple recursive references: %s";
5606f2655fe8Sdan       }else{
56070576bc59Sdrh         pCte->zCteErr = "recursive reference in a subquery: %s";
5608f2655fe8Sdan       }
5609f2655fe8Sdan       sqlite3WalkSelect(pWalker, pSel);
5610f2655fe8Sdan     }
56110576bc59Sdrh     pCte->zCteErr = 0;
561298f45e53Sdan     pParse->pWith = pSavedWith;
56135abe1d3dSdrh     return 1;  /* Success */
56148ce7184bSdan   }
56155abe1d3dSdrh   return 0;  /* No match */
56168ce7184bSdan }
5617eede6a53Sdan #endif
56184e9119d9Sdan 
5619b290f117Sdan #ifndef SQLITE_OMIT_CTE
562071856944Sdan /*
562171856944Sdan ** If the SELECT passed as the second argument has an associated WITH
562271856944Sdan ** clause, pop it from the stack stored as part of the Parse object.
562371856944Sdan **
562471856944Sdan ** This function is used as the xSelectCallback2() callback by
562571856944Sdan ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
562671856944Sdan ** names and other FROM clause elements.
562771856944Sdan */
sqlite3SelectPopWith(Walker * pWalker,Select * p)5628be12083bSdan void sqlite3SelectPopWith(Walker *pWalker, Select *p){
5629b290f117Sdan   Parse *pParse = pWalker->pParse;
56302f65b2f5Sdrh   if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
5631d227a291Sdrh     With *pWith = findRightmost(p)->pWith;
5632d227a291Sdrh     if( pWith!=0 ){
563370a32703Sdan       assert( pParse->pWith==pWith || pParse->nErr );
5634d227a291Sdrh       pParse->pWith = pWith->pOuter;
5635b290f117Sdan     }
5636b290f117Sdan   }
5637067cd837Sdan }
5638b290f117Sdan #endif
5639b290f117Sdan 
56409a94722dSdan /*
56413b88065dSdrh ** The SrcItem structure passed as the second argument represents a
56429a94722dSdan ** sub-query in the FROM clause of a SELECT statement. This function
56433b88065dSdrh ** allocates and populates the SrcItem.pTab object. If successful,
56449a94722dSdan ** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
56459a94722dSdan ** SQLITE_NOMEM.
56469a94722dSdan */
sqlite3ExpandSubquery(Parse * pParse,SrcItem * pFrom)56477601294aSdrh int sqlite3ExpandSubquery(Parse *pParse, SrcItem *pFrom){
564886fb6e17Sdan   Select *pSel = pFrom->pSelect;
564986fb6e17Sdan   Table *pTab;
565086fb6e17Sdan 
56519a94722dSdan   assert( pSel );
565286fb6e17Sdan   pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
56539a94722dSdan   if( pTab==0 ) return SQLITE_NOMEM;
565486fb6e17Sdan   pTab->nTabRef = 1;
565586fb6e17Sdan   if( pFrom->zAlias ){
565686fb6e17Sdan     pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
565786fb6e17Sdan   }else{
5658d6bb6000Sdrh     pTab->zName = sqlite3MPrintf(pParse->db, "%!S", pFrom);
565986fb6e17Sdan   }
566086fb6e17Sdan   while( pSel->pPrior ){ pSel = pSel->pPrior; }
566186fb6e17Sdan   sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
566286fb6e17Sdan   pTab->iPKey = -1;
566386fb6e17Sdan   pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
56646e5020e8Sdrh #ifndef SQLITE_ALLOW_ROWID_IN_VIEW
56656e5020e8Sdrh   /* The usual case - do not allow ROWID on a subquery */
56666e5020e8Sdrh   pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
56676e5020e8Sdrh #else
56686e5020e8Sdrh   pTab->tabFlags |= TF_Ephemeral;  /* Legacy compatibility mode */
56696e5020e8Sdrh #endif
5670f4b33153Sdrh   return pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
567186fb6e17Sdan }
567286fb6e17Sdan 
56734ce7bf91Sdrh 
56744ce7bf91Sdrh /*
56754ce7bf91Sdrh ** Check the N SrcItem objects to the right of pBase.  (N might be zero!)
56764ce7bf91Sdrh ** If any of those SrcItem objects have a USING clause containing zName
56774ce7bf91Sdrh ** then return true.
56784ce7bf91Sdrh **
56794ce7bf91Sdrh ** If N is zero, or none of the N SrcItem objects to the right of pBase
56804ce7bf91Sdrh ** contains a USING clause, or if none of the USING clauses contain zName,
56814ce7bf91Sdrh ** then return false.
56824ce7bf91Sdrh */
inAnyUsingClause(const char * zName,SrcItem * pBase,int N)56834ce7bf91Sdrh static int inAnyUsingClause(
56844ce7bf91Sdrh   const char *zName, /* Name we are looking for */
56854ce7bf91Sdrh   SrcItem *pBase,    /* The base SrcItem.  Looking at pBase[1] and following */
56864ce7bf91Sdrh   int N              /* How many SrcItems to check */
56874ce7bf91Sdrh ){
56884ce7bf91Sdrh   while( N>0 ){
56894ce7bf91Sdrh     N--;
56904ce7bf91Sdrh     pBase++;
56914ce7bf91Sdrh     if( pBase->fg.isUsing==0 ) continue;
5692e32d6a0bSdrh     if( NEVER(pBase->u3.pUsing==0) ) continue;
56934ce7bf91Sdrh     if( sqlite3IdListIndex(pBase->u3.pUsing, zName)>=0 ) return 1;
56944ce7bf91Sdrh   }
56954ce7bf91Sdrh   return 0;
56964ce7bf91Sdrh }
56974ce7bf91Sdrh 
56984ce7bf91Sdrh 
5699b1c685b0Sdanielk1977 /*
57007d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement.
57017d10d5a6Sdrh ** "Expanding" means to do the following:
57027d10d5a6Sdrh **
57037d10d5a6Sdrh **    (1)  Make sure VDBE cursor numbers have been assigned to every
57047d10d5a6Sdrh **         element of the FROM clause.
57057d10d5a6Sdrh **
57067d10d5a6Sdrh **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
57077d10d5a6Sdrh **         defines FROM clause.  When views appear in the FROM clause,
57087d10d5a6Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
57097d10d5a6Sdrh **         that implements the view.  A copy is made of the view's SELECT
57107d10d5a6Sdrh **         statement so that we can freely modify or delete that statement
571160ec914cSpeter.d.reid **         without worrying about messing up the persistent representation
57127d10d5a6Sdrh **         of the view.
57137d10d5a6Sdrh **
571460ec914cSpeter.d.reid **    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
57157d10d5a6Sdrh **         on joins and the ON and USING clause of joins.
57167d10d5a6Sdrh **
57177d10d5a6Sdrh **    (4)  Scan the list of columns in the result set (pEList) looking
57187d10d5a6Sdrh **         for instances of the "*" operator or the TABLE.* operator.
57197d10d5a6Sdrh **         If found, expand each "*" to be every column in every table
57207d10d5a6Sdrh **         and TABLE.* to be every column in TABLE.
57217d10d5a6Sdrh **
5722b3bce662Sdanielk1977 */
selectExpander(Walker * pWalker,Select * p)57237d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){
57247d10d5a6Sdrh   Parse *pParse = pWalker->pParse;
57255abe1d3dSdrh   int i, j, k, rc;
57267d10d5a6Sdrh   SrcList *pTabList;
57277d10d5a6Sdrh   ExprList *pEList;
57287601294aSdrh   SrcItem *pFrom;
57297d10d5a6Sdrh   sqlite3 *db = pParse->db;
57303e3f1a5bSdrh   Expr *pE, *pRight, *pExpr;
5731785097daSdrh   u16 selFlags = p->selFlags;
5732fca23557Sdrh   u32 elistFlags = 0;
57337d10d5a6Sdrh 
5734785097daSdrh   p->selFlags |= SF_Expanded;
57357d10d5a6Sdrh   if( db->mallocFailed  ){
57367d10d5a6Sdrh     return WRC_Abort;
57377d10d5a6Sdrh   }
57389d9c41e2Sdrh   assert( p->pSrc!=0 );
57399d9c41e2Sdrh   if( (selFlags & SF_Expanded)!=0 ){
57407d10d5a6Sdrh     return WRC_Prune;
57417d10d5a6Sdrh   }
574259145813Sdrh   if( pWalker->eCode ){
574359145813Sdrh     /* Renumber selId because it has been copied from a view */
574459145813Sdrh     p->selId = ++pParse->nSelect;
574559145813Sdrh   }
57467d10d5a6Sdrh   pTabList = p->pSrc;
57477d10d5a6Sdrh   pEList = p->pEList;
574890bc36fbSdan   if( pParse->pWith && (p->selFlags & SF_View) ){
574990bc36fbSdan     if( p->pWith==0 ){
575090bc36fbSdan       p->pWith = (With*)sqlite3DbMallocZero(db, sizeof(With));
575190bc36fbSdan       if( p->pWith==0 ){
575290bc36fbSdan         return WRC_Abort;
575390bc36fbSdan       }
575490bc36fbSdan     }
575590bc36fbSdan     p->pWith->bView = 1;
575690bc36fbSdan   }
5757067cd837Sdan   sqlite3WithPush(pParse, p->pWith, 0);
57587d10d5a6Sdrh 
57597d10d5a6Sdrh   /* Make sure cursor numbers have been assigned to all entries in
57607d10d5a6Sdrh   ** the FROM clause of the SELECT statement.
57617d10d5a6Sdrh   */
57627d10d5a6Sdrh   sqlite3SrcListAssignCursors(pParse, pTabList);
57637d10d5a6Sdrh 
57647d10d5a6Sdrh   /* Look up every table named in the FROM clause of the select.  If
57657d10d5a6Sdrh   ** an entry of the FROM clause is a subquery instead of a table or view,
57667d10d5a6Sdrh   ** then create a transient table structure to describe the subquery.
57677d10d5a6Sdrh   */
57687d10d5a6Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
57697d10d5a6Sdrh     Table *pTab;
5770e2b7d7a0Sdrh     assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
577169887c99Sdan     if( pFrom->pTab ) continue;
577269887c99Sdan     assert( pFrom->fg.isRecursive==0 );
57737d10d5a6Sdrh     if( pFrom->zName==0 ){
57747d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
57757d10d5a6Sdrh       Select *pSel = pFrom->pSelect;
57767d10d5a6Sdrh       /* A sub-query in the FROM clause of a SELECT */
57777d10d5a6Sdrh       assert( pSel!=0 );
57787d10d5a6Sdrh       assert( pFrom->pTab==0 );
57792b8c5a00Sdrh       if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
5780dfa552f4Sdan       if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;
578186fb6e17Sdan #endif
57825abe1d3dSdrh #ifndef SQLITE_OMIT_CTE
57835abe1d3dSdrh     }else if( (rc = resolveFromTermToCte(pParse, pWalker, pFrom))!=0 ){
57845abe1d3dSdrh       if( rc>1 ) return WRC_Abort;
57855abe1d3dSdrh       pTab = pFrom->pTab;
57865abe1d3dSdrh       assert( pTab!=0 );
57875abe1d3dSdrh #endif
57887d10d5a6Sdrh     }else{
57897d10d5a6Sdrh       /* An ordinary table or view name in the FROM clause */
57907d10d5a6Sdrh       assert( pFrom->pTab==0 );
579141fb5cd1Sdan       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
57927d10d5a6Sdrh       if( pTab==0 ) return WRC_Abort;
579379df7782Sdrh       if( pTab->nTabRef>=0xffff ){
5794d2a56238Sdrh         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
5795d2a56238Sdrh            pTab->zName);
5796d2a56238Sdrh         pFrom->pTab = 0;
5797d2a56238Sdrh         return WRC_Abort;
5798d2a56238Sdrh       }
579979df7782Sdrh       pTab->nTabRef++;
580020292310Sdrh       if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
580120292310Sdrh         return WRC_Abort;
580220292310Sdrh       }
58038c812f98Sdan #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
5804f38524d2Sdrh       if( !IsOrdinaryTable(pTab) ){
5805bfad7be7Sdrh         i16 nCol;
580659145813Sdrh         u8 eCodeOrig = pWalker->eCode;
58077d10d5a6Sdrh         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
580843152cf8Sdrh         assert( pFrom->pSelect==0 );
5809f38524d2Sdrh         if( IsView(pTab) ){
5810f38524d2Sdrh           if( (db->flags & SQLITE_EnableView)==0
581170149ba4Sdrh            && pTab->pSchema!=db->aDb[1].pSchema
581270149ba4Sdrh           ){
581311d88e68Sdrh             sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited",
581411d88e68Sdrh               pTab->zName);
58153f68142bSdrh           }
5816f38524d2Sdrh           pFrom->pSelect = sqlite3SelectDup(db, pTab->u.view.pSelect, 0);
5817afaa660aSdan         }
58188c812f98Sdan #ifndef SQLITE_OMIT_VIRTUALTABLE
5819afaa660aSdan         else if( ALWAYS(IsVirtual(pTab))
58203f68142bSdrh          && pFrom->fg.fromDDL
5821f38524d2Sdrh          && ALWAYS(pTab->u.vtab.p!=0)
5822f38524d2Sdrh          && pTab->u.vtab.p->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0)
58233f68142bSdrh         ){
582432266a10Sdrh           sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"",
582532266a10Sdrh                                   pTab->zName);
582611d88e68Sdrh         }
5827f38524d2Sdrh         assert( SQLITE_VTABRISK_Normal==1 && SQLITE_VTABRISK_High==2 );
58288c812f98Sdan #endif
5829bfad7be7Sdrh         nCol = pTab->nCol;
5830bfad7be7Sdrh         pTab->nCol = -1;
583159145813Sdrh         pWalker->eCode = 1;  /* Turn on Select.selId renumbering */
58327d10d5a6Sdrh         sqlite3WalkSelect(pWalker, pFrom->pSelect);
583359145813Sdrh         pWalker->eCode = eCodeOrig;
5834bfad7be7Sdrh         pTab->nCol = nCol;
58357d10d5a6Sdrh       }
58367d10d5a6Sdrh #endif
58377d10d5a6Sdrh     }
583885574e31Sdanielk1977 
583985574e31Sdanielk1977     /* Locate the index named by the INDEXED BY clause, if any. */
58401862271fSdrh     if( pFrom->fg.isIndexedBy && sqlite3IndexedByLookup(pParse, pFrom) ){
584185574e31Sdanielk1977       return WRC_Abort;
584285574e31Sdanielk1977     }
58437d10d5a6Sdrh   }
58447d10d5a6Sdrh 
58457d10d5a6Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
58467d10d5a6Sdrh   */
58470c7d3d39Sdrh   assert( db->mallocFailed==0 || pParse->nErr!=0 );
5848358424aeSdrh   if( pParse->nErr || sqlite3ProcessJoin(pParse, p) ){
58497d10d5a6Sdrh     return WRC_Abort;
58507d10d5a6Sdrh   }
58517d10d5a6Sdrh 
58527d10d5a6Sdrh   /* For every "*" that occurs in the column list, insert the names of
58537d10d5a6Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
58547d10d5a6Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
58551a1d3cd2Sdrh   ** with the TK_ASTERISK operator for each "*" that it found in the column
58561a1d3cd2Sdrh   ** list.  The following code just has to locate the TK_ASTERISK
58571a1d3cd2Sdrh   ** expressions and expand each one to the list of all columns in
58581a1d3cd2Sdrh   ** all tables.
58597d10d5a6Sdrh   **
58607d10d5a6Sdrh   ** The first loop just checks to see if there are any "*" operators
58617d10d5a6Sdrh   ** that need expanding.
58627d10d5a6Sdrh   */
58637d10d5a6Sdrh   for(k=0; k<pEList->nExpr; k++){
58643e3f1a5bSdrh     pE = pEList->a[k].pExpr;
58651a1d3cd2Sdrh     if( pE->op==TK_ASTERISK ) break;
586643152cf8Sdrh     assert( pE->op!=TK_DOT || pE->pRight!=0 );
586743152cf8Sdrh     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
58681a1d3cd2Sdrh     if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
5869fca23557Sdrh     elistFlags |= pE->flags;
58707d10d5a6Sdrh   }
58717d10d5a6Sdrh   if( k<pEList->nExpr ){
58727d10d5a6Sdrh     /*
58737d10d5a6Sdrh     ** If we get here it means the result set contains one or more "*"
58747d10d5a6Sdrh     ** operators that need to be expanded.  Loop through each expression
58757d10d5a6Sdrh     ** in the result set and expand them one by one.
58767d10d5a6Sdrh     */
58777d10d5a6Sdrh     struct ExprList_item *a = pEList->a;
58787d10d5a6Sdrh     ExprList *pNew = 0;
58797d10d5a6Sdrh     int flags = pParse->db->flags;
58807d10d5a6Sdrh     int longNames = (flags & SQLITE_FullColNames)!=0
588138b384a0Sdrh                       && (flags & SQLITE_ShortColNames)==0;
588238b384a0Sdrh 
58837d10d5a6Sdrh     for(k=0; k<pEList->nExpr; k++){
58843e3f1a5bSdrh       pE = a[k].pExpr;
5885fca23557Sdrh       elistFlags |= pE->flags;
58863e3f1a5bSdrh       pRight = pE->pRight;
58873e3f1a5bSdrh       assert( pE->op!=TK_DOT || pRight!=0 );
58881a1d3cd2Sdrh       if( pE->op!=TK_ASTERISK
58891a1d3cd2Sdrh        && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
58901a1d3cd2Sdrh       ){
58917d10d5a6Sdrh         /* This particular expression does not need to be expanded.
58927d10d5a6Sdrh         */
5893b7916a78Sdrh         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
58947d10d5a6Sdrh         if( pNew ){
589541cee668Sdrh           pNew->a[pNew->nExpr-1].zEName = a[k].zEName;
5896d88fd539Sdrh           pNew->a[pNew->nExpr-1].fg.eEName = a[k].fg.eEName;
589741cee668Sdrh           a[k].zEName = 0;
58987d10d5a6Sdrh         }
58997d10d5a6Sdrh         a[k].pExpr = 0;
59007d10d5a6Sdrh       }else{
59017d10d5a6Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
59027d10d5a6Sdrh         ** expanded. */
59037d10d5a6Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
59043e3f1a5bSdrh         char *zTName = 0;       /* text of name of TABLE */
590543152cf8Sdrh         if( pE->op==TK_DOT ){
590643152cf8Sdrh           assert( pE->pLeft!=0 );
590733e619fcSdrh           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
590833e619fcSdrh           zTName = pE->pLeft->u.zToken;
59097d10d5a6Sdrh         }
59107d10d5a6Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
59119c2d7aa7Sdrh           Table *pTab = pFrom->pTab;   /* Table for this data source */
59129c2d7aa7Sdrh           ExprList *pNestedFrom;       /* Result-set of a nested FROM clause */
59139c2d7aa7Sdrh           char *zTabName;              /* AS name for this data source */
59149c2d7aa7Sdrh           const char *zSchemaName = 0; /* Schema name for this data source */
59159c2d7aa7Sdrh           int iDb;                     /* Schema index for this data src */
591663879a2cSdrh           IdList *pUsing;              /* USING clause for pFrom[1] */
59179c2d7aa7Sdrh 
59189c2d7aa7Sdrh           if( (zTabName = pFrom->zAlias)==0 ){
59197d10d5a6Sdrh             zTabName = pTab->zName;
59207d10d5a6Sdrh           }
59217d10d5a6Sdrh           if( db->mallocFailed ) break;
592207fae32dSmistachkin           assert( (int)pFrom->fg.isNestedFrom == IsNestedFrom(pFrom->pSelect) );
5923815b782eSdrh           if( pFrom->fg.isNestedFrom ){
59249c2d7aa7Sdrh             assert( pFrom->pSelect!=0 );
59259c2d7aa7Sdrh             pNestedFrom = pFrom->pSelect->pEList;
59269c2d7aa7Sdrh             assert( pNestedFrom!=0 );
59279c2d7aa7Sdrh             assert( pNestedFrom->nExpr==pTab->nCol );
5928815b782eSdrh           }else{
59297d10d5a6Sdrh             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
59307d10d5a6Sdrh               continue;
59317d10d5a6Sdrh             }
59329c2d7aa7Sdrh             pNestedFrom = 0;
59333e3f1a5bSdrh             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
593469c33826Sdrh             zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
59353e3f1a5bSdrh           }
593645e41b73Sdrh           if( i+1<pTabList->nSrc
593745e41b73Sdrh            && pFrom[1].fg.isUsing
593845e41b73Sdrh            && (selFlags & SF_NestedFrom)!=0
593945e41b73Sdrh           ){
594045e41b73Sdrh             int ii;
594172d620bdSdrh             pUsing = pFrom[1].u3.pUsing;
594245e41b73Sdrh             for(ii=0; ii<pUsing->nId; ii++){
594345e41b73Sdrh               const char *zUName = pUsing->a[ii].zName;
594445e41b73Sdrh               pRight = sqlite3Expr(db, TK_ID, zUName);
594545e41b73Sdrh               pNew = sqlite3ExprListAppend(pParse, pNew, pRight);
594645e41b73Sdrh               if( pNew ){
594745e41b73Sdrh                 struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
594845e41b73Sdrh                 assert( pX->zEName==0 );
594945e41b73Sdrh                 pX->zEName = sqlite3MPrintf(db,"..%s", zUName);
5950d88fd539Sdrh                 pX->fg.eEName = ENAME_TAB;
5951d88fd539Sdrh                 pX->fg.bUsingTerm = 1;
595245e41b73Sdrh               }
595345e41b73Sdrh             }
595472d620bdSdrh           }else{
595572d620bdSdrh             pUsing = 0;
595645e41b73Sdrh           }
59577d10d5a6Sdrh           for(j=0; j<pTab->nCol; j++){
5958cf9d36d1Sdrh             char *zName = pTab->aCol[j].zCnName;
595918f8600fSdrh             struct ExprList_item *pX; /* Newly added ExprList term */
59607d10d5a6Sdrh 
5961c75e09c7Sdrh             assert( zName );
59629c2d7aa7Sdrh             if( zTName
59639c2d7aa7Sdrh              && pNestedFrom
59649c2d7aa7Sdrh              && sqlite3MatchEName(&pNestedFrom->a[j], 0, zTName, 0)==0
59653e3f1a5bSdrh             ){
59663e3f1a5bSdrh               continue;
59673e3f1a5bSdrh             }
59683e3f1a5bSdrh 
596980090f92Sdrh             /* If a column is marked as 'hidden', omit it from the expanded
597080090f92Sdrh             ** result-set list unless the SELECT has the SF_IncludeHidden
597180090f92Sdrh             ** bit set.
59727d10d5a6Sdrh             */
5973adef1598Sdrh             if( (p->selFlags & SF_IncludeHidden)==0
5974adef1598Sdrh              && IsHiddenColumn(&pTab->aCol[j])
597580090f92Sdrh             ){
59767d10d5a6Sdrh               continue;
59777d10d5a6Sdrh             }
5978adef1598Sdrh             if( (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND)!=0
5979ab843a51Sdrh              && zTName==0
59804bea8c6bSdrh              && (selFlags & (SF_NestedFrom))==0
5981ab843a51Sdrh             ){
5982ab843a51Sdrh               continue;
5983ab843a51Sdrh             }
59843e3f1a5bSdrh             tableSeen = 1;
59857d10d5a6Sdrh 
598645e41b73Sdrh             if( i>0 && zTName==0 && (selFlags & SF_NestedFrom)==0 ){
5987d44f8b23Sdrh               if( pFrom->fg.isUsing
5988d44f8b23Sdrh                && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0
5989d44f8b23Sdrh               ){
59907d10d5a6Sdrh                 /* In a join with a USING clause, omit columns in the
59917d10d5a6Sdrh                 ** using clause from the table on the right. */
59927d10d5a6Sdrh                 continue;
59937d10d5a6Sdrh               }
59947d10d5a6Sdrh             }
5995b7916a78Sdrh             pRight = sqlite3Expr(db, TK_ID, zName);
5996befbb40fSdrh             if( (pTabList->nSrc>1
5997bdbda1ebSdrh                  && (  (pFrom->fg.jointype & JT_LTORJ)==0
5998d63c07e6Sdrh                      || (selFlags & SF_NestedFrom)!=0
5999befbb40fSdrh                      || !inAnyUsingClause(zName,pFrom,pTabList->nSrc-i-1)
6000befbb40fSdrh                     )
6001befbb40fSdrh                 )
6002befbb40fSdrh              || IN_RENAME_OBJECT
60034ce7bf91Sdrh             ){
6004b7916a78Sdrh               Expr *pLeft;
6005b7916a78Sdrh               pLeft = sqlite3Expr(db, TK_ID, zTabName);
6006abfd35eaSdrh               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
6007cbde37d8Sdan               if( IN_RENAME_OBJECT && pE->pLeft ){
6008cbde37d8Sdan                 sqlite3RenameTokenRemap(pParse, pLeft, pE->pLeft);
6009cbde37d8Sdan               }
601038b384a0Sdrh               if( zSchemaName ){
6011c75e09c7Sdrh                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
6012abfd35eaSdrh                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
6013c75e09c7Sdrh               }
60147d10d5a6Sdrh             }else{
60157d10d5a6Sdrh               pExpr = pRight;
60167d10d5a6Sdrh             }
6017b7916a78Sdrh             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
601818f8600fSdrh             if( pNew==0 ){
601918f8600fSdrh               break;  /* OOM */
602018f8600fSdrh             }
602118f8600fSdrh             pX = &pNew->a[pNew->nExpr-1];
602218f8600fSdrh             assert( pX->zEName==0 );
602318f8600fSdrh             if( (selFlags & SF_NestedFrom)!=0 && !IN_RENAME_OBJECT ){
60249c2d7aa7Sdrh               if( pNestedFrom ){
60259c2d7aa7Sdrh                 pX->zEName = sqlite3DbStrDup(db, pNestedFrom->a[j].zEName);
6026cbb9da33Sdrh                 testcase( pX->zEName==0 );
60273e3f1a5bSdrh               }else{
6028cbb9da33Sdrh                 pX->zEName = sqlite3MPrintf(db, "%s.%s.%s",
602918f8600fSdrh                                            zSchemaName, zTabName, zName);
6030cbb9da33Sdrh                 testcase( pX->zEName==0 );
60313e3f1a5bSdrh               }
6032d88fd539Sdrh               pX->fg.eEName = ENAME_TAB;
603372d620bdSdrh               if( (pFrom->fg.isUsing
603472d620bdSdrh                    && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0)
603572d620bdSdrh                || (pUsing && sqlite3IdListIndex(pUsing, zName)>=0)
603672d620bdSdrh                || (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND)!=0
603772d620bdSdrh               ){
6038d88fd539Sdrh                 pX->fg.bNoExpand = 1;
603972d620bdSdrh               }
604018f8600fSdrh             }else if( longNames ){
604118f8600fSdrh               pX->zEName = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
6042d88fd539Sdrh               pX->fg.eEName = ENAME_NAME;
604318f8600fSdrh             }else{
604418f8600fSdrh               pX->zEName = sqlite3DbStrDup(db, zName);
6045d88fd539Sdrh               pX->fg.eEName = ENAME_NAME;
60468f25d18bSdrh             }
60477d10d5a6Sdrh           }
60487d10d5a6Sdrh         }
60497d10d5a6Sdrh         if( !tableSeen ){
60507d10d5a6Sdrh           if( zTName ){
60517d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
60527d10d5a6Sdrh           }else{
60537d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no tables specified");
60547d10d5a6Sdrh           }
60557d10d5a6Sdrh         }
60567d10d5a6Sdrh       }
60577d10d5a6Sdrh     }
60587d10d5a6Sdrh     sqlite3ExprListDelete(db, pEList);
60597d10d5a6Sdrh     p->pEList = pNew;
60607d10d5a6Sdrh   }
6061fca23557Sdrh   if( p->pEList ){
6062fca23557Sdrh     if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
60637d10d5a6Sdrh       sqlite3ErrorMsg(pParse, "too many columns in result set");
60648836cbbcSdan       return WRC_Abort;
60657d10d5a6Sdrh     }
6066fca23557Sdrh     if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
6067fca23557Sdrh       p->selFlags |= SF_ComplexResult;
6068fca23557Sdrh     }
6069fca23557Sdrh   }
6070cebc8009Sdrh #if TREETRACE_ENABLED
6071cebc8009Sdrh   if( sqlite3TreeTrace & 0x100 ){
6072cebc8009Sdrh     SELECTTRACE(0x100,pParse,p,("After result-set wildcard expansion:\n"));
6073cebc8009Sdrh     sqlite3TreeViewSelect(0, p, 0);
6074cebc8009Sdrh   }
6075cebc8009Sdrh #endif
60767d10d5a6Sdrh   return WRC_Continue;
60777d10d5a6Sdrh }
60787d10d5a6Sdrh 
6079979dd1beSdrh #if SQLITE_DEBUG
6080979dd1beSdrh /*
6081979dd1beSdrh ** Always assert.  This xSelectCallback2 implementation proves that the
6082979dd1beSdrh ** xSelectCallback2 is never invoked.
6083979dd1beSdrh */
sqlite3SelectWalkAssert2(Walker * NotUsed,Select * NotUsed2)6084979dd1beSdrh void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
6085979dd1beSdrh   UNUSED_PARAMETER2(NotUsed, NotUsed2);
6086979dd1beSdrh   assert( 0 );
6087979dd1beSdrh }
6088979dd1beSdrh #endif
6089979dd1beSdrh /*
60907d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries.
60917d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT
60927d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above.
60937d10d5a6Sdrh **
60947d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a
60957d10d5a6Sdrh ** SELECT statement.  The SELECT statement must be expanded before
60967d10d5a6Sdrh ** name resolution is performed.
60977d10d5a6Sdrh **
60987d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse.
60997d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr
61007d10d5a6Sdrh ** and/or pParse->db->mallocFailed.
61017d10d5a6Sdrh */
sqlite3SelectExpand(Parse * pParse,Select * pSelect)61027d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
61037d10d5a6Sdrh   Walker w;
61045b88bc4bSdrh   w.xExprCallback = sqlite3ExprWalkNoop;
61057d10d5a6Sdrh   w.pParse = pParse;
6106878fcf9dSdrh   if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
6107d58d3278Sdrh     w.xSelectCallback = convertCompoundSelectToSubquery;
6108979dd1beSdrh     w.xSelectCallback2 = 0;
61097d10d5a6Sdrh     sqlite3WalkSelect(&w, pSelect);
6110d58d3278Sdrh   }
6111c01b7306Sdrh   w.xSelectCallback = selectExpander;
6112be12083bSdan   w.xSelectCallback2 = sqlite3SelectPopWith;
611359145813Sdrh   w.eCode = 0;
6114c01b7306Sdrh   sqlite3WalkSelect(&w, pSelect);
61157d10d5a6Sdrh }
61167d10d5a6Sdrh 
61177d10d5a6Sdrh 
61187d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
61197d10d5a6Sdrh /*
61207d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
61217d10d5a6Sdrh ** interface.
61227d10d5a6Sdrh **
61237d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl
61247d10d5a6Sdrh ** information to the Table structure that represents the result set
61257d10d5a6Sdrh ** of that subquery.
61267d10d5a6Sdrh **
61277d10d5a6Sdrh ** The Table structure that represents the result set was constructed
61287d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted
61297d10d5a6Sdrh ** at that point because identifiers had not yet been resolved.  This
61307d10d5a6Sdrh ** routine is called after identifier resolution.
61317d10d5a6Sdrh */
selectAddSubqueryTypeInfo(Walker * pWalker,Select * p)6132b290f117Sdan static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
61337d10d5a6Sdrh   Parse *pParse;
61347d10d5a6Sdrh   int i;
61357d10d5a6Sdrh   SrcList *pTabList;
61367601294aSdrh   SrcItem *pFrom;
61377d10d5a6Sdrh 
61389d8b3072Sdrh   assert( p->selFlags & SF_Resolved );
6139cc464418Sdan   if( p->selFlags & SF_HasTypeInfo ) return;
61407d10d5a6Sdrh   p->selFlags |= SF_HasTypeInfo;
61417d10d5a6Sdrh   pParse = pWalker->pParse;
61427d10d5a6Sdrh   pTabList = p->pSrc;
61437d10d5a6Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
61447d10d5a6Sdrh     Table *pTab = pFrom->pTab;
6145e2b7d7a0Sdrh     assert( pTab!=0 );
6146e2b7d7a0Sdrh     if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
61477d10d5a6Sdrh       /* A sub-query in the FROM clause of a SELECT */
61487d10d5a6Sdrh       Select *pSel = pFrom->pSelect;
61498ce7184bSdan       if( pSel ){
61507d10d5a6Sdrh         while( pSel->pPrior ) pSel = pSel->pPrior;
615196fb16eeSdrh         sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel,
615296fb16eeSdrh                                                SQLITE_AFF_NONE);
61537d10d5a6Sdrh       }
61547d10d5a6Sdrh     }
61555a29d9cbSdrh   }
61568ce7184bSdan }
61577d10d5a6Sdrh #endif
61587d10d5a6Sdrh 
61597d10d5a6Sdrh 
61607d10d5a6Sdrh /*
61617d10d5a6Sdrh ** This routine adds datatype and collating sequence information to
61627d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a
61637d10d5a6Sdrh ** SELECT statement.
61647d10d5a6Sdrh **
61657d10d5a6Sdrh ** Use this routine after name resolution.
61667d10d5a6Sdrh */
sqlite3SelectAddTypeInfo(Parse * pParse,Select * pSelect)61677d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
61687d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
61697d10d5a6Sdrh   Walker w;
6170979dd1beSdrh   w.xSelectCallback = sqlite3SelectWalkNoop;
6171b290f117Sdan   w.xSelectCallback2 = selectAddSubqueryTypeInfo;
61725b88bc4bSdrh   w.xExprCallback = sqlite3ExprWalkNoop;
61737d10d5a6Sdrh   w.pParse = pParse;
61747d10d5a6Sdrh   sqlite3WalkSelect(&w, pSelect);
61757d10d5a6Sdrh #endif
61767d10d5a6Sdrh }
61777d10d5a6Sdrh 
61787d10d5a6Sdrh 
61797d10d5a6Sdrh /*
6180030796dfSdrh ** This routine sets up a SELECT statement for processing.  The
61817d10d5a6Sdrh ** following is accomplished:
61827d10d5a6Sdrh **
61837d10d5a6Sdrh **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
61847d10d5a6Sdrh **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
61857d10d5a6Sdrh **     *  ON and USING clauses are shifted into WHERE statements
61867d10d5a6Sdrh **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
61877d10d5a6Sdrh **     *  Identifiers in expression are matched to tables.
61887d10d5a6Sdrh **
61897d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT.
61907d10d5a6Sdrh */
sqlite3SelectPrep(Parse * pParse,Select * p,NameContext * pOuterNC)61917d10d5a6Sdrh void sqlite3SelectPrep(
6192b3bce662Sdanielk1977   Parse *pParse,         /* The parser context */
6193b3bce662Sdanielk1977   Select *p,             /* The SELECT statement being coded. */
61947d10d5a6Sdrh   NameContext *pOuterNC  /* Name context for container */
6195b3bce662Sdanielk1977 ){
6196e2463398Sdrh   assert( p!=0 || pParse->db->mallocFailed );
61970c7d3d39Sdrh   assert( pParse->db->pParse==pParse );
6198e2463398Sdrh   if( pParse->db->mallocFailed ) return;
61997d10d5a6Sdrh   if( p->selFlags & SF_HasTypeInfo ) return;
62007d10d5a6Sdrh   sqlite3SelectExpand(pParse, p);
62010c7d3d39Sdrh   if( pParse->nErr ) return;
62027d10d5a6Sdrh   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
62030c7d3d39Sdrh   if( pParse->nErr ) return;
62047d10d5a6Sdrh   sqlite3SelectAddTypeInfo(pParse, p);
6205f6bbe022Sdrh }
6206b3bce662Sdanielk1977 
6207b3bce662Sdanielk1977 /*
620813449892Sdrh ** Reset the aggregate accumulator.
620913449892Sdrh **
621013449892Sdrh ** The aggregate accumulator is a set of memory cells that hold
621113449892Sdrh ** intermediate results while calculating an aggregate.  This
6212030796dfSdrh ** routine generates code that stores NULLs in all of those memory
6213030796dfSdrh ** cells.
6214b3bce662Sdanielk1977 */
resetAccumulator(Parse * pParse,AggInfo * pAggInfo)621513449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
621613449892Sdrh   Vdbe *v = pParse->pVdbe;
621713449892Sdrh   int i;
6218c99130fdSdrh   struct AggInfo_func *pFunc;
62197e61d18eSdrh   int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
62200c7d3d39Sdrh   assert( pParse->db->pParse==pParse );
62210c7d3d39Sdrh   assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
62227e61d18eSdrh   if( nReg==0 ) return;
62230c7d3d39Sdrh   if( pParse->nErr ) return;
62247e61d18eSdrh #ifdef SQLITE_DEBUG
62257e61d18eSdrh   /* Verify that all AggInfo registers are within the range specified by
62267e61d18eSdrh   ** AggInfo.mnReg..AggInfo.mxReg */
62277e61d18eSdrh   assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
622813449892Sdrh   for(i=0; i<pAggInfo->nColumn; i++){
62297e61d18eSdrh     assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
62307e61d18eSdrh          && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
623113449892Sdrh   }
62327e61d18eSdrh   for(i=0; i<pAggInfo->nFunc; i++){
62337e61d18eSdrh     assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
62347e61d18eSdrh          && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
62357e61d18eSdrh   }
62367e61d18eSdrh #endif
62377e61d18eSdrh   sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
6238c99130fdSdrh   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
6239c99130fdSdrh     if( pFunc->iDistinct>=0 ){
624081185a51Sdrh       Expr *pE = pFunc->pFExpr;
6241a4eeccdfSdrh       assert( ExprUseXList(pE) );
62426ab3a2ecSdanielk1977       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
62430daa002cSdrh         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
62440daa002cSdrh            "argument");
6245c99130fdSdrh         pFunc->iDistinct = -1;
6246c99130fdSdrh       }else{
6247f9eae18bSdan         KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
62484fcb30b7Sdan         pFunc->iDistAddr = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
62494fcb30b7Sdan             pFunc->iDistinct, 0, 0, (char*)pKeyInfo, P4_KEYINFO);
62509be1339fSdrh         ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s(DISTINCT)",
62519be1339fSdrh                           pFunc->pFunc->zName));
6252c99130fdSdrh       }
6253c99130fdSdrh     }
625413449892Sdrh   }
6255b3bce662Sdanielk1977 }
6256b3bce662Sdanielk1977 
6257b3bce662Sdanielk1977 /*
625813449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function
625913449892Sdrh ** in the AggInfo structure.
6260b3bce662Sdanielk1977 */
finalizeAggFunctions(Parse * pParse,AggInfo * pAggInfo)626113449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
626213449892Sdrh   Vdbe *v = pParse->pVdbe;
626313449892Sdrh   int i;
626413449892Sdrh   struct AggInfo_func *pF;
626513449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
6266a4eeccdfSdrh     ExprList *pList;
6267a4eeccdfSdrh     assert( ExprUseXList(pF->pFExpr) );
6268a4eeccdfSdrh     pList = pF->pFExpr->x.pList;
62692700acaaSdrh     sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
62702700acaaSdrh     sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
6271b3bce662Sdanielk1977   }
627213449892Sdrh }
627313449892Sdrh 
6274280c894bSdan 
627513449892Sdrh /*
627613449892Sdrh ** Update the accumulator memory cells for an aggregate based on
627713449892Sdrh ** the current cursor position.
6278280c894bSdan **
6279280c894bSdan ** If regAcc is non-zero and there are no min() or max() aggregates
6280280c894bSdan ** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
628110cc16c9Sdrh ** registers if register regAcc contains 0. The caller will take care
6282280c894bSdan ** of setting and clearing regAcc.
628313449892Sdrh */
updateAccumulator(Parse * pParse,int regAcc,AggInfo * pAggInfo,int eDistinctType)62844fcb30b7Sdan static void updateAccumulator(
62854fcb30b7Sdan   Parse *pParse,
62864fcb30b7Sdan   int regAcc,
62874fcb30b7Sdan   AggInfo *pAggInfo,
62884fcb30b7Sdan   int eDistinctType
62894fcb30b7Sdan ){
629013449892Sdrh   Vdbe *v = pParse->pVdbe;
629113449892Sdrh   int i;
62927a95789cSdrh   int regHit = 0;
62937a95789cSdrh   int addrHitTest = 0;
629413449892Sdrh   struct AggInfo_func *pF;
629513449892Sdrh   struct AggInfo_col *pC;
629613449892Sdrh 
629713449892Sdrh   pAggInfo->directMode = 1;
629813449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
629913449892Sdrh     int nArg;
6300c99130fdSdrh     int addrNext = 0;
630198757157Sdrh     int regAgg;
6302a4eeccdfSdrh     ExprList *pList;
6303a4eeccdfSdrh     assert( ExprUseXList(pF->pFExpr) );
630481185a51Sdrh     assert( !IsWindowFunc(pF->pFExpr) );
6305a4eeccdfSdrh     pList = pF->pFExpr->x.pList;
630681185a51Sdrh     if( ExprHasProperty(pF->pFExpr, EP_WinFunc) ){
630781185a51Sdrh       Expr *pFilter = pF->pFExpr->y.pWin->pFilter;
6308ed09dddeSdan       if( pAggInfo->nAccumulator
6309ed09dddeSdan        && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
6310fa4b0d44Sdan        && regAcc
6311ed09dddeSdan       ){
6312fa4b0d44Sdan         /* If regAcc==0, there there exists some min() or max() function
6313fa4b0d44Sdan         ** without a FILTER clause that will ensure the magnet registers
6314fa4b0d44Sdan         ** are populated. */
6315ed09dddeSdan         if( regHit==0 ) regHit = ++pParse->nMem;
6316fa4b0d44Sdan         /* If this is the first row of the group (regAcc contains 0), clear the
6317ed09dddeSdan         ** "magnet" register regHit so that the accumulator registers
6318af9b58b3Sdan         ** are populated if the FILTER clause jumps over the the
6319af9b58b3Sdan         ** invocation of min() or max() altogether. Or, if this is not
6320fa4b0d44Sdan         ** the first row (regAcc contains 1), set the magnet register so that
6321fa4b0d44Sdan         ** the accumulators are not populated unless the min()/max() is invoked
6322fa4b0d44Sdan         ** and indicates that they should be.  */
6323ed09dddeSdan         sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit);
6324ed09dddeSdan       }
63256ba7ab0dSdan       addrNext = sqlite3VdbeMakeLabel(pParse);
63266ba7ab0dSdan       sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL);
63276ba7ab0dSdan     }
632813449892Sdrh     if( pList ){
632913449892Sdrh       nArg = pList->nExpr;
6330892d3179Sdrh       regAgg = sqlite3GetTempRange(pParse, nArg);
63315579d59fSdrh       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
633213449892Sdrh     }else{
633313449892Sdrh       nArg = 0;
633498757157Sdrh       regAgg = 0;
633513449892Sdrh     }
63364fcb30b7Sdan     if( pF->iDistinct>=0 && pList ){
63376ba7ab0dSdan       if( addrNext==0 ){
6338ec4ccdbcSdrh         addrNext = sqlite3VdbeMakeLabel(pParse);
63396ba7ab0dSdan       }
63405383db71Sdan       pF->iDistinct = codeDistinct(pParse, eDistinctType,
63415383db71Sdan           pF->iDistinct, addrNext, pList, regAgg);
6342c99130fdSdrh     }
6343d36e1041Sdrh     if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
634413449892Sdrh       CollSeq *pColl = 0;
634513449892Sdrh       struct ExprList_item *pItem;
634613449892Sdrh       int j;
6347e82f5d04Sdrh       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
634843617e9aSdrh       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
634913449892Sdrh         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
635013449892Sdrh       }
635113449892Sdrh       if( !pColl ){
635213449892Sdrh         pColl = pParse->db->pDfltColl;
635313449892Sdrh       }
63547a95789cSdrh       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
63557a95789cSdrh       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
635613449892Sdrh     }
63578f26da6cSdrh     sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem);
63582700acaaSdrh     sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
6359ea678832Sdrh     sqlite3VdbeChangeP5(v, (u8)nArg);
6360f49f3523Sdrh     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
6361c99130fdSdrh     if( addrNext ){
6362c99130fdSdrh       sqlite3VdbeResolveLabel(v, addrNext);
6363c99130fdSdrh     }
636413449892Sdrh   }
6365280c894bSdan   if( regHit==0 && pAggInfo->nAccumulator ){
6366280c894bSdan     regHit = regAcc;
6367280c894bSdan   }
63687a95789cSdrh   if( regHit ){
6369688852abSdrh     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
63707a95789cSdrh   }
637113449892Sdrh   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
637281185a51Sdrh     sqlite3ExprCode(pParse, pC->pCExpr, pC->iMem);
637313449892Sdrh   }
6374ed09dddeSdan 
637513449892Sdrh   pAggInfo->directMode = 0;
63767a95789cSdrh   if( addrHitTest ){
6377dc4f6fc0Sdrh     sqlite3VdbeJumpHereOrPopInst(v, addrHitTest);
63787a95789cSdrh   }
637913449892Sdrh }
638013449892Sdrh 
6381b3bce662Sdanielk1977 /*
6382ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple
6383ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab").
6384ef7075deSdan */
6385ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN
explainSimpleCount(Parse * pParse,Table * pTab,Index * pIdx)6386ef7075deSdan static void explainSimpleCount(
6387ef7075deSdan   Parse *pParse,                  /* Parse context */
6388ef7075deSdan   Table *pTab,                    /* Table being queried */
6389ef7075deSdan   Index *pIdx                     /* Index used to optimize scan, or NULL */
6390ef7075deSdan ){
6391ef7075deSdan   if( pParse->explain==2 ){
639248dd1d8eSdrh     int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
63938210233cSdrh     sqlite3VdbeExplain(pParse, 0, "SCAN %s%s%s",
6394ef7075deSdan         pTab->zName,
6395e96f2df3Sdan         bCover ? " USING COVERING INDEX " : "",
6396e96f2df3Sdan         bCover ? pIdx->zName : ""
6397ef7075deSdan     );
6398ef7075deSdan   }
6399ef7075deSdan }
6400ef7075deSdan #else
6401ef7075deSdan # define explainSimpleCount(a,b,c)
6402ef7075deSdan #endif
6403ef7075deSdan 
6404ef7075deSdan /*
6405ab31a845Sdan ** sqlite3WalkExpr() callback used by havingToWhere().
6406ab31a845Sdan **
6407ab31a845Sdan ** If the node passed to the callback is a TK_AND node, return
6408ab31a845Sdan ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
6409ab31a845Sdan **
6410ab31a845Sdan ** Otherwise, return WRC_Prune. In this case, also check if the
6411ab31a845Sdan ** sub-expression matches the criteria for being moved to the WHERE
6412ab31a845Sdan ** clause. If so, add it to the WHERE clause and replace the sub-expression
6413ab31a845Sdan ** within the HAVING expression with a constant "1".
6414ab31a845Sdan */
havingToWhereExprCb(Walker * pWalker,Expr * pExpr)6415ab31a845Sdan static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
6416ab31a845Sdan   if( pExpr->op!=TK_AND ){
6417cd0abc24Sdrh     Select *pS = pWalker->u.pSelect;
6418d59f9835Sdan     /* This routine is called before the HAVING clause of the current
6419d59f9835Sdan     ** SELECT is analyzed for aggregates. So if pExpr->pAggInfo is set
6420d59f9835Sdan     ** here, it indicates that the expression is a correlated reference to a
6421d59f9835Sdan     ** column from an outer aggregate query, or an aggregate function that
6422d59f9835Sdan     ** belongs to an outer query. Do not move the expression to the WHERE
6423d59f9835Sdan     ** clause in this obscure case, as doing so may corrupt the outer Select
6424d59f9835Sdan     ** statements AggInfo structure.  */
6425f39168e4Sdan     if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy)
6426f39168e4Sdan      && ExprAlwaysFalse(pExpr)==0
6427d59f9835Sdan      && pExpr->pAggInfo==0
6428f39168e4Sdan     ){
6429ab31a845Sdan       sqlite3 *db = pWalker->pParse->db;
64305776ee5cSdrh       Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1");
6431ab31a845Sdan       if( pNew ){
6432cd0abc24Sdrh         Expr *pWhere = pS->pWhere;
6433ab31a845Sdan         SWAP(Expr, *pNew, *pExpr);
6434d5c851c1Sdrh         pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew);
6435cd0abc24Sdrh         pS->pWhere = pNew;
6436cd0abc24Sdrh         pWalker->eCode = 1;
6437ab31a845Sdan       }
6438ab31a845Sdan     }
6439ab31a845Sdan     return WRC_Prune;
6440ab31a845Sdan   }
6441ab31a845Sdan   return WRC_Continue;
6442ab31a845Sdan }
6443ab31a845Sdan 
6444ab31a845Sdan /*
6445ab31a845Sdan ** Transfer eligible terms from the HAVING clause of a query, which is
6446ab31a845Sdan ** processed after grouping, to the WHERE clause, which is processed before
6447ab31a845Sdan ** grouping. For example, the query:
6448ab31a845Sdan **
6449ab31a845Sdan **   SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
6450ab31a845Sdan **
6451ab31a845Sdan ** can be rewritten as:
6452ab31a845Sdan **
6453ab31a845Sdan **   SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
6454ab31a845Sdan **
6455ab31a845Sdan ** A term of the HAVING expression is eligible for transfer if it consists
6456ab31a845Sdan ** entirely of constants and expressions that are also GROUP BY terms that
6457ab31a845Sdan ** use the "BINARY" collation sequence.
6458ab31a845Sdan */
havingToWhere(Parse * pParse,Select * p)6459cd0abc24Sdrh static void havingToWhere(Parse *pParse, Select *p){
6460ab31a845Sdan   Walker sWalker;
6461ab31a845Sdan   memset(&sWalker, 0, sizeof(sWalker));
6462ab31a845Sdan   sWalker.pParse = pParse;
6463ab31a845Sdan   sWalker.xExprCallback = havingToWhereExprCb;
6464cd0abc24Sdrh   sWalker.u.pSelect = p;
6465cd0abc24Sdrh   sqlite3WalkExpr(&sWalker, p->pHaving);
64665e431beaSdrh #if TREETRACE_ENABLED
64675e431beaSdrh   if( sWalker.eCode && (sqlite3TreeTrace & 0x100)!=0 ){
6468cd0abc24Sdrh     SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
6469cd0abc24Sdrh     sqlite3TreeViewSelect(0, p, 0);
6470cd0abc24Sdrh   }
6471cd0abc24Sdrh #endif
6472ab31a845Sdan }
6473ab31a845Sdan 
6474ab31a845Sdan /*
6475e08e8d6bSdrh ** Check to see if the pThis entry of pTabList is a self-join of a prior view.
64763b88065dSdrh ** If it is, then return the SrcItem for the prior view.  If it is not,
6477e08e8d6bSdrh ** then return 0.
6478e08e8d6bSdrh */
isSelfJoinView(SrcList * pTabList,SrcItem * pThis)64797601294aSdrh static SrcItem *isSelfJoinView(
6480e08e8d6bSdrh   SrcList *pTabList,           /* Search for self-joins in this FROM clause */
64817601294aSdrh   SrcItem *pThis               /* Search for prior reference to this subquery */
6482e08e8d6bSdrh ){
64837601294aSdrh   SrcItem *pItem;
64848794c68aSdrh   assert( pThis->pSelect!=0 );
64858794c68aSdrh   if( pThis->pSelect->selFlags & SF_PushDown ) return 0;
6486e08e8d6bSdrh   for(pItem = pTabList->a; pItem<pThis; pItem++){
6487bdefaf08Sdrh     Select *pS1;
6488e08e8d6bSdrh     if( pItem->pSelect==0 ) continue;
6489e08e8d6bSdrh     if( pItem->fg.viaCoroutine ) continue;
649033543c23Sdrh     if( pItem->zName==0 ) continue;
649130ad79aeSdrh     assert( pItem->pTab!=0 );
649230ad79aeSdrh     assert( pThis->pTab!=0 );
649330ad79aeSdrh     if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue;
6494ed712980Sdrh     if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
6495bdefaf08Sdrh     pS1 = pItem->pSelect;
649630ad79aeSdrh     if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){
6497bdefaf08Sdrh       /* The query flattener left two different CTE tables with identical
6498bdefaf08Sdrh       ** names in the same FROM clause. */
6499bdefaf08Sdrh       continue;
6500bdefaf08Sdrh     }
65018794c68aSdrh     if( pItem->pSelect->selFlags & SF_PushDown ){
6502ed712980Sdrh       /* The view was modified by some other optimization such as
6503ed712980Sdrh       ** pushDownWhereTerms() */
6504ed712980Sdrh       continue;
6505ed712980Sdrh     }
6506ed712980Sdrh     return pItem;
6507e08e8d6bSdrh   }
6508e08e8d6bSdrh   return 0;
6509e08e8d6bSdrh }
6510e08e8d6bSdrh 
6511c54246ffSdrh /*
6512c54246ffSdrh ** Deallocate a single AggInfo object
6513c54246ffSdrh */
agginfoFree(sqlite3 * db,AggInfo * p)6514c54246ffSdrh static void agginfoFree(sqlite3 *db, AggInfo *p){
6515c54246ffSdrh   sqlite3DbFree(db, p->aCol);
6516c54246ffSdrh   sqlite3DbFree(db, p->aFunc);
6517c54246ffSdrh   sqlite3DbFreeNN(db, p);
6518c54246ffSdrh }
6519c54246ffSdrh 
6520269ba804Sdrh #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
6521269ba804Sdrh /*
6522269ba804Sdrh ** Attempt to transform a query of the form
6523269ba804Sdrh **
6524269ba804Sdrh **    SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
6525269ba804Sdrh **
6526269ba804Sdrh ** Into this:
6527269ba804Sdrh **
6528269ba804Sdrh **    SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
6529269ba804Sdrh **
6530269ba804Sdrh ** The transformation only works if all of the following are true:
6531269ba804Sdrh **
6532269ba804Sdrh **   *  The subquery is a UNION ALL of two or more terms
6533a4b5fb55Sdan **   *  The subquery does not have a LIMIT clause
6534269ba804Sdrh **   *  There is no WHERE or GROUP BY or HAVING clauses on the subqueries
653573c53b39Sdrh **   *  The outer query is a simple count(*) with no WHERE clause or other
653673c53b39Sdrh **      extraneous syntax.
6537269ba804Sdrh **
6538269ba804Sdrh ** Return TRUE if the optimization is undertaken.
6539269ba804Sdrh */
countOfViewOptimization(Parse * pParse,Select * p)6540269ba804Sdrh static int countOfViewOptimization(Parse *pParse, Select *p){
6541269ba804Sdrh   Select *pSub, *pPrior;
6542269ba804Sdrh   Expr *pExpr;
6543269ba804Sdrh   Expr *pCount;
6544269ba804Sdrh   sqlite3 *db;
65453d240d21Sdrh   if( (p->selFlags & SF_Aggregate)==0 ) return 0;   /* This is an aggregate */
6546269ba804Sdrh   if( p->pEList->nExpr!=1 ) return 0;               /* Single result column */
654773c53b39Sdrh   if( p->pWhere ) return 0;
654873c53b39Sdrh   if( p->pGroupBy ) return 0;
6549269ba804Sdrh   pExpr = p->pEList->a[0].pExpr;
6550269ba804Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;        /* Result is an aggregate */
6551a4eeccdfSdrh   assert( ExprUseUToken(pExpr) );
65523d240d21Sdrh   if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0;  /* Is count() */
6553a4eeccdfSdrh   assert( ExprUseXList(pExpr) );
6554269ba804Sdrh   if( pExpr->x.pList!=0 ) return 0;                 /* Must be count(*) */
65553d240d21Sdrh   if( p->pSrc->nSrc!=1 ) return 0;                  /* One table in FROM  */
6556269ba804Sdrh   pSub = p->pSrc->a[0].pSelect;
6557269ba804Sdrh   if( pSub==0 ) return 0;                           /* The FROM is a subquery */
65583d240d21Sdrh   if( pSub->pPrior==0 ) return 0;                   /* Must be a compound ry */
6559269ba804Sdrh   do{
6560269ba804Sdrh     if( pSub->op!=TK_ALL && pSub->pPrior ) return 0;  /* Must be UNION ALL */
6561269ba804Sdrh     if( pSub->pWhere ) return 0;                      /* No WHERE clause */
6562a4b5fb55Sdan     if( pSub->pLimit ) return 0;                      /* No LIMIT clause */
6563269ba804Sdrh     if( pSub->selFlags & SF_Aggregate ) return 0;     /* Not an aggregate */
65643d240d21Sdrh     pSub = pSub->pPrior;                              /* Repeat over compound */
6565269ba804Sdrh   }while( pSub );
6566269ba804Sdrh 
65673d240d21Sdrh   /* If we reach this point then it is OK to perform the transformation */
6568269ba804Sdrh 
6569269ba804Sdrh   db = pParse->db;
6570269ba804Sdrh   pCount = pExpr;
6571269ba804Sdrh   pExpr = 0;
6572269ba804Sdrh   pSub = p->pSrc->a[0].pSelect;
6573269ba804Sdrh   p->pSrc->a[0].pSelect = 0;
6574269ba804Sdrh   sqlite3SrcListDelete(db, p->pSrc);
6575269ba804Sdrh   p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
6576269ba804Sdrh   while( pSub ){
6577269ba804Sdrh     Expr *pTerm;
6578269ba804Sdrh     pPrior = pSub->pPrior;
6579269ba804Sdrh     pSub->pPrior = 0;
6580269ba804Sdrh     pSub->pNext = 0;
6581269ba804Sdrh     pSub->selFlags |= SF_Aggregate;
6582269ba804Sdrh     pSub->selFlags &= ~SF_Compound;
6583269ba804Sdrh     pSub->nSelectRow = 0;
6584269ba804Sdrh     sqlite3ExprListDelete(db, pSub->pEList);
6585269ba804Sdrh     pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
6586269ba804Sdrh     pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
6587269ba804Sdrh     pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
6588269ba804Sdrh     sqlite3PExprAddSelect(pParse, pTerm, pSub);
6589269ba804Sdrh     if( pExpr==0 ){
6590269ba804Sdrh       pExpr = pTerm;
6591269ba804Sdrh     }else{
6592269ba804Sdrh       pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
6593269ba804Sdrh     }
6594269ba804Sdrh     pSub = pPrior;
6595269ba804Sdrh   }
6596269ba804Sdrh   p->pEList->a[0].pExpr = pExpr;
6597269ba804Sdrh   p->selFlags &= ~SF_Aggregate;
6598269ba804Sdrh 
65995e431beaSdrh #if TREETRACE_ENABLED
66005e431beaSdrh   if( sqlite3TreeTrace & 0x400 ){
6601269ba804Sdrh     SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
6602269ba804Sdrh     sqlite3TreeViewSelect(0, p, 0);
6603269ba804Sdrh   }
6604269ba804Sdrh #endif
6605269ba804Sdrh   return 1;
6606269ba804Sdrh }
6607269ba804Sdrh #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
6608269ba804Sdrh 
6609e08e8d6bSdrh /*
6610fb98dac0Sdrh ** If any term of pSrc, or any SF_NestedFrom sub-query, is not the same
6611fb98dac0Sdrh ** as pSrcItem but has the same alias as p0, then return true.
6612fb98dac0Sdrh ** Otherwise return false.
6613fb98dac0Sdrh */
sameSrcAlias(SrcItem * p0,SrcList * pSrc)6614fb98dac0Sdrh static int sameSrcAlias(SrcItem *p0, SrcList *pSrc){
6615fb98dac0Sdrh   int i;
6616fb98dac0Sdrh   for(i=0; i<pSrc->nSrc; i++){
6617fb98dac0Sdrh     SrcItem *p1 = &pSrc->a[i];
6618fb98dac0Sdrh     if( p1==p0 ) continue;
6619fb98dac0Sdrh     if( p0->pTab==p1->pTab && 0==sqlite3_stricmp(p0->zAlias, p1->zAlias) ){
6620fb98dac0Sdrh       return 1;
6621fb98dac0Sdrh     }
6622fb98dac0Sdrh     if( p1->pSelect
6623fb98dac0Sdrh      && (p1->pSelect->selFlags & SF_NestedFrom)!=0
6624fb98dac0Sdrh      && sameSrcAlias(p0, p1->pSelect->pSrc)
6625fb98dac0Sdrh     ){
6626fb98dac0Sdrh       return 1;
6627fb98dac0Sdrh     }
6628fb98dac0Sdrh   }
6629fb98dac0Sdrh   return 0;
6630fb98dac0Sdrh }
6631fb98dac0Sdrh 
6632fb98dac0Sdrh /*
66337d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument.
66349bb61fe7Sdrh **
6635340309fdSdrh ** The results are returned according to the SelectDest structure.
6636340309fdSdrh ** See comments in sqliteInt.h for further information.
6637e78e8284Sdrh **
66389bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
66399bb61fe7Sdrh ** encountered, then an appropriate error message is left in
66409bb61fe7Sdrh ** pParse->zErrMsg.
66419bb61fe7Sdrh **
66429bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
66439bb61fe7Sdrh ** calling function needs to do that.
66449bb61fe7Sdrh */
sqlite3Select(Parse * pParse,Select * p,SelectDest * pDest)66454adee20fSdanielk1977 int sqlite3Select(
6646cce7d176Sdrh   Parse *pParse,         /* The parser context */
66479bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
66487d10d5a6Sdrh   SelectDest *pDest      /* What to do with the query results */
6649cce7d176Sdrh ){
665013449892Sdrh   int i, j;              /* Loop counters */
665113449892Sdrh   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
665213449892Sdrh   Vdbe *v;               /* The virtual machine under construction */
6653b3bce662Sdanielk1977   int isAgg;             /* True for select lists like "count(*)" */
6654c29cbb0bSmistachkin   ExprList *pEList = 0;  /* List of columns to extract. */
6655ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
66569bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
66572282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
66582282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
6659bf790973Sdrh   AggInfo *pAggInfo = 0; /* Aggregate information */
66601d83f052Sdrh   int rc = 1;            /* Value to return from this function */
6661e8e4af76Sdrh   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
6662079a3072Sdrh   SortCtx sSort;         /* Info on how to code the ORDER BY clause */
6663ec7429aeSdrh   int iEnd;              /* Address of the end of the query */
666417435752Sdrh   sqlite3 *db;           /* The database connection */
666547d9f839Sdrh   ExprList *pMinMaxOrderBy = 0;  /* Added ORDER BY for min/max queries */
666647d9f839Sdrh   u8 minMaxFlag;                 /* Flag for min/max queries */
66679bb61fe7Sdrh 
666817435752Sdrh   db = pParse->db;
66690c7d3d39Sdrh   assert( pParse==db->pParse );
6670e2ca99c9Sdrh   v = sqlite3GetVdbe(pParse);
66710c7d3d39Sdrh   if( p==0 || pParse->nErr ){
66726f7adc8aSdrh     return 1;
66736f7adc8aSdrh   }
66740c7d3d39Sdrh   assert( db->mallocFailed==0 );
66754adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
66765e431beaSdrh #if TREETRACE_ENABLED
6677e2ca99c9Sdrh   SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain));
6678c2d0df95Sdrh   if( sqlite3TreeTrace & 0x10100 ){
6679c2d0df95Sdrh     if( (sqlite3TreeTrace & 0x10001)==0x10000 ){
6680c2d0df95Sdrh       sqlite3TreeViewLine(0, "In sqlite3Select() at %s:%d",
6681c2d0df95Sdrh                            __FILE__, __LINE__);
6682c2d0df95Sdrh     }
6683c2d0df95Sdrh     sqlite3ShowSelect(p);
6684c90713d3Sdrh   }
6685eb9b884cSdrh #endif
6686daffd0e5Sdrh 
66878e1ee88cSdrh   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
66888e1ee88cSdrh   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
66899afccba2Sdan   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
66909afccba2Sdan   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
6691f1ea4255Sdrh   if( IgnorableDistinct(pDest) ){
66929ed1dfa8Sdanielk1977     assert(pDest->eDest==SRT_Exists     || pDest->eDest==SRT_Union ||
66939afccba2Sdan            pDest->eDest==SRT_Except     || pDest->eDest==SRT_Discard ||
6694f1ea4255Sdrh            pDest->eDest==SRT_DistQueue  || pDest->eDest==SRT_DistFifo );
6695f1ea4255Sdrh     /* All of these destinations are also able to ignore the ORDER BY clause */
6696fad1ad05Sdrh     if( p->pOrderBy ){
66975e431beaSdrh #if TREETRACE_ENABLED
6698fad1ad05Sdrh       SELECTTRACE(1,pParse,p, ("dropping superfluous ORDER BY:\n"));
66995e431beaSdrh       if( sqlite3TreeTrace & 0x100 ){
6700fad1ad05Sdrh         sqlite3TreeViewExprList(0, p->pOrderBy, 0, "ORDERBY");
6701fad1ad05Sdrh       }
6702fad1ad05Sdrh #endif
6703fad1ad05Sdrh       sqlite3ParserAddCleanup(pParse,
6704fad1ad05Sdrh         (void(*)(sqlite3*,void*))sqlite3ExprListDelete,
6705fad1ad05Sdrh         p->pOrderBy);
67066d0053cfSdrh       testcase( pParse->earlyCleanup );
6707ccfcbceaSdrh       p->pOrderBy = 0;
6708fad1ad05Sdrh     }
67097d10d5a6Sdrh     p->selFlags &= ~SF_Distinct;
6710b7cbf5c1Sdrh     p->selFlags |= SF_NoopOrderBy;
67119a99334dSdrh   }
67127d10d5a6Sdrh   sqlite3SelectPrep(pParse, p, 0);
67130c7d3d39Sdrh   if( pParse->nErr ){
67149a99334dSdrh     goto select_end;
67159a99334dSdrh   }
67160c7d3d39Sdrh   assert( db->mallocFailed==0 );
6717adc57f68Sdrh   assert( p->pEList!=0 );
67185e431beaSdrh #if TREETRACE_ENABLED
67195e431beaSdrh   if( sqlite3TreeTrace & 0x104 ){
6720e2243d26Sdrh     SELECTTRACE(0x104,pParse,p, ("after name resolution:\n"));
672117645f5eSdrh     sqlite3TreeViewSelect(0, p, 0);
672217645f5eSdrh   }
672317645f5eSdrh #endif
6724cce7d176Sdrh 
67255daf69e5Sdan   /* If the SF_UFSrcCheck flag is set, then this function is being called
672607ca7d61Sdan   ** as part of populating the temp table for an UPDATE...FROM statement.
672707ca7d61Sdan   ** In this case, it is an error if the target object (pSrc->a[0]) name
67285daf69e5Sdan   ** or alias is duplicated within FROM clause (pSrc->a[1..n]).
67295daf69e5Sdan   **
67305daf69e5Sdan   ** Postgres disallows this case too. The reason is that some other
67315daf69e5Sdan   ** systems handle this case differently, and not all the same way,
67325daf69e5Sdan   ** which is just confusing. To avoid this, we follow PG's lead and
67335daf69e5Sdan   ** disallow it altogether.  */
67345daf69e5Sdan   if( p->selFlags & SF_UFSrcCheck ){
67357601294aSdrh     SrcItem *p0 = &p->pSrc->a[0];
6736fb98dac0Sdrh     if( sameSrcAlias(p0, p->pSrc) ){
673707ca7d61Sdan       sqlite3ErrorMsg(pParse,
673807ca7d61Sdan           "target object/alias may not appear in FROM clause: %s",
673907ca7d61Sdan           p0->zAlias ? p0->zAlias : p0->pTab->zName
674007ca7d61Sdan       );
674107ca7d61Sdan       goto select_end;
674207ca7d61Sdan     }
67435daf69e5Sdan 
67445daf69e5Sdan     /* Clear the SF_UFSrcCheck flag. The check has already been performed,
67455daf69e5Sdan     ** and leaving this flag set can cause errors if a compound sub-query
67465daf69e5Sdan     ** in p->pSrc is flattened into this query and this function called
67475daf69e5Sdan     ** again as part of compound SELECT processing.  */
67485daf69e5Sdan     p->selFlags &= ~SF_UFSrcCheck;
674907ca7d61Sdan   }
675007ca7d61Sdan 
6751f35f2f92Sdrh   if( pDest->eDest==SRT_Output ){
67529088186bSdrh     sqlite3GenerateColumnNames(pParse, p);
6753f35f2f92Sdrh   }
6754f35f2f92Sdrh 
675567a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
675644918c74Sdan   if( sqlite3WindowRewrite(pParse, p) ){
67570c7d3d39Sdrh     assert( pParse->nErr );
675886fb6e17Sdan     goto select_end;
675986fb6e17Sdan   }
67605e431beaSdrh #if TREETRACE_ENABLED
67615e431beaSdrh   if( p->pWin && (sqlite3TreeTrace & 0x108)!=0 ){
6762dfa552f4Sdan     SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n"));
6763dfa552f4Sdan     sqlite3TreeViewSelect(0, p, 0);
6764dfa552f4Sdan   }
6765dfa552f4Sdan #endif
676667a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */
676786fb6e17Sdan   pTabList = p->pSrc;
67687392569fSdan   isAgg = (p->selFlags & SF_Aggregate)!=0;
6769f02cdd37Sdan   memset(&sSort, 0, sizeof(sSort));
6770f02cdd37Sdan   sSort.pOrderBy = p->pOrderBy;
677186fb6e17Sdan 
67729216de8aSdrh   /* Try to do various optimizations (flattening subqueries, and strength
67732589787cSdrh   ** reduction of join operators) in the FROM clause up into the main query
6774d820cb1bSdrh   */
677551522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
6776f23329a2Sdanielk1977   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
67777601294aSdrh     SrcItem *pItem = &pTabList->a[i];
6778daf79acbSdanielk1977     Select *pSub = pItem->pSelect;
67792679f14fSdrh     Table *pTab = pItem->pTab;
67802589787cSdrh 
6781b5aaee5eSdrh     /* The expander should have already created transient Table objects
6782b5aaee5eSdrh     ** even for FROM clause elements such as subqueries that do not correspond
6783b5aaee5eSdrh     ** to a real table */
6784b5aaee5eSdrh     assert( pTab!=0 );
6785b5aaee5eSdrh 
67862589787cSdrh     /* Convert LEFT JOIN into JOIN if there are terms of the right table
67872589787cSdrh     ** of the LEFT JOIN used in the WHERE clause.
67882589787cSdrh     */
6789ff02ac7fSdrh     if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))==JT_LEFT
67902589787cSdrh      && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor)
67912589787cSdrh      && OptimizationEnabled(db, SQLITE_SimplifyJoin)
67922589787cSdrh     ){
67932589787cSdrh       SELECTTRACE(0x100,pParse,p,
67942589787cSdrh                 ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
6795efce69deSdrh       pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
6796d7480403Sdrh       assert( pItem->iCursor>=0 );
679792d1afbaSdrh       unsetJoinExpr(p->pWhere, pItem->iCursor,
679892d1afbaSdrh                     pTabList->a[0].fg.jointype & JT_LTORJ);
67992589787cSdrh     }
68002589787cSdrh 
68012589787cSdrh     /* No futher action if this term of the FROM clause is no a subquery */
68024490c40bSdrh     if( pSub==0 ) continue;
68032679f14fSdrh 
68042679f14fSdrh     /* Catch mismatch in the declared columns of a view and the number of
68052679f14fSdrh     ** columns in the SELECT on the RHS */
68062679f14fSdrh     if( pTab->nCol!=pSub->pEList->nExpr ){
68072679f14fSdrh       sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
68082679f14fSdrh                       pTab->nCol, pTab->zName, pSub->pEList->nExpr);
68092679f14fSdrh       goto select_end;
68102679f14fSdrh     }
68112679f14fSdrh 
681225c221ebSdrh     /* Do not try to flatten an aggregate subquery.
681325c221ebSdrh     **
681425c221ebSdrh     ** Flattening an aggregate subquery is only possible if the outer query
681525c221ebSdrh     ** is not a join.  But if the outer query is not a join, then the subquery
681625c221ebSdrh     ** will be implemented as a co-routine and there is no advantage to
681725c221ebSdrh     ** flattening in that case.
681825c221ebSdrh     */
681925c221ebSdrh     if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
682025c221ebSdrh     assert( pSub->pGroupBy==0 );
682125c221ebSdrh 
6822bb301231Sdrh     /* If a FROM-clause subquery has an ORDER BY clause that is not
6823bb301231Sdrh     ** really doing anything, then delete it now so that it does not
68240fb78f0cSdrh     ** interfere with query flattening.  See the discussion at
68250fb78f0cSdrh     ** https://sqlite.org/forum/forumpost/2d76f2bcf65d256a
6826bb301231Sdrh     **
6827bb301231Sdrh     ** Beware of these cases where the ORDER BY clause may not be safely
6828bb301231Sdrh     ** omitted:
6829bb301231Sdrh     **
6830bb301231Sdrh     **    (1)   There is also a LIMIT clause
6831bb301231Sdrh     **    (2)   The subquery was added to help with window-function
6832bb301231Sdrh     **          processing
68330fb78f0cSdrh     **    (3)   The subquery is in the FROM clause of an UPDATE
68340fb78f0cSdrh     **    (4)   The outer query uses an aggregate function other than
6835bb301231Sdrh     **          the built-in count(), min(), or max().
68360fb78f0cSdrh     **    (5)   The ORDER BY isn't going to accomplish anything because
68370fb78f0cSdrh     **          one of:
68380fb78f0cSdrh     **            (a)  The outer query has a different ORDER BY clause
68390fb78f0cSdrh     **            (b)  The subquery is part of a join
68400fb78f0cSdrh     **          See forum post 062d576715d277c8
6841bb301231Sdrh     */
6842bb301231Sdrh     if( pSub->pOrderBy!=0
68430fb78f0cSdrh      && (p->pOrderBy!=0 || pTabList->nSrc>1)      /* Condition (5) */
6844bb301231Sdrh      && pSub->pLimit==0                           /* Condition (1) */
6845bb301231Sdrh      && (pSub->selFlags & SF_OrderByReqd)==0      /* Condition (2) */
68460fb78f0cSdrh      && (p->selFlags & SF_OrderByReqd)==0         /* Condition (3) and (4) */
6847bb301231Sdrh      && OptimizationEnabled(db, SQLITE_OmitOrderBy)
6848bb301231Sdrh     ){
6849bb301231Sdrh       SELECTTRACE(0x100,pParse,p,
6850bb301231Sdrh                 ("omit superfluous ORDER BY on %r FROM-clause subquery\n",i+1));
6851e834484dSdrh       sqlite3ParserAddCleanup(pParse,
6852e834484dSdrh          (void(*)(sqlite3*,void*))sqlite3ExprListDelete,
6853e834484dSdrh          pSub->pOrderBy);
6854bb301231Sdrh       pSub->pOrderBy = 0;
6855bb301231Sdrh     }
6856bb301231Sdrh 
6857fca23557Sdrh     /* If the outer query contains a "complex" result set (that is,
6858fca23557Sdrh     ** if the result set of the outer query uses functions or subqueries)
6859fca23557Sdrh     ** and if the subquery contains an ORDER BY clause and if
6860648fe49fSdrh     ** it will be implemented as a co-routine, then do not flatten.  This
6861648fe49fSdrh     ** restriction allows SQL constructs like this:
6862648fe49fSdrh     **
6863648fe49fSdrh     **  SELECT expensive_function(x)
6864648fe49fSdrh     **    FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
6865648fe49fSdrh     **
6866648fe49fSdrh     ** The expensive_function() is only computed on the 10 rows that
6867648fe49fSdrh     ** are output, rather than every row of the table.
6868fca23557Sdrh     **
6869fca23557Sdrh     ** The requirement that the outer query have a complex result set
6870fca23557Sdrh     ** means that flattening does occur on simpler SQL constraints without
6871fca23557Sdrh     ** the expensive_function() like:
6872fca23557Sdrh     **
6873fca23557Sdrh     **  SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
6874648fe49fSdrh     */
687525c221ebSdrh     if( pSub->pOrderBy!=0
6876648fe49fSdrh      && i==0
6877fca23557Sdrh      && (p->selFlags & SF_ComplexResult)!=0
6878648fe49fSdrh      && (pTabList->nSrc==1
6879a76ac88aSdrh          || (pTabList->a[1].fg.jointype&(JT_OUTER|JT_CROSS))!=0)
6880648fe49fSdrh     ){
6881648fe49fSdrh       continue;
6882648fe49fSdrh     }
6883648fe49fSdrh 
688425c221ebSdrh     if( flattenSubquery(pParse, p, i, isAgg) ){
68854acd754cSdrh       if( pParse->nErr ) goto select_end;
68864490c40bSdrh       /* This subquery can be absorbed into its parent. */
68874490c40bSdrh       i = -1;
68884490c40bSdrh     }
68894490c40bSdrh     pTabList = p->pSrc;
68904490c40bSdrh     if( db->mallocFailed ) goto select_end;
68914490c40bSdrh     if( !IgnorableOrderby(pDest) ){
68924490c40bSdrh       sSort.pOrderBy = p->pOrderBy;
68934490c40bSdrh     }
68944490c40bSdrh   }
68954490c40bSdrh #endif
68964490c40bSdrh 
68974490c40bSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
68984490c40bSdrh   /* Handle compound SELECT statements using the separate multiSelect()
68994490c40bSdrh   ** procedure.
69004490c40bSdrh   */
69014490c40bSdrh   if( p->pPrior ){
69024490c40bSdrh     rc = multiSelect(pParse, p, pDest);
69035e431beaSdrh #if TREETRACE_ENABLED
6904f20609d1Sdrh     SELECTTRACE(0x1,pParse,p,("end compound-select processing\n"));
69055e431beaSdrh     if( (sqlite3TreeTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
6906f20609d1Sdrh       sqlite3TreeViewSelect(0, p, 0);
6907f20609d1Sdrh     }
69084490c40bSdrh #endif
6909c631ded5Sdrh     if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
69104490c40bSdrh     return rc;
69114490c40bSdrh   }
69124490c40bSdrh #endif
69134490c40bSdrh 
69147810ab64Sdrh   /* Do the WHERE-clause constant propagation optimization if this is
69157810ab64Sdrh   ** a join.  No need to speed time on this operation for non-join queries
69167810ab64Sdrh   ** as the equivalent optimization will be handled by query planner in
69177810ab64Sdrh   ** sqlite3WhereBegin().
69187810ab64Sdrh   */
6919b775c976Sdrh   if( p->pWhere!=0
6920b775c976Sdrh    && p->pWhere->op==TK_AND
69217810ab64Sdrh    && OptimizationEnabled(db, SQLITE_PropagateConst)
692224e1116eSdrh    && propagateConstants(pParse, p)
692324e1116eSdrh   ){
69245e431beaSdrh #if TREETRACE_ENABLED
69255e431beaSdrh     if( sqlite3TreeTrace & 0x100 ){
692624e1116eSdrh       SELECTTRACE(0x100,pParse,p,("After constant propagation:\n"));
692724e1116eSdrh       sqlite3TreeViewSelect(0, p, 0);
692824e1116eSdrh     }
692924e1116eSdrh #endif
693024e1116eSdrh   }else{
69317810ab64Sdrh     SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n"));
693224e1116eSdrh   }
693324e1116eSdrh 
6934a4b5fb55Sdan #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
6935a4b5fb55Sdan   if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
6936a4b5fb55Sdan    && countOfViewOptimization(pParse, p)
6937a4b5fb55Sdan   ){
6938a4b5fb55Sdan     if( db->mallocFailed ) goto select_end;
6939a4b5fb55Sdan     pEList = p->pEList;
6940a4b5fb55Sdan     pTabList = p->pSrc;
6941a4b5fb55Sdan   }
6942a4b5fb55Sdan #endif
6943a4b5fb55Sdan 
6944701caf1eSdrh   /* For each term in the FROM clause, do two things:
6945701caf1eSdrh   ** (1) Authorized unreferenced tables
6946701caf1eSdrh   ** (2) Generate code for all sub-queries
6947d820cb1bSdrh   */
69484490c40bSdrh   for(i=0; i<pTabList->nSrc; i++){
69497601294aSdrh     SrcItem *pItem = &pTabList->a[i];
6950a79e2a2dSdrh     SrcItem *pPrior;
695113449892Sdrh     SelectDest dest;
6952701caf1eSdrh     Select *pSub;
6953824d21afSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
6954824d21afSdrh     const char *zSavedAuthContext;
6955824d21afSdrh #endif
6956701caf1eSdrh 
69573d240d21Sdrh     /* Issue SQLITE_READ authorizations with a fake column name for any
69583d240d21Sdrh     ** tables that are referenced but from which no values are extracted.
69593d240d21Sdrh     ** Examples of where these kinds of null SQLITE_READ authorizations
69603d240d21Sdrh     ** would occur:
6961701caf1eSdrh     **
69622336c935Sdrh     **     SELECT count(*) FROM t1;   -- SQLITE_READ t1.""
69632336c935Sdrh     **     SELECT t1.* FROM t1, t2;   -- SQLITE_READ t2.""
69642336c935Sdrh     **
69652336c935Sdrh     ** The fake column name is an empty string.  It is possible for a table to
69662336c935Sdrh     ** have a column named by the empty string, in which case there is no way to
69672336c935Sdrh     ** distinguish between an unreferenced table and an actual reference to the
69682336c935Sdrh     ** "" column. The original design was for the fake column name to be a NULL,
69692336c935Sdrh     ** which would be unambiguous.  But legacy authorization callbacks might
69703d240d21Sdrh     ** assume the column name is non-NULL and segfault.  The use of an empty
69713d240d21Sdrh     ** string for the fake column name seems safer.
6972701caf1eSdrh     */
697374c490e0Sdrh     if( pItem->colUsed==0 && pItem->zName!=0 ){
69742336c935Sdrh       sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
6975701caf1eSdrh     }
6976701caf1eSdrh 
6977701caf1eSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
6978701caf1eSdrh     /* Generate code for all sub-queries in the FROM clause
6979701caf1eSdrh     */
6980701caf1eSdrh     pSub = pItem->pSelect;
69815b6a9ed4Sdrh     if( pSub==0 ) continue;
698221172c4cSdrh 
698314c4d428Sdrh     /* The code for a subquery should only be generated once. */
698414c4d428Sdrh     assert( pItem->addrFillSub==0 );
6985daf79acbSdanielk1977 
6986fc976065Sdanielk1977     /* Increment Parse.nHeight by the height of the largest expression
6987f7b5496eSdrh     ** tree referred to by this, the parent select. The child select
6988fc976065Sdanielk1977     ** may contain expression trees of at most
6989fc976065Sdanielk1977     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
6990fc976065Sdanielk1977     ** more conservative than necessary, but much easier than enforcing
6991fc976065Sdanielk1977     ** an exact limit.
6992fc976065Sdanielk1977     */
6993fc976065Sdanielk1977     pParse->nHeight += sqlite3SelectExprHeight(p);
6994daf79acbSdanielk1977 
6995adc57f68Sdrh     /* Make copies of constant WHERE-clause terms in the outer query down
6996adc57f68Sdrh     ** inside the subquery.  This can help the subquery to run more efficiently.
6997adc57f68Sdrh     */
69987fbb101cSdrh     if( OptimizationEnabled(db, SQLITE_PushDown)
6999df67ec08Sdrh      && (pItem->fg.isCte==0
7000df67ec08Sdrh          || (pItem->u2.pCteUse->eM10d!=M10d_Yes && pItem->u2.pCteUse->nUse<2))
7001a9cdb904Sdrh      && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem)
700269b72d5aSdrh     ){
70035e431beaSdrh #if TREETRACE_ENABLED
70045e431beaSdrh       if( sqlite3TreeTrace & 0x100 ){
7005d2a4401cSdrh         SELECTTRACE(0x100,pParse,p,
7006d2a4401cSdrh             ("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
700769b72d5aSdrh         sqlite3TreeViewSelect(0, p, 0);
7008daf79acbSdanielk1977       }
700969b72d5aSdrh #endif
70108794c68aSdrh       assert( pItem->pSelect && (pItem->pSelect->selFlags & SF_PushDown)!=0 );
70112d277bb5Sdrh     }else{
70122d277bb5Sdrh       SELECTTRACE(0x100,pParse,p,("Push-down not possible\n"));
701369b72d5aSdrh     }
7014adc57f68Sdrh 
7015824d21afSdrh     zSavedAuthContext = pParse->zAuthContext;
7016824d21afSdrh     pParse->zAuthContext = pItem->zName;
7017824d21afSdrh 
7018adc57f68Sdrh     /* Generate code to implement the subquery
70190ff47e9eSdrh     **
7020cf5cab01Sdrh     ** The subquery is implemented as a co-routine if all of the following are
70219debb58eSdrh     ** true:
70229debb58eSdrh     **
7023a79e2a2dSdrh     **    (1)  the subquery is guaranteed to be the outer loop (so that
7024a79e2a2dSdrh     **         it does not need to be computed more than once), and
7025745912efSdrh     **    (2)  the subquery is not a CTE that should be materialized
70269debb58eSdrh     **    (3)  the subquery is not part of a left operand for a RIGHT JOIN
7027adc57f68Sdrh     */
70280ff47e9eSdrh     if( i==0
70290ff47e9eSdrh      && (pTabList->nSrc==1
7030a76ac88aSdrh             || (pTabList->a[1].fg.jointype&(JT_OUTER|JT_CROSS))!=0)  /* (1) */
7031745912efSdrh      && (pItem->fg.isCte==0 || pItem->u2.pCteUse->eM10d!=M10d_Yes)   /* (2) */
70329debb58eSdrh      && (pTabList->a[0].fg.jointype & JT_LTORJ)==0                   /* (3) */
7033a5759677Sdrh     ){
703421172c4cSdrh       /* Implement a co-routine that will return a single row of the result
703521172c4cSdrh       ** set on each invocation.
703621172c4cSdrh       */
7037725de29aSdrh       int addrTop = sqlite3VdbeCurrentAddr(v)+1;
7038824d21afSdrh 
703921172c4cSdrh       pItem->regReturn = ++pParse->nMem;
7040725de29aSdrh       sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
7041a979993bSdrh       VdbeComment((v, "%!S", pItem));
704221172c4cSdrh       pItem->addrFillSub = addrTop;
704321172c4cSdrh       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
7044a979993bSdrh       ExplainQueryPlan((pParse, 1, "CO-ROUTINE %!S", pItem));
704521172c4cSdrh       sqlite3Select(pParse, pSub, &dest);
7046c3489bbfSdrh       pItem->pTab->nRowLogEst = pSub->nSelectRow;
70478a48b9c0Sdrh       pItem->fg.viaCoroutine = 1;
70485f612295Sdrh       pItem->regResult = dest.iSdst;
70492fade2f7Sdrh       sqlite3VdbeEndCoroutine(v, pItem->regReturn);
705021172c4cSdrh       sqlite3VdbeJumpHere(v, addrTop-1);
705121172c4cSdrh       sqlite3ClearTempRegCache(pParse);
7052a79e2a2dSdrh     }else if( pItem->fg.isCte && pItem->u2.pCteUse->addrM9e>0 ){
7053a79e2a2dSdrh       /* This is a CTE for which materialization code has already been
7054a79e2a2dSdrh       ** generated.  Invoke the subroutine to compute the materialization,
7055a79e2a2dSdrh       ** the make the pItem->iCursor be a copy of the ephemerial table that
7056a79e2a2dSdrh       ** holds the result of the materialization. */
7057a79e2a2dSdrh       CteUse *pCteUse = pItem->u2.pCteUse;
7058a79e2a2dSdrh       sqlite3VdbeAddOp2(v, OP_Gosub, pCteUse->regRtn, pCteUse->addrM9e);
7059a79e2a2dSdrh       if( pItem->iCursor!=pCteUse->iCur ){
7060a79e2a2dSdrh         sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pCteUse->iCur);
7061834c6881Sdrh         VdbeComment((v, "%!S", pItem));
7062a79e2a2dSdrh       }
7063a79e2a2dSdrh       pSub->nSelectRow = pCteUse->nRowEst;
7064a79e2a2dSdrh     }else if( (pPrior = isSelfJoinView(pTabList, pItem))!=0 ){
7065a79e2a2dSdrh       /* This view has already been materialized by a prior entry in
7066a79e2a2dSdrh       ** this same FROM clause.  Reuse it. */
7067a79e2a2dSdrh       if( pPrior->addrFillSub ){
7068a79e2a2dSdrh         sqlite3VdbeAddOp2(v, OP_Gosub, pPrior->regReturn, pPrior->addrFillSub);
7069a79e2a2dSdrh       }
7070a79e2a2dSdrh       sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
7071a79e2a2dSdrh       pSub->nSelectRow = pPrior->pSelect->nSelectRow;
7072daf79acbSdanielk1977     }else{
707314c4d428Sdrh       /* Materialize the view.  If the view is not correlated, generate a
7074d685dd6bSdrh       ** subroutine to do the materialization so that subsequent uses of
7075d685dd6bSdrh       ** the same view can reuse the materialization. */
70767157e8eaSdrh       int topAddr;
707748f2d3b1Sdrh       int onceAddr = 0;
7078e08e8d6bSdrh 
70795b6a9ed4Sdrh       pItem->regReturn = ++pParse->nMem;
708040822eb2Sdrh       topAddr = sqlite3VdbeAddOp0(v, OP_Goto);
70817157e8eaSdrh       pItem->addrFillSub = topAddr+1;
708240822eb2Sdrh       pItem->fg.isMaterialized = 1;
70838a48b9c0Sdrh       if( pItem->fg.isCorrelated==0 ){
7084ed17167eSdrh         /* If the subquery is not correlated and if we are not inside of
70855b6a9ed4Sdrh         ** a trigger, then we only need to compute the value of the subquery
70865b6a9ed4Sdrh         ** once. */
7087511f9e8dSdrh         onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
7088a979993bSdrh         VdbeComment((v, "materialize %!S", pItem));
7089725de29aSdrh       }else{
7090a979993bSdrh         VdbeNoopComment((v, "materialize %!S", pItem));
70915b6a9ed4Sdrh       }
70921013c932Sdrh       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
7093a979993bSdrh       ExplainQueryPlan((pParse, 1, "MATERIALIZE %!S", pItem));
70945fdb9a35Sdrh       dest.zAffSdst = sqlite3TableAffinityStr(db, pItem->pTab);
70957d10d5a6Sdrh       sqlite3Select(pParse, pSub, &dest);
70965fdb9a35Sdrh       sqlite3DbFree(db, dest.zAffSdst);
70975fdb9a35Sdrh       dest.zAffSdst = 0;
7098c3489bbfSdrh       pItem->pTab->nRowLogEst = pSub->nSelectRow;
709948f2d3b1Sdrh       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
710040822eb2Sdrh       sqlite3VdbeAddOp2(v, OP_Return, pItem->regReturn, topAddr+1);
7101a979993bSdrh       VdbeComment((v, "end %!S", pItem));
710240822eb2Sdrh       sqlite3VdbeJumpHere(v, topAddr);
7103cdc69557Sdrh       sqlite3ClearTempRegCache(pParse);
7104d685dd6bSdrh       if( pItem->fg.isCte && pItem->fg.isCorrelated==0 ){
7105a79e2a2dSdrh         CteUse *pCteUse = pItem->u2.pCteUse;
7106a79e2a2dSdrh         pCteUse->addrM9e = pItem->addrFillSub;
7107a79e2a2dSdrh         pCteUse->regRtn = pItem->regReturn;
7108a79e2a2dSdrh         pCteUse->iCur = pItem->iCursor;
7109a79e2a2dSdrh         pCteUse->nRowEst = pSub->nSelectRow;
7110a79e2a2dSdrh       }
7111daf79acbSdanielk1977     }
7112adc57f68Sdrh     if( db->mallocFailed ) goto select_end;
7113fc976065Sdanielk1977     pParse->nHeight -= sqlite3SelectExprHeight(p);
7114824d21afSdrh     pParse->zAuthContext = zSavedAuthContext;
7115daf79acbSdanielk1977 #endif
7116701caf1eSdrh   }
7117adc57f68Sdrh 
711838b4149cSdrh   /* Various elements of the SELECT copied into local variables for
711938b4149cSdrh   ** convenience */
7120adc57f68Sdrh   pEList = p->pEList;
7121daf79acbSdanielk1977   pWhere = p->pWhere;
7122832508b7Sdrh   pGroupBy = p->pGroupBy;
7123832508b7Sdrh   pHaving = p->pHaving;
7124e8e4af76Sdrh   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
7125832508b7Sdrh 
71265e431beaSdrh #if TREETRACE_ENABLED
71275e431beaSdrh   if( sqlite3TreeTrace & 0x400 ){
7128bc8edba1Sdrh     SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
7129bc8edba1Sdrh     sqlite3TreeViewSelect(0, p, 0);
7130f23329a2Sdanielk1977   }
7131f23329a2Sdanielk1977 #endif
7132f23329a2Sdanielk1977 
713350118cdfSdan   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
713450118cdfSdan   ** if the select-list is the same as the ORDER BY list, then this query
713550118cdfSdan   ** can be rewritten as a GROUP BY. In other words, this:
713650118cdfSdan   **
713750118cdfSdan   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
713850118cdfSdan   **
713950118cdfSdan   ** is transformed to:
714050118cdfSdan   **
7141dea7d70dSdrh   **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
714250118cdfSdan   **
714350118cdfSdan   ** The second form is preferred as a single index (or temp-table) may be
714450118cdfSdan   ** used for both the ORDER BY and DISTINCT processing. As originally
714550118cdfSdan   ** written the query must use a temp-table for at least one of the ORDER
714650118cdfSdan   ** BY and DISTINCT, and an index or separate temp-table for the other.
714750118cdfSdan   */
714850118cdfSdan   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
7149adc57f68Sdrh    && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
7150ef9f719dSdrh #ifndef SQLITE_OMIT_WINDOWFUNC
7151e59c562bSdan    && p->pWin==0
7152ef9f719dSdrh #endif
715350118cdfSdan   ){
715450118cdfSdan     p->selFlags &= ~SF_Distinct;
7155adc57f68Sdrh     pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
71569e10f9abSdan     p->selFlags |= SF_Aggregate;
7157e8e4af76Sdrh     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
7158e8e4af76Sdrh     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
7159e8e4af76Sdrh     ** original setting of the SF_Distinct flag, not the current setting */
7160e8e4af76Sdrh     assert( sDistinct.isTnct );
7161ece092e7Sdan     sDistinct.isTnct = 2;
71627512cb47Sdrh 
71635e431beaSdrh #if TREETRACE_ENABLED
71645e431beaSdrh     if( sqlite3TreeTrace & 0x400 ){
71657512cb47Sdrh       SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
71667512cb47Sdrh       sqlite3TreeViewSelect(0, p, 0);
71677512cb47Sdrh     }
71687512cb47Sdrh #endif
716950118cdfSdan   }
717050118cdfSdan 
7171adc57f68Sdrh   /* If there is an ORDER BY clause, then create an ephemeral index to
7172adc57f68Sdrh   ** do the sorting.  But this sorting ephemeral index might end up
7173adc57f68Sdrh   ** being unused if the data can be extracted in pre-sorted order.
7174adc57f68Sdrh   ** If that is the case, then the OP_OpenEphemeral instruction will be
7175adc57f68Sdrh   ** changed to an OP_Noop once we figure out that the sorting index is
7176adc57f68Sdrh   ** not needed.  The sSort.addrSortIndex variable is used to facilitate
7177adc57f68Sdrh   ** that change.
71787cedc8d4Sdanielk1977   */
7179079a3072Sdrh   if( sSort.pOrderBy ){
71800342b1f5Sdrh     KeyInfo *pKeyInfo;
7181f9eae18bSdan     pKeyInfo = sqlite3KeyInfoFromExprList(
7182f9eae18bSdan         pParse, sSort.pOrderBy, 0, pEList->nExpr);
7183079a3072Sdrh     sSort.iECursor = pParse->nTab++;
7184079a3072Sdrh     sSort.addrSortIndex =
718566a5167bSdrh       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
7186f45f2326Sdrh           sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
7187f45f2326Sdrh           (char*)pKeyInfo, P4_KEYINFO
7188f45f2326Sdrh       );
71899d2985c7Sdrh   }else{
7190079a3072Sdrh     sSort.addrSortIndex = -1;
71917cedc8d4Sdanielk1977   }
71927cedc8d4Sdanielk1977 
71932d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
71942d0794e3Sdrh   */
71956c8c8ce0Sdanielk1977   if( pDest->eDest==SRT_EphemTab ){
71962b596da8Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
719718f8600fSdrh     if( p->selFlags & SF_NestedFrom ){
719818f8600fSdrh       /* Delete or NULL-out result columns that will never be used */
719918f8600fSdrh       int ii;
7200d88fd539Sdrh       for(ii=pEList->nExpr-1; ii>0 && pEList->a[ii].fg.bUsed==0; ii--){
720118f8600fSdrh         sqlite3ExprDelete(db, pEList->a[ii].pExpr);
720218f8600fSdrh         sqlite3DbFree(db, pEList->a[ii].zEName);
720318f8600fSdrh         pEList->nExpr--;
720418f8600fSdrh       }
720518f8600fSdrh       for(ii=0; ii<pEList->nExpr; ii++){
7206d88fd539Sdrh         if( pEList->a[ii].fg.bUsed==0 ) pEList->a[ii].pExpr->op = TK_NULL;
720718f8600fSdrh       }
720818f8600fSdrh     }
72092d0794e3Sdrh   }
72102d0794e3Sdrh 
7211f42bacc2Sdrh   /* Set the limiter.
7212f42bacc2Sdrh   */
7213ec4ccdbcSdrh   iEnd = sqlite3VdbeMakeLabel(pParse);
721469b9383eSdan   if( (p->selFlags & SF_FixedLimit)==0 ){
7215c3489bbfSdrh     p->nSelectRow = 320;  /* 4 billion rows */
721669b9383eSdan   }
72173c8fb6fbSdrh   if( p->pLimit ) computeLimitRegisters(pParse, p, iEnd);
7218079a3072Sdrh   if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
72190ff287fbSdrh     sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
7220079a3072Sdrh     sSort.sortFlags |= SORTFLAG_UseSorter;
7221c6aff30cSdrh   }
7222f42bacc2Sdrh 
7223adc57f68Sdrh   /* Open an ephemeral index to use for the distinct set.
7224cce7d176Sdrh   */
72252ce22453Sdan   if( p->selFlags & SF_Distinct ){
7226e8e4af76Sdrh     sDistinct.tabTnct = pParse->nTab++;
7227e8e4af76Sdrh     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
7228e8e4af76Sdrh                        sDistinct.tabTnct, 0, 0,
7229f9eae18bSdan                        (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
72302ec2fb22Sdrh                        P4_KEYINFO);
7231d4187c71Sdrh     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
7232e8e4af76Sdrh     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
7233832508b7Sdrh   }else{
7234e8e4af76Sdrh     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
7235efb7251dSdrh   }
7236832508b7Sdrh 
723713449892Sdrh   if( !isAgg && pGroupBy==0 ){
7238e8e4af76Sdrh     /* No aggregate functions and no GROUP BY clause */
723967a9b8edSdan     u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)
724067a9b8edSdan                    | (p->selFlags & SF_FixedLimit);
724167a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
7242067b92baSdrh     Window *pWin = p->pWin;      /* Main window object (or NULL) */
7243f9eae18bSdan     if( pWin ){
72444ea562eeSdan       sqlite3WindowCodeInit(pParse, p);
724586fb6e17Sdan     }
724667a9b8edSdan #endif
724767a9b8edSdan     assert( WHERE_USE_LIMIT==SF_FixedLimit );
724867a9b8edSdan 
724986fb6e17Sdan 
725038cc40c2Sdan     /* Begin the database scan. */
7251cfd74700Sdrh     SELECTTRACE(1,pParse,p,("WhereBegin\n"));
7252079a3072Sdrh     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
7253895bab33Sdrh                                p->pEList, p, wctrlFlags, p->nSelectRow);
72541d83f052Sdrh     if( pWInfo==0 ) goto select_end;
72556f32848dSdrh     if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
72566f32848dSdrh       p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
72576f32848dSdrh     }
72586457a353Sdrh     if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
72596f32848dSdrh       sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
72606f32848dSdrh     }
7261079a3072Sdrh     if( sSort.pOrderBy ){
7262079a3072Sdrh       sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
72636ee5a7b4Sdrh       sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);
7264079a3072Sdrh       if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
7265079a3072Sdrh         sSort.pOrderBy = 0;
7266079a3072Sdrh       }
7267079a3072Sdrh     }
726813162ef9Sdrh     SELECTTRACE(1,pParse,p,("WhereBegin returns\n"));
7269cce7d176Sdrh 
7270b9bb7c18Sdrh     /* If sorting index that was created by a prior OP_OpenEphemeral
7271b9bb7c18Sdrh     ** instruction ended up not being needed, then change the OP_OpenEphemeral
72729d2985c7Sdrh     ** into an OP_Noop.
72739d2985c7Sdrh     */
7274079a3072Sdrh     if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
7275079a3072Sdrh       sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
72769d2985c7Sdrh     }
72779d2985c7Sdrh 
72782def2f7eSdrh     assert( p->pEList==pEList );
727967a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
7280f9eae18bSdan     if( pWin ){
7281ec4ccdbcSdrh       int addrGosub = sqlite3VdbeMakeLabel(pParse);
7282ec4ccdbcSdrh       int iCont = sqlite3VdbeMakeLabel(pParse);
7283ec4ccdbcSdrh       int iBreak = sqlite3VdbeMakeLabel(pParse);
7284f9eae18bSdan       int regGosub = ++pParse->nMem;
728586fb6e17Sdan 
7286dacf1de9Sdan       sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);
728786fb6e17Sdan 
7288efa3a3c9Sdan       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
7289f9eae18bSdan       sqlite3VdbeResolveLabel(v, addrGosub);
7290b0225bc5Sdrh       VdbeNoopComment((v, "inner-loop subroutine"));
7291d4cb09e3Sdrh       sSort.labelOBLopt = 0;
7292efa3a3c9Sdan       selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
7293dacf1de9Sdan       sqlite3VdbeResolveLabel(v, iCont);
729486fb6e17Sdan       sqlite3VdbeAddOp1(v, OP_Return, regGosub);
72950b3b0dd1Sdrh       VdbeComment((v, "end inner-loop subroutine"));
7296efa3a3c9Sdan       sqlite3VdbeResolveLabel(v, iBreak);
729767a9b8edSdan     }else
729867a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */
729967a9b8edSdan     {
730086fb6e17Sdan       /* Use the standard inner loop. */
73012def2f7eSdrh       selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
73026f32848dSdrh           sqlite3WhereContinueLabel(pWInfo),
73036f32848dSdrh           sqlite3WhereBreakLabel(pWInfo));
73042282792aSdrh 
7305cce7d176Sdrh       /* End the database scan loop.
7306cce7d176Sdrh       */
730713162ef9Sdrh       SELECTTRACE(1,pParse,p,("WhereEnd\n"));
73084adee20fSdanielk1977       sqlite3WhereEnd(pWInfo);
730986fb6e17Sdan     }
731013449892Sdrh   }else{
7311e8e4af76Sdrh     /* This case when there exist aggregate functions or a GROUP BY clause
7312e8e4af76Sdrh     ** or both */
731313449892Sdrh     NameContext sNC;    /* Name context for processing aggregate information */
731413449892Sdrh     int iAMem;          /* First Mem address for storing current GROUP BY */
731513449892Sdrh     int iBMem;          /* First Mem address for previous GROUP BY */
731613449892Sdrh     int iUseFlag;       /* Mem address holding flag indicating that at least
731713449892Sdrh                         ** one row of the input to the aggregator has been
731813449892Sdrh                         ** processed */
731913449892Sdrh     int iAbortFlag;     /* Mem address which causes query abort if positive */
732013449892Sdrh     int groupBySort;    /* Rows come from source in GROUP BY order */
7321d176611bSdrh     int addrEnd;        /* End of processing for this SELECT */
73221c9d835dSdrh     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
73231c9d835dSdrh     int sortOut = 0;    /* Output register from the sorter */
7324374cd78cSdan     int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
7325d176611bSdrh 
7326d176611bSdrh     /* Remove any and all aliases between the result set and the
7327d176611bSdrh     ** GROUP BY clause.
7328d176611bSdrh     */
7329d176611bSdrh     if( pGroupBy ){
7330dc5ea5c7Sdrh       int k;                        /* Loop counter */
7331d176611bSdrh       struct ExprList_item *pItem;  /* For looping over expression in a list */
7332d176611bSdrh 
7333dc5ea5c7Sdrh       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
7334c2acc4e4Sdrh         pItem->u.x.iAlias = 0;
7335d176611bSdrh       }
7336dc5ea5c7Sdrh       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
7337c2acc4e4Sdrh         pItem->u.x.iAlias = 0;
7338d176611bSdrh       }
7339c3489bbfSdrh       assert( 66==sqlite3LogEst(100) );
7340c3489bbfSdrh       if( p->nSelectRow>66 ) p->nSelectRow = 66;
7341cce7d176Sdrh 
7342374cd78cSdan       /* If there is both a GROUP BY and an ORDER BY clause and they are
7343374cd78cSdan       ** identical, then it may be possible to disable the ORDER BY clause
7344374cd78cSdan       ** on the grounds that the GROUP BY will cause elements to come out
7345adc57f68Sdrh       ** in the correct order. It also may not - the GROUP BY might use a
7346374cd78cSdan       ** database index that causes rows to be grouped together as required
7347374cd78cSdan       ** but not actually sorted. Either way, record the fact that the
7348374cd78cSdan       ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
7349374cd78cSdan       ** variable.  */
73508c9bcb23Sdan       if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){
7351e39f388eSdrh         int ii;
73528c9bcb23Sdan         /* The GROUP BY processing doesn't care whether rows are delivered in
73538c9bcb23Sdan         ** ASC or DESC order - only that each group is returned contiguously.
73548c9bcb23Sdan         ** So set the ASC/DESC flags in the GROUP BY to match those in the
73558c9bcb23Sdan         ** ORDER BY to maximize the chances of rows being delivered in an
73568c9bcb23Sdan         ** order that makes the ORDER BY redundant.  */
7357e39f388eSdrh         for(ii=0; ii<pGroupBy->nExpr; ii++){
7358d88fd539Sdrh           u8 sortFlags;
7359d88fd539Sdrh           sortFlags = sSort.pOrderBy->a[ii].fg.sortFlags & KEYINFO_ORDER_DESC;
7360d88fd539Sdrh           pGroupBy->a[ii].fg.sortFlags = sortFlags;
73618c9bcb23Sdan         }
7362374cd78cSdan         if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
7363374cd78cSdan           orderByGrp = 1;
7364374cd78cSdan         }
73658c9bcb23Sdan       }
73668c9bcb23Sdan     }else{
73678c9bcb23Sdan       assert( 0==sqlite3LogEst(1) );
73688c9bcb23Sdan       p->nSelectRow = 0;
73698c9bcb23Sdan     }
737013449892Sdrh 
7371d176611bSdrh     /* Create a label to jump to when we want to abort the query */
7372ec4ccdbcSdrh     addrEnd = sqlite3VdbeMakeLabel(pParse);
737313449892Sdrh 
737413449892Sdrh     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
737513449892Sdrh     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
737613449892Sdrh     ** SELECT statement.
73772282792aSdrh     */
7378bf790973Sdrh     pAggInfo = sqlite3DbMallocZero(db, sizeof(*pAggInfo) );
7379c54246ffSdrh     if( pAggInfo ){
7380c54246ffSdrh       sqlite3ParserAddCleanup(pParse,
7381c54246ffSdrh           (void(*)(sqlite3*,void*))agginfoFree, pAggInfo);
73826d0053cfSdrh       testcase( pParse->earlyCleanup );
7383c54246ffSdrh     }
7384c54246ffSdrh     if( db->mallocFailed ){
7385bf790973Sdrh       goto select_end;
7386bf790973Sdrh     }
7387e26d428aSdrh     pAggInfo->selId = p->selId;
738813449892Sdrh     memset(&sNC, 0, sizeof(sNC));
738913449892Sdrh     sNC.pParse = pParse;
739013449892Sdrh     sNC.pSrcList = pTabList;
7391bf790973Sdrh     sNC.uNC.pAggInfo = pAggInfo;
739225c3b8caSdrh     VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
7393bf790973Sdrh     pAggInfo->mnReg = pParse->nMem+1;
7394bf790973Sdrh     pAggInfo->nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
7395bf790973Sdrh     pAggInfo->pGroupBy = pGroupBy;
7396d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pEList);
7397079a3072Sdrh     sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
7398d2b3e23bSdrh     if( pHaving ){
7399ab31a845Sdan       if( pGroupBy ){
7400ab31a845Sdan         assert( pWhere==p->pWhere );
7401cd0abc24Sdrh         assert( pHaving==p->pHaving );
7402cd0abc24Sdrh         assert( pGroupBy==p->pGroupBy );
7403cd0abc24Sdrh         havingToWhere(pParse, p);
7404ab31a845Sdan         pWhere = p->pWhere;
7405ab31a845Sdan       }
7406d2b3e23bSdrh       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
740713449892Sdrh     }
7408bf790973Sdrh     pAggInfo->nAccumulator = pAggInfo->nColumn;
7409bf790973Sdrh     if( p->pGroupBy==0 && p->pHaving==0 && pAggInfo->nFunc==1 ){
741081185a51Sdrh       minMaxFlag = minMaxQuery(db, pAggInfo->aFunc[0].pFExpr, &pMinMaxOrderBy);
741147d9f839Sdrh     }else{
741247d9f839Sdrh       minMaxFlag = WHERE_ORDERBY_NORMAL;
741347d9f839Sdrh     }
7414bf790973Sdrh     for(i=0; i<pAggInfo->nFunc; i++){
741581185a51Sdrh       Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
7416a4eeccdfSdrh       assert( ExprUseXList(pExpr) );
74173a8c4be7Sdrh       sNC.ncFlags |= NC_InAggFunc;
74186ba7ab0dSdan       sqlite3ExprAnalyzeAggList(&sNC, pExpr->x.pList);
74196ba7ab0dSdan #ifndef SQLITE_OMIT_WINDOWFUNC
74204f9adee2Sdan       assert( !IsWindowFunc(pExpr) );
74214f9adee2Sdan       if( ExprHasProperty(pExpr, EP_WinFunc) ){
74224f9adee2Sdan         sqlite3ExprAnalyzeAggregates(&sNC, pExpr->y.pWin->pFilter);
7423b28c4e56Sdan       }
74246ba7ab0dSdan #endif
74253a8c4be7Sdrh       sNC.ncFlags &= ~NC_InAggFunc;
742613449892Sdrh     }
7427bf790973Sdrh     pAggInfo->mxReg = pParse->nMem;
742817435752Sdrh     if( db->mallocFailed ) goto select_end;
74295e431beaSdrh #if TREETRACE_ENABLED
74305e431beaSdrh     if( sqlite3TreeTrace & 0x400 ){
74317ea11066Sdrh       int ii;
7432bf790973Sdrh       SELECTTRACE(0x400,pParse,p,("After aggregate analysis %p:\n", pAggInfo));
74337ea11066Sdrh       sqlite3TreeViewSelect(0, p, 0);
7434b9366f8eSdrh       if( minMaxFlag ){
7435b9366f8eSdrh         sqlite3DebugPrintf("MIN/MAX Optimization (0x%02x) adds:\n", minMaxFlag);
7436b9366f8eSdrh         sqlite3TreeViewExprList(0, pMinMaxOrderBy, 0, "ORDERBY");
7437b9366f8eSdrh       }
7438bf790973Sdrh       for(ii=0; ii<pAggInfo->nColumn; ii++){
7439f4c29127Sdrh         struct AggInfo_col *pCol = &pAggInfo->aCol[ii];
7440f4c29127Sdrh         sqlite3DebugPrintf(
7441f4c29127Sdrh            "agg-column[%d] pTab=%s iTable=%d iColumn=%d iMem=%d"
7442f4c29127Sdrh            " iSorterColumn=%d\n",
7443f4c29127Sdrh            ii, pCol->pTab ? pCol->pTab->zName : "NULL",
7444f4c29127Sdrh            pCol->iTable, pCol->iColumn, pCol->iMem,
7445f4c29127Sdrh            pCol->iSorterColumn);
744681185a51Sdrh         sqlite3TreeViewExpr(0, pAggInfo->aCol[ii].pCExpr, 0);
74477ea11066Sdrh       }
7448bf790973Sdrh       for(ii=0; ii<pAggInfo->nFunc; ii++){
74497ea11066Sdrh         sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
7450bf790973Sdrh             ii, pAggInfo->aFunc[ii].iMem);
745181185a51Sdrh         sqlite3TreeViewExpr(0, pAggInfo->aFunc[ii].pFExpr, 0);
74527ea11066Sdrh       }
74537ea11066Sdrh     }
74547ea11066Sdrh #endif
74557ea11066Sdrh 
745613449892Sdrh 
745713449892Sdrh     /* Processing for aggregates with GROUP BY is very different and
74583c4809a2Sdanielk1977     ** much more complex than aggregates without a GROUP BY.
745913449892Sdrh     */
746013449892Sdrh     if( pGroupBy ){
746113449892Sdrh       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
7462728e0f91Sdrh       int addr1;          /* A-vs-B comparision jump */
7463d176611bSdrh       int addrOutputRow;  /* Start of subroutine that outputs a result row */
7464d176611bSdrh       int regOutputRow;   /* Return address register for output subroutine */
7465d176611bSdrh       int addrSetAbort;   /* Set the abort flag and return */
7466d176611bSdrh       int addrTopOfLoop;  /* Top of the input loop */
7467d176611bSdrh       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
7468d176611bSdrh       int addrReset;      /* Subroutine for resetting the accumulator */
7469d176611bSdrh       int regReset;       /* Return address register for reset subroutine */
74705383db71Sdan       ExprList *pDistinct = 0;
74715383db71Sdan       u16 distFlag = 0;
74725383db71Sdan       int eDist = WHERE_DISTINCT_NOOP;
74735383db71Sdan 
74745383db71Sdan       if( pAggInfo->nFunc==1
74755383db71Sdan        && pAggInfo->aFunc[0].iDistinct>=0
7476a4eeccdfSdrh        && ALWAYS(pAggInfo->aFunc[0].pFExpr!=0)
7477a4eeccdfSdrh        && ALWAYS(ExprUseXList(pAggInfo->aFunc[0].pFExpr))
7478a4eeccdfSdrh        && pAggInfo->aFunc[0].pFExpr->x.pList!=0
74795383db71Sdan       ){
74805383db71Sdan         Expr *pExpr = pAggInfo->aFunc[0].pFExpr->x.pList->a[0].pExpr;
74815383db71Sdan         pExpr = sqlite3ExprDup(db, pExpr, 0);
74825383db71Sdan         pDistinct = sqlite3ExprListDup(db, pGroupBy, 0);
74835383db71Sdan         pDistinct = sqlite3ExprListAppend(pParse, pDistinct, pExpr);
7484f330d53fSdan         distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0;
74855383db71Sdan       }
748613449892Sdrh 
748713449892Sdrh       /* If there is a GROUP BY clause we might need a sorting index to
748813449892Sdrh       ** implement it.  Allocate that sorting index now.  If it turns out
74891c9d835dSdrh       ** that we do not need it after all, the OP_SorterOpen instruction
749013449892Sdrh       ** will be converted into a Noop.
749113449892Sdrh       */
7492bf790973Sdrh       pAggInfo->sortingIdx = pParse->nTab++;
7493bf790973Sdrh       pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pGroupBy,
7494bf790973Sdrh                                             0, pAggInfo->nColumn);
74951c9d835dSdrh       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
7496bf790973Sdrh           pAggInfo->sortingIdx, pAggInfo->nSortingColumn,
74972ec2fb22Sdrh           0, (char*)pKeyInfo, P4_KEYINFO);
749813449892Sdrh 
749913449892Sdrh       /* Initialize memory locations used by GROUP BY aggregate processing
750013449892Sdrh       */
75010a07c107Sdrh       iUseFlag = ++pParse->nMem;
75020a07c107Sdrh       iAbortFlag = ++pParse->nMem;
7503d176611bSdrh       regOutputRow = ++pParse->nMem;
7504ec4ccdbcSdrh       addrOutputRow = sqlite3VdbeMakeLabel(pParse);
7505d176611bSdrh       regReset = ++pParse->nMem;
7506ec4ccdbcSdrh       addrReset = sqlite3VdbeMakeLabel(pParse);
75070a07c107Sdrh       iAMem = pParse->nMem + 1;
750813449892Sdrh       pParse->nMem += pGroupBy->nExpr;
75090a07c107Sdrh       iBMem = pParse->nMem + 1;
751013449892Sdrh       pParse->nMem += pGroupBy->nExpr;
75114c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
7512d4e70ebdSdrh       VdbeComment((v, "clear abort flag"));
7513b8475df8Sdrh       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
7514e313382eSdrh 
751513449892Sdrh       /* Begin a loop that will extract all source rows in GROUP BY order.
751613449892Sdrh       ** This might involve two separate loops with an OP_Sort in between, or
751713449892Sdrh       ** it might be a single loop that uses an index to extract information
751813449892Sdrh       ** in the right order to begin with.
751913449892Sdrh       */
75202eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
7521cfd74700Sdrh       SELECTTRACE(1,pParse,p,("WhereBegin\n"));
75225383db71Sdan       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, pDistinct,
7523fb643592Sdrh           p, (sDistinct.isTnct==2 ? WHERE_DISTINCTBY : WHERE_GROUPBY)
7524ece092e7Sdan           |  (orderByGrp ? WHERE_SORTBYGROUP : 0) | distFlag, 0
7525374cd78cSdan       );
7526bfd6f1bcSdan       if( pWInfo==0 ){
7527b19a5812Sdan         sqlite3ExprListDelete(db, pDistinct);
7528bfd6f1bcSdan         goto select_end;
7529bfd6f1bcSdan       }
753076075807Sdan       eDist = sqlite3WhereIsDistinct(pWInfo);
753113162ef9Sdrh       SELECTTRACE(1,pParse,p,("WhereBegin returns\n"));
7532ddba0c22Sdrh       if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
753313449892Sdrh         /* The optimizer is able to deliver rows in group by order so
7534b9bb7c18Sdrh         ** we do not have to sort.  The OP_OpenEphemeral table will be
753513449892Sdrh         ** cancelled later because we still need to use the pKeyInfo
753613449892Sdrh         */
753713449892Sdrh         groupBySort = 0;
753813449892Sdrh       }else{
753913449892Sdrh         /* Rows are coming out in undetermined order.  We have to push
754013449892Sdrh         ** each row into a sorting index, terminate the first loop,
754113449892Sdrh         ** then loop over the sorting index in order to get the output
754213449892Sdrh         ** in sorted order
754313449892Sdrh         */
7544892d3179Sdrh         int regBase;
7545892d3179Sdrh         int regRecord;
7546892d3179Sdrh         int nCol;
7547892d3179Sdrh         int nGroupBy;
7548892d3179Sdrh 
75492ce22453Sdan         explainTempTable(pParse,
7550e8e4af76Sdrh             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
7551e8e4af76Sdrh                     "DISTINCT" : "GROUP BY");
75522ce22453Sdan 
755313449892Sdrh         groupBySort = 1;
7554892d3179Sdrh         nGroupBy = pGroupBy->nExpr;
7555dd23c6bfSdan         nCol = nGroupBy;
7556dd23c6bfSdan         j = nGroupBy;
7557bf790973Sdrh         for(i=0; i<pAggInfo->nColumn; i++){
7558bf790973Sdrh           if( pAggInfo->aCol[i].iSorterColumn>=j ){
7559892d3179Sdrh             nCol++;
756013449892Sdrh             j++;
756113449892Sdrh           }
7562892d3179Sdrh         }
7563892d3179Sdrh         regBase = sqlite3GetTempRange(pParse, nCol);
75645579d59fSdrh         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
7565dd23c6bfSdan         j = nGroupBy;
7566ee373020Sdrh         pAggInfo->directMode = 1;
7567bf790973Sdrh         for(i=0; i<pAggInfo->nColumn; i++){
7568bf790973Sdrh           struct AggInfo_col *pCol = &pAggInfo->aCol[i];
7569892d3179Sdrh           if( pCol->iSorterColumn>=j ){
7570ee373020Sdrh             sqlite3ExprCode(pParse, pCol->pCExpr, j + regBase);
75716a012f04Sdrh             j++;
7572892d3179Sdrh           }
7573892d3179Sdrh         }
7574ee373020Sdrh         pAggInfo->directMode = 0;
7575892d3179Sdrh         regRecord = sqlite3GetTempReg(pParse);
75761db639ceSdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
7577bf790973Sdrh         sqlite3VdbeAddOp2(v, OP_SorterInsert, pAggInfo->sortingIdx, regRecord);
7578892d3179Sdrh         sqlite3ReleaseTempReg(pParse, regRecord);
7579892d3179Sdrh         sqlite3ReleaseTempRange(pParse, regBase, nCol);
758013162ef9Sdrh         SELECTTRACE(1,pParse,p,("WhereEnd\n"));
758113449892Sdrh         sqlite3WhereEnd(pWInfo);
7582bf790973Sdrh         pAggInfo->sortingIdxPTab = sortPTab = pParse->nTab++;
75831c9d835dSdrh         sortOut = sqlite3GetTempReg(pParse);
75841c9d835dSdrh         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
7585bf790973Sdrh         sqlite3VdbeAddOp2(v, OP_SorterSort, pAggInfo->sortingIdx, addrEnd);
7586688852abSdrh         VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
7587bf790973Sdrh         pAggInfo->useSortingIdx = 1;
7588374cd78cSdan       }
7589374cd78cSdan 
7590374cd78cSdan       /* If the index or temporary table used by the GROUP BY sort
7591374cd78cSdan       ** will naturally deliver rows in the order required by the ORDER BY
7592374cd78cSdan       ** clause, cancel the ephemeral table open coded earlier.
7593374cd78cSdan       **
7594374cd78cSdan       ** This is an optimization - the correct answer should result regardless.
7595374cd78cSdan       ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
7596374cd78cSdan       ** disable this optimization for testing purposes.  */
7597374cd78cSdan       if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
7598374cd78cSdan        && (groupBySort || sqlite3WhereIsSorted(pWInfo))
7599374cd78cSdan       ){
7600374cd78cSdan         sSort.pOrderBy = 0;
7601374cd78cSdan         sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
760213449892Sdrh       }
760313449892Sdrh 
760413449892Sdrh       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
760513449892Sdrh       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
760613449892Sdrh       ** Then compare the current GROUP BY terms against the GROUP BY terms
760713449892Sdrh       ** from the previous row currently stored in a0, a1, a2...
760813449892Sdrh       */
760913449892Sdrh       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
76101c9d835dSdrh       if( groupBySort ){
7611bf790973Sdrh         sqlite3VdbeAddOp3(v, OP_SorterData, pAggInfo->sortingIdx,
761238b4149cSdrh                           sortOut, sortPTab);
76131c9d835dSdrh       }
761413449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
761513449892Sdrh         if( groupBySort ){
76161c9d835dSdrh           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
761713449892Sdrh         }else{
7618bf790973Sdrh           pAggInfo->directMode = 1;
76192dcef11bSdrh           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
762013449892Sdrh         }
762113449892Sdrh       }
762216ee60ffSdrh       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
76232ec2fb22Sdrh                           (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
7624728e0f91Sdrh       addr1 = sqlite3VdbeCurrentAddr(v);
7625728e0f91Sdrh       sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
762613449892Sdrh 
762713449892Sdrh       /* Generate code that runs whenever the GROUP BY changes.
7628e00ee6ebSdrh       ** Changes in the GROUP BY are detected by the previous code
762913449892Sdrh       ** block.  If there were no changes, this block is skipped.
763013449892Sdrh       **
763113449892Sdrh       ** This code copies current group by terms in b0,b1,b2,...
763213449892Sdrh       ** over to a0,a1,a2.  It then calls the output subroutine
763313449892Sdrh       ** and resets the aggregate accumulator registers in preparation
763413449892Sdrh       ** for the next GROUP BY batch.
763513449892Sdrh       */
7636b21e7c70Sdrh       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
76372eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
7638d4e70ebdSdrh       VdbeComment((v, "output one row"));
7639688852abSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
7640d4e70ebdSdrh       VdbeComment((v, "check abort flag"));
76412eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
7642d4e70ebdSdrh       VdbeComment((v, "reset accumulator"));
764313449892Sdrh 
764413449892Sdrh       /* Update the aggregate accumulators based on the content of
764513449892Sdrh       ** the current row
764613449892Sdrh       */
7647728e0f91Sdrh       sqlite3VdbeJumpHere(v, addr1);
76485383db71Sdan       updateAccumulator(pParse, iUseFlag, pAggInfo, eDist);
76494c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
7650d4e70ebdSdrh       VdbeComment((v, "indicate data in accumulator"));
765113449892Sdrh 
765213449892Sdrh       /* End of the loop
765313449892Sdrh       */
765413449892Sdrh       if( groupBySort ){
7655bf790973Sdrh         sqlite3VdbeAddOp2(v, OP_SorterNext, pAggInfo->sortingIdx,addrTopOfLoop);
7656688852abSdrh         VdbeCoverage(v);
765713449892Sdrh       }else{
765813162ef9Sdrh         SELECTTRACE(1,pParse,p,("WhereEnd\n"));
765913449892Sdrh         sqlite3WhereEnd(pWInfo);
766048f2d3b1Sdrh         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
766113449892Sdrh       }
7662bfd6f1bcSdan       sqlite3ExprListDelete(db, pDistinct);
766313449892Sdrh 
766413449892Sdrh       /* Output the final row of result
766513449892Sdrh       */
76662eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
7667d4e70ebdSdrh       VdbeComment((v, "output final row"));
766813449892Sdrh 
7669d176611bSdrh       /* Jump over the subroutines
7670d176611bSdrh       */
7671076e85f5Sdrh       sqlite3VdbeGoto(v, addrEnd);
7672d176611bSdrh 
7673d176611bSdrh       /* Generate a subroutine that outputs a single row of the result
7674d176611bSdrh       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
7675d176611bSdrh       ** is less than or equal to zero, the subroutine is a no-op.  If
7676d176611bSdrh       ** the processing calls for the query to abort, this subroutine
7677d176611bSdrh       ** increments the iAbortFlag memory location before returning in
7678d176611bSdrh       ** order to signal the caller to abort.
7679d176611bSdrh       */
7680d176611bSdrh       addrSetAbort = sqlite3VdbeCurrentAddr(v);
7681d176611bSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
7682d176611bSdrh       VdbeComment((v, "set abort flag"));
7683d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
7684d176611bSdrh       sqlite3VdbeResolveLabel(v, addrOutputRow);
7685d176611bSdrh       addrOutputRow = sqlite3VdbeCurrentAddr(v);
7686d176611bSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
768738b4149cSdrh       VdbeCoverage(v);
7688d176611bSdrh       VdbeComment((v, "Groupby result generator entry point"));
7689d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
7690bf790973Sdrh       finalizeAggFunctions(pParse, pAggInfo);
7691d176611bSdrh       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
76922def2f7eSdrh       selectInnerLoop(pParse, p, -1, &sSort,
7693e8e4af76Sdrh                       &sDistinct, pDest,
7694d176611bSdrh                       addrOutputRow+1, addrSetAbort);
7695d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
7696d176611bSdrh       VdbeComment((v, "end groupby result generator"));
7697d176611bSdrh 
7698d176611bSdrh       /* Generate a subroutine that will reset the group-by accumulator
7699d176611bSdrh       */
7700d176611bSdrh       sqlite3VdbeResolveLabel(v, addrReset);
7701bf790973Sdrh       resetAccumulator(pParse, pAggInfo);
7702280c894bSdan       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
7703280c894bSdan       VdbeComment((v, "indicate accumulator empty"));
7704d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regReset);
7705d176611bSdrh 
7706ece092e7Sdan       if( distFlag!=0 && eDist!=WHERE_DISTINCT_NOOP ){
77075383db71Sdan         struct AggInfo_func *pF = &pAggInfo->aFunc[0];
77085383db71Sdan         fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
77095383db71Sdan       }
771043152cf8Sdrh     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
771113449892Sdrh     else {
7712a5533162Sdanielk1977       Table *pTab;
7713bf790973Sdrh       if( (pTab = isSimpleCount(p, pAggInfo))!=0 ){
7714a5533162Sdanielk1977         /* If isSimpleCount() returns a pointer to a Table structure, then
7715a5533162Sdanielk1977         ** the SQL statement is of the form:
7716a5533162Sdanielk1977         **
7717a5533162Sdanielk1977         **   SELECT count(*) FROM <tbl>
7718a5533162Sdanielk1977         **
7719a5533162Sdanielk1977         ** where the Table structure returned represents table <tbl>.
7720a5533162Sdanielk1977         **
7721a5533162Sdanielk1977         ** This statement is so common that it is optimized specially. The
7722a5533162Sdanielk1977         ** OP_Count instruction is executed either on the intkey table that
7723a5533162Sdanielk1977         ** contains the data for table <tbl> or on one of its indexes. It
7724a5533162Sdanielk1977         ** is better to execute the op on an index, as indexes are almost
7725a5533162Sdanielk1977         ** always spread across less pages than their corresponding tables.
7726a5533162Sdanielk1977         */
7727a5533162Sdanielk1977         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
7728a5533162Sdanielk1977         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
7729a5533162Sdanielk1977         Index *pIdx;                         /* Iterator variable */
7730a5533162Sdanielk1977         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
7731a5533162Sdanielk1977         Index *pBest = 0;                    /* Best index found so far */
7732013e7bb7Sdrh         Pgno iRoot = pTab->tnum;             /* Root page of scanned b-tree */
7733a9d1ccb9Sdanielk1977 
7734a5533162Sdanielk1977         sqlite3CodeVerifySchema(pParse, iDb);
7735a5533162Sdanielk1977         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
7736a5533162Sdanielk1977 
7737d9e3cad2Sdrh         /* Search for the index that has the lowest scan cost.
7738a5533162Sdanielk1977         **
77393e9548b3Sdrh         ** (2011-04-15) Do not do a full scan of an unordered index.
77403e9548b3Sdrh         **
7741abcc1941Sdrh         ** (2013-10-03) Do not count the entries in a partial index.
77425f33f375Sdrh         **
7743a5533162Sdanielk1977         ** In practice the KeyInfo structure will not be used. It is only
7744a5533162Sdanielk1977         ** passed to keep OP_OpenRead happy.
7745a5533162Sdanielk1977         */
77465c7917e4Sdrh         if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
774798aa1d73Sdrh         if( !p->pSrc->a[0].fg.notIndexed ){
7748a5533162Sdanielk1977           for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
7749d9e3cad2Sdrh             if( pIdx->bUnordered==0
7750e13e9f54Sdrh              && pIdx->szIdxRow<pTab->szTabRow
7751d3037a41Sdrh              && pIdx->pPartIdxWhere==0
7752e13e9f54Sdrh              && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
7753d9e3cad2Sdrh             ){
7754a5533162Sdanielk1977               pBest = pIdx;
7755a5533162Sdanielk1977             }
7756a5533162Sdanielk1977           }
775798aa1d73Sdrh         }
7758d9e3cad2Sdrh         if( pBest ){
7759a5533162Sdanielk1977           iRoot = pBest->tnum;
77602ec2fb22Sdrh           pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
7761a5533162Sdanielk1977         }
7762a5533162Sdanielk1977 
7763a5533162Sdanielk1977         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
7764013e7bb7Sdrh         sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, (int)iRoot, iDb, 1);
7765a5533162Sdanielk1977         if( pKeyInfo ){
77662ec2fb22Sdrh           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
7767a5533162Sdanielk1977         }
7768bf790973Sdrh         sqlite3VdbeAddOp2(v, OP_Count, iCsr, pAggInfo->aFunc[0].iMem);
7769a5533162Sdanielk1977         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
7770ef7075deSdan         explainSimpleCount(pParse, pTab, pBest);
7771e50478d7Sdrh       }else{
7772280c894bSdan         int regAcc = 0;           /* "populate accumulators" flag */
77734fcb30b7Sdan         ExprList *pDistinct = 0;
77744fcb30b7Sdan         u16 distFlag = 0;
77755383db71Sdan         int eDist;
7776280c894bSdan 
7777ed09dddeSdan         /* If there are accumulator registers but no min() or max() functions
7778ed09dddeSdan         ** without FILTER clauses, allocate register regAcc. Register regAcc
7779ed09dddeSdan         ** will contain 0 the first time the inner loop runs, and 1 thereafter.
7780ed09dddeSdan         ** The code generated by updateAccumulator() uses this to ensure
7781ed09dddeSdan         ** that the accumulator registers are (a) updated only once if
7782ed09dddeSdan         ** there are no min() or max functions or (b) always updated for the
7783ed09dddeSdan         ** first row visited by the aggregate, so that they are updated at
7784ed09dddeSdan         ** least once even if the FILTER clause means the min() or max()
7785ed09dddeSdan         ** function visits zero rows.  */
7786bf790973Sdrh         if( pAggInfo->nAccumulator ){
7787bf790973Sdrh           for(i=0; i<pAggInfo->nFunc; i++){
778881185a51Sdrh             if( ExprHasProperty(pAggInfo->aFunc[i].pFExpr, EP_WinFunc) ){
7789bf790973Sdrh               continue;
7790280c894bSdan             }
7791bf790973Sdrh             if( pAggInfo->aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ){
7792bf790973Sdrh               break;
7793bf790973Sdrh             }
7794bf790973Sdrh           }
7795bf790973Sdrh           if( i==pAggInfo->nFunc ){
7796280c894bSdan             regAcc = ++pParse->nMem;
7797280c894bSdan             sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
7798280c894bSdan           }
77994fcb30b7Sdan         }else if( pAggInfo->nFunc==1 && pAggInfo->aFunc[0].iDistinct>=0 ){
7800a4eeccdfSdrh           assert( ExprUseXList(pAggInfo->aFunc[0].pFExpr) );
78014fcb30b7Sdan           pDistinct = pAggInfo->aFunc[0].pFExpr->x.pList;
7802f330d53fSdan           distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0;
7803280c894bSdan         }
7804280c894bSdan 
780513449892Sdrh         /* This case runs if the aggregate has no GROUP BY clause.  The
780613449892Sdrh         ** processing is much simpler since there is only a single row
780713449892Sdrh         ** of output.
780813449892Sdrh         */
780947d9f839Sdrh         assert( p->pGroupBy==0 );
7810bf790973Sdrh         resetAccumulator(pParse, pAggInfo);
781147d9f839Sdrh 
781247d9f839Sdrh         /* If this query is a candidate for the min/max optimization, then
781347d9f839Sdrh         ** minMaxFlag will have been previously set to either
781447d9f839Sdrh         ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
781547d9f839Sdrh         ** be an appropriate ORDER BY expression for the optimization.
781647d9f839Sdrh         */
781747d9f839Sdrh         assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
781847d9f839Sdrh         assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
781947d9f839Sdrh 
7820cfd74700Sdrh         SELECTTRACE(1,pParse,p,("WhereBegin\n"));
782147d9f839Sdrh         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
7822fb643592Sdrh                                    pDistinct, p, minMaxFlag|distFlag, 0);
7823dba0137eSdanielk1977         if( pWInfo==0 ){
7824dba0137eSdanielk1977           goto select_end;
7825dba0137eSdanielk1977         }
782613162ef9Sdrh         SELECTTRACE(1,pParse,p,("WhereBegin returns\n"));
78275383db71Sdan         eDist = sqlite3WhereIsDistinct(pWInfo);
78285383db71Sdan         updateAccumulator(pParse, regAcc, pAggInfo, eDist);
78295383db71Sdan         if( eDist!=WHERE_DISTINCT_NOOP ){
7830de695eabSdrh           struct AggInfo_func *pF = pAggInfo->aFunc;
78313117b7b0Sdrh           if( pF ){
78325383db71Sdan             fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
78335383db71Sdan           }
78343117b7b0Sdrh         }
78355383db71Sdan 
7836280c894bSdan         if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
7837d193057aSdrh         if( minMaxFlag ){
7838d193057aSdrh           sqlite3WhereMinMaxOptEarlyOut(v, pWInfo);
7839a9d1ccb9Sdanielk1977         }
784013162ef9Sdrh         SELECTTRACE(1,pParse,p,("WhereEnd\n"));
784113449892Sdrh         sqlite3WhereEnd(pWInfo);
7842bf790973Sdrh         finalizeAggFunctions(pParse, pAggInfo);
78437a895a80Sdanielk1977       }
78447a895a80Sdanielk1977 
7845079a3072Sdrh       sSort.pOrderBy = 0;
784635573356Sdrh       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
78472def2f7eSdrh       selectInnerLoop(pParse, p, -1, 0, 0,
7848a9671a22Sdrh                       pDest, addrEnd, addrEnd);
784913449892Sdrh     }
785013449892Sdrh     sqlite3VdbeResolveLabel(v, addrEnd);
785113449892Sdrh 
785213449892Sdrh   } /* endif aggregate query */
78532282792aSdrh 
7854e8e4af76Sdrh   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
78552ce22453Sdan     explainTempTable(pParse, "DISTINCT");
78562ce22453Sdan   }
78572ce22453Sdan 
7858cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
7859cce7d176Sdrh   ** and send them to the callback one by one.
7860cce7d176Sdrh   */
7861079a3072Sdrh   if( sSort.pOrderBy ){
786238b4149cSdrh     explainTempTable(pParse,
786338b4149cSdrh                      sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
786424e25d32Sdan     assert( p->pEList==pEList );
7865079a3072Sdrh     generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
7866cce7d176Sdrh   }
78676a535340Sdrh 
7868ec7429aeSdrh   /* Jump here to skip this query
7869ec7429aeSdrh   */
7870ec7429aeSdrh   sqlite3VdbeResolveLabel(v, iEnd);
7871ec7429aeSdrh 
78725b1c07e7Sdan   /* The SELECT has been coded. If there is an error in the Parse structure,
78735b1c07e7Sdan   ** set the return code to 1. Otherwise 0. */
78745b1c07e7Sdan   rc = (pParse->nErr>0);
78751d83f052Sdrh 
78761d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
78771d83f052Sdrh   ** successful coding of the SELECT.
78781d83f052Sdrh   */
78791d83f052Sdrh select_end:
788044918c74Sdan   assert( db->mallocFailed==0 || db->mallocFailed==1 );
78810c7d3d39Sdrh   assert( db->mallocFailed==0 || pParse->nErr!=0 );
788247d9f839Sdrh   sqlite3ExprListDelete(db, pMinMaxOrderBy);
788389636628Sdrh #ifdef SQLITE_DEBUG
78847b4c4d4aSdrh   if( pAggInfo && !db->mallocFailed ){
7885bf790973Sdrh     for(i=0; i<pAggInfo->nColumn; i++){
788681185a51Sdrh       Expr *pExpr = pAggInfo->aCol[i].pCExpr;
788706ddb08fSdrh       assert( pExpr!=0 );
7888bf790973Sdrh       assert( pExpr->pAggInfo==pAggInfo );
788989636628Sdrh       assert( pExpr->iAgg==i );
789089636628Sdrh     }
7891bf790973Sdrh     for(i=0; i<pAggInfo->nFunc; i++){
789281185a51Sdrh       Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
789306ddb08fSdrh       assert( pExpr!=0 );
7894bf790973Sdrh       assert( pExpr->pAggInfo==pAggInfo );
789589636628Sdrh       assert( pExpr->iAgg==i );
789689636628Sdrh     }
789789636628Sdrh   }
789889636628Sdrh #endif
789989636628Sdrh 
79005e431beaSdrh #if TREETRACE_ENABLED
7901f20609d1Sdrh   SELECTTRACE(0x1,pParse,p,("end processing\n"));
79025e431beaSdrh   if( (sqlite3TreeTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
7903f20609d1Sdrh     sqlite3TreeViewSelect(0, p, 0);
7904f20609d1Sdrh   }
7905eb9b884cSdrh #endif
7906e2ca99c9Sdrh   ExplainQueryPlanPop(pParse);
79071d83f052Sdrh   return rc;
7908cce7d176Sdrh }
7909