xref: /sqlite-3.40.0/src/select.c (revision f018cc2e)
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 **
15*f018cc2eSdrh ** $Id: select.c,v 1.473 2008/09/13 01:20:15 drh Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19315555caSdrh 
20cce7d176Sdrh /*
21eda639e1Sdrh ** Delete all the content of a Select structure but do not deallocate
22eda639e1Sdrh ** the select structure itself.
23eda639e1Sdrh */
24633e6d57Sdrh static void clearSelect(sqlite3 *db, Select *p){
25633e6d57Sdrh   sqlite3ExprListDelete(db, p->pEList);
26633e6d57Sdrh   sqlite3SrcListDelete(db, p->pSrc);
27633e6d57Sdrh   sqlite3ExprDelete(db, p->pWhere);
28633e6d57Sdrh   sqlite3ExprListDelete(db, p->pGroupBy);
29633e6d57Sdrh   sqlite3ExprDelete(db, p->pHaving);
30633e6d57Sdrh   sqlite3ExprListDelete(db, p->pOrderBy);
31633e6d57Sdrh   sqlite3SelectDelete(db, p->pPrior);
32633e6d57Sdrh   sqlite3ExprDelete(db, p->pLimit);
33633e6d57Sdrh   sqlite3ExprDelete(db, p->pOffset);
34eda639e1Sdrh }
35eda639e1Sdrh 
361013c932Sdrh /*
371013c932Sdrh ** Initialize a SelectDest structure.
381013c932Sdrh */
391013c932Sdrh void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
401013c932Sdrh   pDest->eDest = eDest;
411013c932Sdrh   pDest->iParm = iParm;
421013c932Sdrh   pDest->affinity = 0;
431013c932Sdrh   pDest->iMem = 0;
44ad27e761Sdrh   pDest->nMem = 0;
451013c932Sdrh }
461013c932Sdrh 
47eda639e1Sdrh 
48eda639e1Sdrh /*
499bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that
509bb61fe7Sdrh ** structure.
51cce7d176Sdrh */
524adee20fSdanielk1977 Select *sqlite3SelectNew(
5317435752Sdrh   Parse *pParse,        /* Parsing context */
54daffd0e5Sdrh   ExprList *pEList,     /* which columns to include in the result */
55ad3cab52Sdrh   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
56daffd0e5Sdrh   Expr *pWhere,         /* the WHERE clause */
57daffd0e5Sdrh   ExprList *pGroupBy,   /* the GROUP BY clause */
58daffd0e5Sdrh   Expr *pHaving,        /* the HAVING clause */
59daffd0e5Sdrh   ExprList *pOrderBy,   /* the ORDER BY clause */
609bbca4c1Sdrh   int isDistinct,       /* true if the DISTINCT keyword is present */
61a2dc3b1aSdanielk1977   Expr *pLimit,         /* LIMIT value.  NULL means not used */
62a2dc3b1aSdanielk1977   Expr *pOffset         /* OFFSET value.  NULL means no offset */
639bb61fe7Sdrh ){
649bb61fe7Sdrh   Select *pNew;
65eda639e1Sdrh   Select standin;
6617435752Sdrh   sqlite3 *db = pParse->db;
6717435752Sdrh   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
68a2dc3b1aSdanielk1977   assert( !pOffset || pLimit );   /* Can't have OFFSET without LIMIT. */
69daffd0e5Sdrh   if( pNew==0 ){
70eda639e1Sdrh     pNew = &standin;
71eda639e1Sdrh     memset(pNew, 0, sizeof(*pNew));
72eda639e1Sdrh   }
73b733d037Sdrh   if( pEList==0 ){
74a1644fd8Sdanielk1977     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
75b733d037Sdrh   }
769bb61fe7Sdrh   pNew->pEList = pEList;
779bb61fe7Sdrh   pNew->pSrc = pSrc;
789bb61fe7Sdrh   pNew->pWhere = pWhere;
799bb61fe7Sdrh   pNew->pGroupBy = pGroupBy;
809bb61fe7Sdrh   pNew->pHaving = pHaving;
819bb61fe7Sdrh   pNew->pOrderBy = pOrderBy;
827d10d5a6Sdrh   pNew->selFlags = isDistinct ? SF_Distinct : 0;
8382c3d636Sdrh   pNew->op = TK_SELECT;
848103b7d2Sdrh   assert( pOffset==0 || pLimit!=0 );
85a2dc3b1aSdanielk1977   pNew->pLimit = pLimit;
86a2dc3b1aSdanielk1977   pNew->pOffset = pOffset;
87b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
88b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
89b9bb7c18Sdrh   pNew->addrOpenEphm[2] = -1;
900a846f96Sdrh   if( db->mallocFailed ) {
91633e6d57Sdrh     clearSelect(db, pNew);
920a846f96Sdrh     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
93eda639e1Sdrh     pNew = 0;
94daffd0e5Sdrh   }
959bb61fe7Sdrh   return pNew;
969bb61fe7Sdrh }
979bb61fe7Sdrh 
989bb61fe7Sdrh /*
99eda639e1Sdrh ** Delete the given Select structure and all of its substructures.
100eda639e1Sdrh */
101633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){
102eda639e1Sdrh   if( p ){
103633e6d57Sdrh     clearSelect(db, p);
104633e6d57Sdrh     sqlite3DbFree(db, p);
105eda639e1Sdrh   }
106eda639e1Sdrh }
107eda639e1Sdrh 
108eda639e1Sdrh /*
10901f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
11001f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
11101f3f253Sdrh ** in terms of the following bit values:
11201f3f253Sdrh **
11301f3f253Sdrh **     JT_INNER
1143dec223cSdrh **     JT_CROSS
11501f3f253Sdrh **     JT_OUTER
11601f3f253Sdrh **     JT_NATURAL
11701f3f253Sdrh **     JT_LEFT
11801f3f253Sdrh **     JT_RIGHT
11901f3f253Sdrh **
12001f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
12101f3f253Sdrh **
12201f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
12301f3f253Sdrh ** a join type, but put an error in the pParse structure.
12401f3f253Sdrh */
1254adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
12601f3f253Sdrh   int jointype = 0;
12701f3f253Sdrh   Token *apAll[3];
12801f3f253Sdrh   Token *p;
1295719628aSdrh   static const struct {
130c182d163Sdrh     const char zKeyword[8];
131290c1948Sdrh     u8 nChar;
132290c1948Sdrh     u8 code;
13301f3f253Sdrh   } keywords[] = {
13401f3f253Sdrh     { "natural", 7, JT_NATURAL },
135195e6967Sdrh     { "left",    4, JT_LEFT|JT_OUTER },
136195e6967Sdrh     { "right",   5, JT_RIGHT|JT_OUTER },
137195e6967Sdrh     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
13801f3f253Sdrh     { "outer",   5, JT_OUTER },
13901f3f253Sdrh     { "inner",   5, JT_INNER },
1403dec223cSdrh     { "cross",   5, JT_INNER|JT_CROSS },
14101f3f253Sdrh   };
14201f3f253Sdrh   int i, j;
14301f3f253Sdrh   apAll[0] = pA;
14401f3f253Sdrh   apAll[1] = pB;
14501f3f253Sdrh   apAll[2] = pC;
146195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
14701f3f253Sdrh     p = apAll[i];
14801f3f253Sdrh     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
14901f3f253Sdrh       if( p->n==keywords[j].nChar
1502646da7eSdrh           && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
15101f3f253Sdrh         jointype |= keywords[j].code;
15201f3f253Sdrh         break;
15301f3f253Sdrh       }
15401f3f253Sdrh     }
15501f3f253Sdrh     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
15601f3f253Sdrh       jointype |= JT_ERROR;
15701f3f253Sdrh       break;
15801f3f253Sdrh     }
15901f3f253Sdrh   }
160ad2d8307Sdrh   if(
161ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
162195e6967Sdrh      (jointype & JT_ERROR)!=0
163ad2d8307Sdrh   ){
164a9671a22Sdrh     const char *zSp = " ";
165a9671a22Sdrh     assert( pB!=0 );
166a9671a22Sdrh     if( pC==0 ){ zSp++; }
167ae29ffbeSdrh     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
168a9671a22Sdrh        "%T %T%s%T", pA, pB, zSp, pC);
16901f3f253Sdrh     jointype = JT_INNER;
170195e6967Sdrh   }else if( jointype & JT_RIGHT ){
1714adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
172da93d238Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported");
173195e6967Sdrh     jointype = JT_INNER;
17401f3f253Sdrh   }
17501f3f253Sdrh   return jointype;
17601f3f253Sdrh }
17701f3f253Sdrh 
17801f3f253Sdrh /*
179ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
180ad2d8307Sdrh ** is not contained in the table.
181ad2d8307Sdrh */
182ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
183ad2d8307Sdrh   int i;
184ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
1854adee20fSdanielk1977     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
186ad2d8307Sdrh   }
187ad2d8307Sdrh   return -1;
188ad2d8307Sdrh }
189ad2d8307Sdrh 
190ad2d8307Sdrh /*
19191bb0eedSdrh ** Set the value of a token to a '\000'-terminated string.
19291bb0eedSdrh */
19391bb0eedSdrh static void setToken(Token *p, const char *z){
1942646da7eSdrh   p->z = (u8*)z;
195261919ccSdanielk1977   p->n = z ? strlen(z) : 0;
19691bb0eedSdrh   p->dyn = 0;
19791bb0eedSdrh }
19891bb0eedSdrh 
199c182d163Sdrh /*
200f3b863edSdanielk1977 ** Set the token to the double-quoted and escaped version of the string pointed
201f3b863edSdanielk1977 ** to by z. For example;
202f3b863edSdanielk1977 **
203f3b863edSdanielk1977 **    {a"bc}  ->  {"a""bc"}
204f3b863edSdanielk1977 */
2051e536953Sdanielk1977 static void setQuotedToken(Parse *pParse, Token *p, const char *z){
206a686bfcfSdanielk1977 
207*f018cc2eSdrh   /* Check if the string appears to be quoted using "..." or `...`
208*f018cc2eSdrh   ** or [...] or '...' or if the string contains any " characters.
209*f018cc2eSdrh   ** If it does, then record a version of the string with the special
210*f018cc2eSdrh   ** characters escaped.
211a686bfcfSdanielk1977   */
212a686bfcfSdanielk1977   const char *z2 = z;
213*f018cc2eSdrh   if( *z2!='[' && *z2!='`' && *z2!='\'' ){
214a686bfcfSdanielk1977     while( *z2 ){
215a686bfcfSdanielk1977       if( *z2=='"' ) break;
216a686bfcfSdanielk1977       z2++;
217a686bfcfSdanielk1977     }
218*f018cc2eSdrh   }
219a686bfcfSdanielk1977 
220a686bfcfSdanielk1977   if( *z2 ){
221a686bfcfSdanielk1977     /* String contains " characters - copy and quote the string. */
222a686bfcfSdanielk1977     p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z);
223f3b863edSdanielk1977     if( p->z ){
224f3b863edSdanielk1977       p->n = strlen((char *)p->z);
225a686bfcfSdanielk1977       p->dyn = 1;
226a686bfcfSdanielk1977     }
2271e536953Sdanielk1977   }else{
228a686bfcfSdanielk1977     /* String contains no " characters - copy the pointer. */
229a686bfcfSdanielk1977     p->z = (u8*)z;
230a686bfcfSdanielk1977     p->n = (z2 - z);
231a686bfcfSdanielk1977     p->dyn = 0;
232f3b863edSdanielk1977   }
233f3b863edSdanielk1977 }
234f3b863edSdanielk1977 
235f3b863edSdanielk1977 /*
236c182d163Sdrh ** Create an expression node for an identifier with the name of zName
237c182d163Sdrh */
23817435752Sdrh Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
239c182d163Sdrh   Token dummy;
240c182d163Sdrh   setToken(&dummy, zName);
24117435752Sdrh   return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
242c182d163Sdrh }
243c182d163Sdrh 
24491bb0eedSdrh /*
245ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the
246ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2.
247ad2d8307Sdrh */
248ad2d8307Sdrh static void addWhereTerm(
24917435752Sdrh   Parse *pParse,           /* Parsing context */
250ad2d8307Sdrh   const char *zCol,        /* Name of the column */
251ad2d8307Sdrh   const Table *pTab1,      /* First table */
252030530deSdrh   const char *zAlias1,     /* Alias for first table.  May be NULL */
253ad2d8307Sdrh   const Table *pTab2,      /* Second table */
254030530deSdrh   const char *zAlias2,     /* Alias for second table.  May be NULL */
25522d6a53aSdrh   int iRightJoinTable,     /* VDBE cursor for the right table */
256ad27e761Sdrh   Expr **ppExpr,           /* Add the equality term to this expression */
257ad27e761Sdrh   int isOuterJoin          /* True if dealing with an OUTER join */
258ad2d8307Sdrh ){
259ad2d8307Sdrh   Expr *pE1a, *pE1b, *pE1c;
260ad2d8307Sdrh   Expr *pE2a, *pE2b, *pE2c;
261ad2d8307Sdrh   Expr *pE;
262ad2d8307Sdrh 
26317435752Sdrh   pE1a = sqlite3CreateIdExpr(pParse, zCol);
26417435752Sdrh   pE2a = sqlite3CreateIdExpr(pParse, zCol);
265030530deSdrh   if( zAlias1==0 ){
266030530deSdrh     zAlias1 = pTab1->zName;
267030530deSdrh   }
26817435752Sdrh   pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
269030530deSdrh   if( zAlias2==0 ){
270030530deSdrh     zAlias2 = pTab2->zName;
271030530deSdrh   }
27217435752Sdrh   pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
27317435752Sdrh   pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
27417435752Sdrh   pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
2751e536953Sdanielk1977   pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
276ad27e761Sdrh   if( pE && isOuterJoin ){
2771f16230bSdrh     ExprSetProperty(pE, EP_FromJoin);
27822d6a53aSdrh     pE->iRightJoinTable = iRightJoinTable;
279206f3d96Sdrh   }
280f4ce8ed0Sdrh   *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
281ad2d8307Sdrh }
282ad2d8307Sdrh 
283ad2d8307Sdrh /*
2841f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
28522d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the
28622d6a53aSdrh ** expression.
2871cc093c2Sdrh **
288e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
2891cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
2901f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
2911f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
2921f16230bSdrh ** WHERE clause during join processing but we need to remember that they
2931f16230bSdrh ** originated in the ON or USING clause.
29422d6a53aSdrh **
29522d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the
29622d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not
29722d6a53aSdrh ** explicitly mentioned in the expression.  That information is needed
29822d6a53aSdrh ** for cases like this:
29922d6a53aSdrh **
30022d6a53aSdrh **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
30122d6a53aSdrh **
30222d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5
30322d6a53aSdrh ** term until after the t2 loop of the join.  In that way, a
30422d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
30522d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately
30622d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in
30722d6a53aSdrh ** the output, which is incorrect.
3081cc093c2Sdrh */
30922d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){
3101cc093c2Sdrh   while( p ){
3111f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
31222d6a53aSdrh     p->iRightJoinTable = iTable;
31322d6a53aSdrh     setJoinExpr(p->pLeft, iTable);
3141cc093c2Sdrh     p = p->pRight;
3151cc093c2Sdrh   }
3161cc093c2Sdrh }
3171cc093c2Sdrh 
3181cc093c2Sdrh /*
319ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
320ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
321ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
322ad2d8307Sdrh **
32391bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure.
32491bb0eedSdrh ** The left most table is the first entry in Select.pSrc.  The right-most
32591bb0eedSdrh ** table is the last entry.  The join operator is held in the entry to
32691bb0eedSdrh ** the left.  Thus entry 0 contains the join operator for the join between
32791bb0eedSdrh ** entries 0 and 1.  Any ON or USING clauses associated with the join are
32891bb0eedSdrh ** also attached to the left entry.
32991bb0eedSdrh **
330ad2d8307Sdrh ** This routine returns the number of errors encountered.
331ad2d8307Sdrh */
332ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
33391bb0eedSdrh   SrcList *pSrc;                  /* All tables in the FROM clause */
33491bb0eedSdrh   int i, j;                       /* Loop counters */
33591bb0eedSdrh   struct SrcList_item *pLeft;     /* Left table being joined */
33691bb0eedSdrh   struct SrcList_item *pRight;    /* Right table being joined */
337ad2d8307Sdrh 
33891bb0eedSdrh   pSrc = p->pSrc;
33991bb0eedSdrh   pLeft = &pSrc->a[0];
34091bb0eedSdrh   pRight = &pLeft[1];
34191bb0eedSdrh   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
34291bb0eedSdrh     Table *pLeftTab = pLeft->pTab;
34391bb0eedSdrh     Table *pRightTab = pRight->pTab;
344ad27e761Sdrh     int isOuter;
34591bb0eedSdrh 
34691bb0eedSdrh     if( pLeftTab==0 || pRightTab==0 ) continue;
347ad27e761Sdrh     isOuter = (pRight->jointype & JT_OUTER)!=0;
348ad2d8307Sdrh 
349ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
350ad2d8307Sdrh     ** every column that the two tables have in common.
351ad2d8307Sdrh     */
35261dfc31dSdrh     if( pRight->jointype & JT_NATURAL ){
35361dfc31dSdrh       if( pRight->pOn || pRight->pUsing ){
3544adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
355ad2d8307Sdrh            "an ON or USING clause", 0);
356ad2d8307Sdrh         return 1;
357ad2d8307Sdrh       }
35891bb0eedSdrh       for(j=0; j<pLeftTab->nCol; j++){
35991bb0eedSdrh         char *zName = pLeftTab->aCol[j].zName;
36091bb0eedSdrh         if( columnIndex(pRightTab, zName)>=0 ){
3611e536953Sdanielk1977           addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
36222d6a53aSdrh                               pRightTab, pRight->zAlias,
363ad27e761Sdrh                               pRight->iCursor, &p->pWhere, isOuter);
36422d6a53aSdrh 
365ad2d8307Sdrh         }
366ad2d8307Sdrh       }
367ad2d8307Sdrh     }
368ad2d8307Sdrh 
369ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
370ad2d8307Sdrh     */
37161dfc31dSdrh     if( pRight->pOn && pRight->pUsing ){
3724adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
373da93d238Sdrh         "clauses in the same join");
374ad2d8307Sdrh       return 1;
375ad2d8307Sdrh     }
376ad2d8307Sdrh 
377ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
37891bb0eedSdrh     ** an AND operator.
379ad2d8307Sdrh     */
38061dfc31dSdrh     if( pRight->pOn ){
381ad27e761Sdrh       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
38217435752Sdrh       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
38361dfc31dSdrh       pRight->pOn = 0;
384ad2d8307Sdrh     }
385ad2d8307Sdrh 
386ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
387ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
388ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
389ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
390ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
391ad2d8307Sdrh     ** not contained in both tables to be joined.
392ad2d8307Sdrh     */
39361dfc31dSdrh     if( pRight->pUsing ){
39461dfc31dSdrh       IdList *pList = pRight->pUsing;
395ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
39691bb0eedSdrh         char *zName = pList->a[j].zName;
39791bb0eedSdrh         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
3984adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
39991bb0eedSdrh             "not present in both tables", zName);
400ad2d8307Sdrh           return 1;
401ad2d8307Sdrh         }
4021e536953Sdanielk1977         addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
40322d6a53aSdrh                             pRightTab, pRight->zAlias,
404ad27e761Sdrh                             pRight->iCursor, &p->pWhere, isOuter);
405ad2d8307Sdrh       }
406ad2d8307Sdrh     }
407ad2d8307Sdrh   }
408ad2d8307Sdrh   return 0;
409ad2d8307Sdrh }
410ad2d8307Sdrh 
411ad2d8307Sdrh /*
412c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
413c926afbcSdrh ** stack into the sorter.
414c926afbcSdrh */
415d59ba6ceSdrh static void pushOntoSorter(
416d59ba6ceSdrh   Parse *pParse,         /* Parser context */
417d59ba6ceSdrh   ExprList *pOrderBy,    /* The ORDER BY clause */
418b7654111Sdrh   Select *pSelect,       /* The whole SELECT statement */
419b7654111Sdrh   int regData            /* Register holding data to be sorted */
420d59ba6ceSdrh ){
421d59ba6ceSdrh   Vdbe *v = pParse->pVdbe;
422892d3179Sdrh   int nExpr = pOrderBy->nExpr;
423892d3179Sdrh   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
424892d3179Sdrh   int regRecord = sqlite3GetTempReg(pParse);
425191b54cbSdrh   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
426892d3179Sdrh   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
427b21e7c70Sdrh   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
4281db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
429892d3179Sdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
430892d3179Sdrh   sqlite3ReleaseTempReg(pParse, regRecord);
431892d3179Sdrh   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
43292b01d53Sdrh   if( pSelect->iLimit ){
43315007a99Sdrh     int addr1, addr2;
434b7654111Sdrh     int iLimit;
4350acb7e48Sdrh     if( pSelect->iOffset ){
436b7654111Sdrh       iLimit = pSelect->iOffset+1;
437b7654111Sdrh     }else{
438b7654111Sdrh       iLimit = pSelect->iLimit;
439b7654111Sdrh     }
440b7654111Sdrh     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
441b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
4423c84ddffSdrh     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
443d59ba6ceSdrh     sqlite3VdbeJumpHere(v, addr1);
4443c84ddffSdrh     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
4453c84ddffSdrh     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
44615007a99Sdrh     sqlite3VdbeJumpHere(v, addr2);
44792b01d53Sdrh     pSelect->iLimit = 0;
448d59ba6ceSdrh   }
449c926afbcSdrh }
450c926afbcSdrh 
451c926afbcSdrh /*
452ec7429aeSdrh ** Add code to implement the OFFSET
453ea48eb2eSdrh */
454ec7429aeSdrh static void codeOffset(
455bab39e13Sdrh   Vdbe *v,          /* Generate code into this VM */
456ea48eb2eSdrh   Select *p,        /* The SELECT statement being coded */
457b7654111Sdrh   int iContinue     /* Jump here to skip the current record */
458ea48eb2eSdrh ){
45992b01d53Sdrh   if( p->iOffset && iContinue!=0 ){
46015007a99Sdrh     int addr;
4618558cde1Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
4623c84ddffSdrh     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
46366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
464d4e70ebdSdrh     VdbeComment((v, "skip OFFSET records"));
46515007a99Sdrh     sqlite3VdbeJumpHere(v, addr);
466ea48eb2eSdrh   }
467ea48eb2eSdrh }
468ea48eb2eSdrh 
469ea48eb2eSdrh /*
47098757157Sdrh ** Add code that will check to make sure the N registers starting at iMem
47198757157Sdrh ** form a distinct entry.  iTab is a sorting index that holds previously
472a2a49dc9Sdrh ** seen combinations of the N values.  A new entry is made in iTab
473a2a49dc9Sdrh ** if the current N values are new.
474a2a49dc9Sdrh **
475a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the
476a2a49dc9Sdrh ** stack if the top N elements are not distinct.
477a2a49dc9Sdrh */
478a2a49dc9Sdrh static void codeDistinct(
4792dcef11bSdrh   Parse *pParse,     /* Parsing and code generating context */
480a2a49dc9Sdrh   int iTab,          /* A sorting index used to test for distinctness */
481a2a49dc9Sdrh   int addrRepeat,    /* Jump to here if not distinct */
482477df4b3Sdrh   int N,             /* Number of elements */
483a2a49dc9Sdrh   int iMem           /* First element */
484a2a49dc9Sdrh ){
4852dcef11bSdrh   Vdbe *v;
4862dcef11bSdrh   int r1;
4872dcef11bSdrh 
4882dcef11bSdrh   v = pParse->pVdbe;
4892dcef11bSdrh   r1 = sqlite3GetTempReg(pParse);
4901db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
4912dcef11bSdrh   sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1);
4922dcef11bSdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
4932dcef11bSdrh   sqlite3ReleaseTempReg(pParse, r1);
494a2a49dc9Sdrh }
495a2a49dc9Sdrh 
496a2a49dc9Sdrh /*
497e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression
498e305f43fSdrh ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
499e305f43fSdrh ** column.  We do this in a subroutine because the error occurs in multiple
500e305f43fSdrh ** places.
501e305f43fSdrh */
5026c8c8ce0Sdanielk1977 static int checkForMultiColumnSelectError(
5036c8c8ce0Sdanielk1977   Parse *pParse,       /* Parse context. */
5046c8c8ce0Sdanielk1977   SelectDest *pDest,   /* Destination of SELECT results */
5056c8c8ce0Sdanielk1977   int nExpr            /* Number of result columns returned by SELECT */
5066c8c8ce0Sdanielk1977 ){
5076c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
508e305f43fSdrh   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
509e305f43fSdrh     sqlite3ErrorMsg(pParse, "only a single result allowed for "
510e305f43fSdrh        "a SELECT that is part of an expression");
511e305f43fSdrh     return 1;
512e305f43fSdrh   }else{
513e305f43fSdrh     return 0;
514e305f43fSdrh   }
515e305f43fSdrh }
516c99130fdSdrh 
517c99130fdSdrh /*
5182282792aSdrh ** This routine generates the code for the inside of the inner loop
5192282792aSdrh ** of a SELECT.
52082c3d636Sdrh **
52138640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
52238640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
52338640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
52438640e15Sdrh ** datatypes for each column.
5252282792aSdrh */
526d2b3e23bSdrh static void selectInnerLoop(
5272282792aSdrh   Parse *pParse,          /* The parser context */
528df199a25Sdrh   Select *p,              /* The complete select statement being coded */
5292282792aSdrh   ExprList *pEList,       /* List of values being extracted */
53082c3d636Sdrh   int srcTab,             /* Pull data from this table */
531967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
5322282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
5332282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
5346c8c8ce0Sdanielk1977   SelectDest *pDest,      /* How to dispose of the results */
5352282792aSdrh   int iContinue,          /* Jump here to continue with next row */
536a9671a22Sdrh   int iBreak              /* Jump here to break out of the inner loop */
5372282792aSdrh ){
5382282792aSdrh   Vdbe *v = pParse->pVdbe;
539d847eaadSdrh   int i;
540ea48eb2eSdrh   int hasDistinct;        /* True if the DISTINCT keyword is present */
541d847eaadSdrh   int regResult;              /* Start of memory holding result set */
542d847eaadSdrh   int eDest = pDest->eDest;   /* How to dispose of results */
543d847eaadSdrh   int iParm = pDest->iParm;   /* First argument to disposal method */
544d847eaadSdrh   int nResultCol;             /* Number of result columns */
54538640e15Sdrh 
546d2b3e23bSdrh   if( v==0 ) return;
54738640e15Sdrh   assert( pEList!=0 );
548e49b146fSdrh   hasDistinct = distinct>=0;
549ea48eb2eSdrh   if( pOrderBy==0 && !hasDistinct ){
550b7654111Sdrh     codeOffset(v, p, iContinue);
551df199a25Sdrh   }
552df199a25Sdrh 
553967e8b73Sdrh   /* Pull the requested columns.
5542282792aSdrh   */
55538640e15Sdrh   if( nColumn>0 ){
556d847eaadSdrh     nResultCol = nColumn;
557a2a49dc9Sdrh   }else{
558d847eaadSdrh     nResultCol = pEList->nExpr;
559a2a49dc9Sdrh   }
5601ece7325Sdrh   if( pDest->iMem==0 ){
5610acb7e48Sdrh     pDest->iMem = pParse->nMem+1;
562ad27e761Sdrh     pDest->nMem = nResultCol;
5630acb7e48Sdrh     pParse->nMem += nResultCol;
564ad27e761Sdrh   }else if( pDest->nMem!=nResultCol ){
565995ae279Sdrh     /* This happens when two SELECTs of a compound SELECT have differing
566995ae279Sdrh     ** numbers of result columns.  The error message will be generated by
567995ae279Sdrh     ** a higher-level routine. */
568ad27e761Sdrh     return;
5691013c932Sdrh   }
5701ece7325Sdrh   regResult = pDest->iMem;
571a2a49dc9Sdrh   if( nColumn>0 ){
572967e8b73Sdrh     for(i=0; i<nColumn; i++){
573d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
57482c3d636Sdrh     }
5759ed1dfa8Sdanielk1977   }else if( eDest!=SRT_Exists ){
5769ed1dfa8Sdanielk1977     /* If the destination is an EXISTS(...) expression, the actual
5779ed1dfa8Sdanielk1977     ** values returned by the SELECT are not required.
5789ed1dfa8Sdanielk1977     */
5797d10d5a6Sdrh     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
580a2a49dc9Sdrh   }
581d847eaadSdrh   nColumn = nResultCol;
5822282792aSdrh 
583daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
584daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
585daffd0e5Sdrh   ** part of the result.
5862282792aSdrh   */
587ea48eb2eSdrh   if( hasDistinct ){
588f8875400Sdrh     assert( pEList!=0 );
589f8875400Sdrh     assert( pEList->nExpr==nColumn );
590d847eaadSdrh     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
591ea48eb2eSdrh     if( pOrderBy==0 ){
592b7654111Sdrh       codeOffset(v, p, iContinue);
593ea48eb2eSdrh     }
5942282792aSdrh   }
59582c3d636Sdrh 
5966c8c8ce0Sdanielk1977   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
597d2b3e23bSdrh     return;
598e305f43fSdrh   }
599e305f43fSdrh 
600c926afbcSdrh   switch( eDest ){
60182c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
60282c3d636Sdrh     ** table iParm.
6032282792aSdrh     */
60413449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
605c926afbcSdrh     case SRT_Union: {
6069cbf3425Sdrh       int r1;
6079cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
608d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
6099cbf3425Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
6109cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
611c926afbcSdrh       break;
612c926afbcSdrh     }
61382c3d636Sdrh 
61482c3d636Sdrh     /* Construct a record from the query result, but instead of
61582c3d636Sdrh     ** saving that record, use it as a key to delete elements from
61682c3d636Sdrh     ** the temporary table iParm.
61782c3d636Sdrh     */
618c926afbcSdrh     case SRT_Except: {
619e14006d0Sdrh       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
620c926afbcSdrh       break;
621c926afbcSdrh     }
6225338a5f7Sdanielk1977 #endif
6235338a5f7Sdanielk1977 
6245338a5f7Sdanielk1977     /* Store the result as data using a unique key.
6255338a5f7Sdanielk1977     */
6265338a5f7Sdanielk1977     case SRT_Table:
627b9bb7c18Sdrh     case SRT_EphemTab: {
628b7654111Sdrh       int r1 = sqlite3GetTempReg(pParse);
629d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
6305338a5f7Sdanielk1977       if( pOrderBy ){
631b7654111Sdrh         pushOntoSorter(pParse, pOrderBy, p, r1);
6325338a5f7Sdanielk1977       }else{
633b7654111Sdrh         int r2 = sqlite3GetTempReg(pParse);
634b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
635b7654111Sdrh         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
636b7654111Sdrh         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
637b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r2);
6385338a5f7Sdanielk1977       }
639b7654111Sdrh       sqlite3ReleaseTempReg(pParse, r1);
6405338a5f7Sdanielk1977       break;
6415338a5f7Sdanielk1977     }
6422282792aSdrh 
64393758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
6442282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
6452282792aSdrh     ** then there should be a single item on the stack.  Write this
6462282792aSdrh     ** item into the set table with bogus data.
6472282792aSdrh     */
648c926afbcSdrh     case SRT_Set: {
649967e8b73Sdrh       assert( nColumn==1 );
6506c8c8ce0Sdanielk1977       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
651c926afbcSdrh       if( pOrderBy ){
652de941c60Sdrh         /* At first glance you would think we could optimize out the
653de941c60Sdrh         ** ORDER BY in this case since the order of entries in the set
654de941c60Sdrh         ** does not matter.  But there might be a LIMIT clause, in which
655de941c60Sdrh         ** case the order does matter */
656d847eaadSdrh         pushOntoSorter(pParse, pOrderBy, p, regResult);
657c926afbcSdrh       }else{
658b7654111Sdrh         int r1 = sqlite3GetTempReg(pParse);
659d847eaadSdrh         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
660da250ea5Sdrh         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
661b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
662b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r1);
663c926afbcSdrh       }
664c926afbcSdrh       break;
665c926afbcSdrh     }
66682c3d636Sdrh 
667504b6989Sdrh     /* If any row exist in the result set, record that fact and abort.
668ec7429aeSdrh     */
669ec7429aeSdrh     case SRT_Exists: {
6704c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
671ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
672ec7429aeSdrh       break;
673ec7429aeSdrh     }
674ec7429aeSdrh 
6752282792aSdrh     /* If this is a scalar select that is part of an expression, then
6762282792aSdrh     ** store the results in the appropriate memory cell and break out
6772282792aSdrh     ** of the scan loop.
6782282792aSdrh     */
679c926afbcSdrh     case SRT_Mem: {
680967e8b73Sdrh       assert( nColumn==1 );
681c926afbcSdrh       if( pOrderBy ){
682d847eaadSdrh         pushOntoSorter(pParse, pOrderBy, p, regResult);
683c926afbcSdrh       }else{
684b21e7c70Sdrh         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
685ec7429aeSdrh         /* The LIMIT clause will jump out of the loop for us */
686c926afbcSdrh       }
687c926afbcSdrh       break;
688c926afbcSdrh     }
68993758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
6902282792aSdrh 
691c182d163Sdrh     /* Send the data to the callback function or to a subroutine.  In the
692c182d163Sdrh     ** case of a subroutine, the subroutine itself is responsible for
693c182d163Sdrh     ** popping the data from the stack.
694f46f905aSdrh     */
695e00ee6ebSdrh     case SRT_Coroutine:
6967d10d5a6Sdrh     case SRT_Output: {
697f46f905aSdrh       if( pOrderBy ){
698b7654111Sdrh         int r1 = sqlite3GetTempReg(pParse);
699d847eaadSdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
700b7654111Sdrh         pushOntoSorter(pParse, pOrderBy, p, r1);
701b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r1);
702e00ee6ebSdrh       }else if( eDest==SRT_Coroutine ){
70392b01d53Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
704c182d163Sdrh       }else{
705d847eaadSdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
706da250ea5Sdrh         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
707ac82fcf5Sdrh       }
708142e30dfSdrh       break;
709142e30dfSdrh     }
710142e30dfSdrh 
7116a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER)
712d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
713d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
714d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
715d7489c39Sdrh     ** about the actual results of the select.
716d7489c39Sdrh     */
717c926afbcSdrh     default: {
718f46f905aSdrh       assert( eDest==SRT_Discard );
719c926afbcSdrh       break;
720c926afbcSdrh     }
72193758c8dSdanielk1977 #endif
722c926afbcSdrh   }
723ec7429aeSdrh 
724ec7429aeSdrh   /* Jump to the end of the loop if the LIMIT is reached.
725ec7429aeSdrh   */
726e49b146fSdrh   if( p->iLimit ){
727e49b146fSdrh     assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
728e49b146fSdrh                             ** pushOntoSorter() would have cleared p->iLimit */
7298558cde1Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
7303c84ddffSdrh     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
731ec7429aeSdrh   }
73282c3d636Sdrh }
73382c3d636Sdrh 
73482c3d636Sdrh /*
735dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records
736dece1a84Sdrh ** the collating sequence for each expression in that expression list.
737dece1a84Sdrh **
7380342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
7390342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to
7400342b1f5Sdrh ** implement that clause.  If the ExprList is the result set of a SELECT
7410342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual
7420342b1f5Sdrh ** index to implement a DISTINCT test.
7430342b1f5Sdrh **
744dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
745dece1a84Sdrh ** function is responsible for seeing that this structure is eventually
74666a5167bSdrh ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
74766a5167bSdrh ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
748dece1a84Sdrh */
749dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
750dece1a84Sdrh   sqlite3 *db = pParse->db;
751dece1a84Sdrh   int nExpr;
752dece1a84Sdrh   KeyInfo *pInfo;
753dece1a84Sdrh   struct ExprList_item *pItem;
754dece1a84Sdrh   int i;
755dece1a84Sdrh 
756dece1a84Sdrh   nExpr = pList->nExpr;
75717435752Sdrh   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
758dece1a84Sdrh   if( pInfo ){
7592646da7eSdrh     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
760dece1a84Sdrh     pInfo->nField = nExpr;
76114db2665Sdanielk1977     pInfo->enc = ENC(db);
762dece1a84Sdrh     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
763dece1a84Sdrh       CollSeq *pColl;
764dece1a84Sdrh       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
765dece1a84Sdrh       if( !pColl ){
766dece1a84Sdrh         pColl = db->pDfltColl;
767dece1a84Sdrh       }
768dece1a84Sdrh       pInfo->aColl[i] = pColl;
769dece1a84Sdrh       pInfo->aSortOrder[i] = pItem->sortOrder;
770dece1a84Sdrh     }
771dece1a84Sdrh   }
772dece1a84Sdrh   return pInfo;
773dece1a84Sdrh }
774dece1a84Sdrh 
775dece1a84Sdrh 
776dece1a84Sdrh /*
777d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
778d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
779d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
780d8bc7086Sdrh ** routine generates the code needed to do that.
781d8bc7086Sdrh */
782c926afbcSdrh static void generateSortTail(
783cdd536f0Sdrh   Parse *pParse,    /* Parsing context */
784c926afbcSdrh   Select *p,        /* The SELECT statement */
785c926afbcSdrh   Vdbe *v,          /* Generate code into this VDBE */
786c926afbcSdrh   int nColumn,      /* Number of columns of data */
7876c8c8ce0Sdanielk1977   SelectDest *pDest /* Write the sorted results here */
788c926afbcSdrh ){
7890342b1f5Sdrh   int brk = sqlite3VdbeMakeLabel(v);
7900342b1f5Sdrh   int cont = sqlite3VdbeMakeLabel(v);
791d8bc7086Sdrh   int addr;
7920342b1f5Sdrh   int iTab;
79361fc595fSdrh   int pseudoTab = 0;
7940342b1f5Sdrh   ExprList *pOrderBy = p->pOrderBy;
795ffbc3088Sdrh 
7966c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
7976c8c8ce0Sdanielk1977   int iParm = pDest->iParm;
7986c8c8ce0Sdanielk1977 
7992d401ab8Sdrh   int regRow;
8002d401ab8Sdrh   int regRowid;
8012d401ab8Sdrh 
8029d2985c7Sdrh   iTab = pOrderBy->iECursor;
8037d10d5a6Sdrh   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
804cdd536f0Sdrh     pseudoTab = pParse->nTab++;
805cd3e8f7cSdanielk1977     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nColumn);
8067d10d5a6Sdrh     sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, eDest==SRT_Output);
807cdd536f0Sdrh   }
80866a5167bSdrh   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, brk);
809b7654111Sdrh   codeOffset(v, p, cont);
8102d401ab8Sdrh   regRow = sqlite3GetTempReg(pParse);
8112d401ab8Sdrh   regRowid = sqlite3GetTempReg(pParse);
8122d401ab8Sdrh   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
813c926afbcSdrh   switch( eDest ){
814c926afbcSdrh     case SRT_Table:
815b9bb7c18Sdrh     case SRT_EphemTab: {
8162d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
8172d401ab8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
8182d401ab8Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
819c926afbcSdrh       break;
820c926afbcSdrh     }
82193758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
822c926afbcSdrh     case SRT_Set: {
823c926afbcSdrh       assert( nColumn==1 );
824a7a8e14bSdanielk1977       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
825da250ea5Sdrh       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
826a7a8e14bSdanielk1977       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
827c926afbcSdrh       break;
828c926afbcSdrh     }
829c926afbcSdrh     case SRT_Mem: {
830c926afbcSdrh       assert( nColumn==1 );
831b21e7c70Sdrh       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
832ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
833c926afbcSdrh       break;
834c926afbcSdrh     }
83593758c8dSdanielk1977 #endif
8367d10d5a6Sdrh     case SRT_Output:
837e00ee6ebSdrh     case SRT_Coroutine: {
838ac82fcf5Sdrh       int i;
8392d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid);
8402d401ab8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid);
841ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
8429882d999Sdanielk1977         assert( regRow!=pDest->iMem+i );
8431013c932Sdrh         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
844ac82fcf5Sdrh       }
8457d10d5a6Sdrh       if( eDest==SRT_Output ){
8461013c932Sdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
847da250ea5Sdrh         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
848a9671a22Sdrh       }else{
84992b01d53Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
850ce665cf6Sdrh       }
851ac82fcf5Sdrh       break;
852ac82fcf5Sdrh     }
853c926afbcSdrh     default: {
854f46f905aSdrh       /* Do nothing */
855c926afbcSdrh       break;
856c926afbcSdrh     }
857c926afbcSdrh   }
8582d401ab8Sdrh   sqlite3ReleaseTempReg(pParse, regRow);
8592d401ab8Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
860ec7429aeSdrh 
861a9671a22Sdrh   /* LIMIT has been implemented by the pushOntoSorter() routine.
862ec7429aeSdrh   */
863a9671a22Sdrh   assert( p->iLimit==0 );
864ec7429aeSdrh 
865ec7429aeSdrh   /* The bottom of the loop
866ec7429aeSdrh   */
8670342b1f5Sdrh   sqlite3VdbeResolveLabel(v, cont);
86866a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
8690342b1f5Sdrh   sqlite3VdbeResolveLabel(v, brk);
8707d10d5a6Sdrh   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
87166a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
872cdd536f0Sdrh   }
873cdd536f0Sdrh 
874d8bc7086Sdrh }
875d8bc7086Sdrh 
876d8bc7086Sdrh /*
877517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
878517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
879e78e8284Sdrh **
880955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the
881955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The
882955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
883955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The
884955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is
885955de52cSdanielk1977 ** considered a column by this function.
886e78e8284Sdrh **
887955de52cSdanielk1977 **   SELECT col FROM tbl;
888955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl;
889955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl);
890955de52cSdanielk1977 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
891955de52cSdanielk1977 **
892955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL.
893fcb78a49Sdrh */
894955de52cSdanielk1977 static const char *columnType(
895955de52cSdanielk1977   NameContext *pNC,
896955de52cSdanielk1977   Expr *pExpr,
897955de52cSdanielk1977   const char **pzOriginDb,
898955de52cSdanielk1977   const char **pzOriginTab,
899955de52cSdanielk1977   const char **pzOriginCol
900955de52cSdanielk1977 ){
901955de52cSdanielk1977   char const *zType = 0;
902955de52cSdanielk1977   char const *zOriginDb = 0;
903955de52cSdanielk1977   char const *zOriginTab = 0;
904955de52cSdanielk1977   char const *zOriginCol = 0;
905517eb646Sdanielk1977   int j;
906b3bce662Sdanielk1977   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
9075338a5f7Sdanielk1977 
90800e279d9Sdanielk1977   switch( pExpr->op ){
90930bcf5dbSdrh     case TK_AGG_COLUMN:
91000e279d9Sdanielk1977     case TK_COLUMN: {
911955de52cSdanielk1977       /* The expression is a column. Locate the table the column is being
912955de52cSdanielk1977       ** extracted from in NameContext.pSrcList. This table may be real
913955de52cSdanielk1977       ** database table or a subquery.
914955de52cSdanielk1977       */
915955de52cSdanielk1977       Table *pTab = 0;            /* Table structure column is extracted from */
916955de52cSdanielk1977       Select *pS = 0;             /* Select the column is extracted from */
917955de52cSdanielk1977       int iCol = pExpr->iColumn;  /* Index of column in pTab */
918b3bce662Sdanielk1977       while( pNC && !pTab ){
919b3bce662Sdanielk1977         SrcList *pTabList = pNC->pSrcList;
920b3bce662Sdanielk1977         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
921b3bce662Sdanielk1977         if( j<pTabList->nSrc ){
9226a3ea0e6Sdrh           pTab = pTabList->a[j].pTab;
923955de52cSdanielk1977           pS = pTabList->a[j].pSelect;
924b3bce662Sdanielk1977         }else{
925b3bce662Sdanielk1977           pNC = pNC->pNext;
926b3bce662Sdanielk1977         }
927b3bce662Sdanielk1977       }
928955de52cSdanielk1977 
9297e62779aSdrh       if( pTab==0 ){
9307e62779aSdrh         /* FIX ME:
9317e62779aSdrh         ** This can occurs if you have something like "SELECT new.x;" inside
9327e62779aSdrh         ** a trigger.  In other words, if you reference the special "new"
9337e62779aSdrh         ** table in the result set of a select.  We do not have a good way
9347e62779aSdrh         ** to find the actual table type, so call it "TEXT".  This is really
9357e62779aSdrh         ** something of a bug, but I do not know how to fix it.
9367e62779aSdrh         **
9377e62779aSdrh         ** This code does not produce the correct answer - it just prevents
9387e62779aSdrh         ** a segfault.  See ticket #1229.
9397e62779aSdrh         */
9407e62779aSdrh         zType = "TEXT";
9417e62779aSdrh         break;
9427e62779aSdrh       }
943955de52cSdanielk1977 
944b3bce662Sdanielk1977       assert( pTab );
945955de52cSdanielk1977       if( pS ){
946955de52cSdanielk1977         /* The "table" is actually a sub-select or a view in the FROM clause
947955de52cSdanielk1977         ** of the SELECT statement. Return the declaration type and origin
948955de52cSdanielk1977         ** data for the result-set column of the sub-select.
949955de52cSdanielk1977         */
950955de52cSdanielk1977         if( iCol>=0 && iCol<pS->pEList->nExpr ){
951955de52cSdanielk1977           /* If iCol is less than zero, then the expression requests the
952955de52cSdanielk1977           ** rowid of the sub-select or view. This expression is legal (see
953955de52cSdanielk1977           ** test case misc2.2.2) - it always evaluates to NULL.
954955de52cSdanielk1977           */
955955de52cSdanielk1977           NameContext sNC;
956955de52cSdanielk1977           Expr *p = pS->pEList->a[iCol].pExpr;
957955de52cSdanielk1977           sNC.pSrcList = pS->pSrc;
958955de52cSdanielk1977           sNC.pNext = 0;
959955de52cSdanielk1977           sNC.pParse = pNC->pParse;
960955de52cSdanielk1977           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
961955de52cSdanielk1977         }
9624b2688abSdanielk1977       }else if( pTab->pSchema ){
963955de52cSdanielk1977         /* A real table */
964955de52cSdanielk1977         assert( !pS );
965fcb78a49Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
966fcb78a49Sdrh         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
967fcb78a49Sdrh         if( iCol<0 ){
968fcb78a49Sdrh           zType = "INTEGER";
969955de52cSdanielk1977           zOriginCol = "rowid";
970fcb78a49Sdrh         }else{
971fcb78a49Sdrh           zType = pTab->aCol[iCol].zType;
972955de52cSdanielk1977           zOriginCol = pTab->aCol[iCol].zName;
973955de52cSdanielk1977         }
974955de52cSdanielk1977         zOriginTab = pTab->zName;
975955de52cSdanielk1977         if( pNC->pParse ){
976955de52cSdanielk1977           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
977955de52cSdanielk1977           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
978955de52cSdanielk1977         }
979fcb78a49Sdrh       }
98000e279d9Sdanielk1977       break;
981736c22b8Sdrh     }
98293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
98300e279d9Sdanielk1977     case TK_SELECT: {
984955de52cSdanielk1977       /* The expression is a sub-select. Return the declaration type and
985955de52cSdanielk1977       ** origin info for the single column in the result set of the SELECT
986955de52cSdanielk1977       ** statement.
987955de52cSdanielk1977       */
988b3bce662Sdanielk1977       NameContext sNC;
98900e279d9Sdanielk1977       Select *pS = pExpr->pSelect;
990955de52cSdanielk1977       Expr *p = pS->pEList->a[0].pExpr;
991955de52cSdanielk1977       sNC.pSrcList = pS->pSrc;
992b3bce662Sdanielk1977       sNC.pNext = pNC;
993955de52cSdanielk1977       sNC.pParse = pNC->pParse;
994955de52cSdanielk1977       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
99500e279d9Sdanielk1977       break;
996fcb78a49Sdrh     }
99793758c8dSdanielk1977 #endif
99800e279d9Sdanielk1977   }
99900e279d9Sdanielk1977 
1000955de52cSdanielk1977   if( pzOriginDb ){
1001955de52cSdanielk1977     assert( pzOriginTab && pzOriginCol );
1002955de52cSdanielk1977     *pzOriginDb = zOriginDb;
1003955de52cSdanielk1977     *pzOriginTab = zOriginTab;
1004955de52cSdanielk1977     *pzOriginCol = zOriginCol;
1005955de52cSdanielk1977   }
1006517eb646Sdanielk1977   return zType;
1007517eb646Sdanielk1977 }
1008517eb646Sdanielk1977 
1009517eb646Sdanielk1977 /*
1010517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
1011517eb646Sdanielk1977 ** in the result set.
1012517eb646Sdanielk1977 */
1013517eb646Sdanielk1977 static void generateColumnTypes(
1014517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
1015517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
1016517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
1017517eb646Sdanielk1977 ){
10183f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE
1019517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
1020517eb646Sdanielk1977   int i;
1021b3bce662Sdanielk1977   NameContext sNC;
1022b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
1023955de52cSdanielk1977   sNC.pParse = pParse;
1024517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
1025517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
10263f913576Sdrh     const char *zType;
10273f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1028955de52cSdanielk1977     const char *zOrigDb = 0;
1029955de52cSdanielk1977     const char *zOrigTab = 0;
1030955de52cSdanielk1977     const char *zOrigCol = 0;
10313f913576Sdrh     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
1032955de52cSdanielk1977 
103385b623f2Sdrh     /* The vdbe must make its own copy of the column-type and other
10344b1ae99dSdanielk1977     ** column specific strings, in case the schema is reset before this
10354b1ae99dSdanielk1977     ** virtual machine is deleted.
1036fbcd585fSdanielk1977     */
103766a5167bSdrh     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P4_TRANSIENT);
103866a5167bSdrh     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P4_TRANSIENT);
103966a5167bSdrh     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P4_TRANSIENT);
10403f913576Sdrh #else
10413f913576Sdrh     zType = columnType(&sNC, p, 0, 0, 0);
10423f913576Sdrh #endif
10433f913576Sdrh     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P4_TRANSIENT);
1044fcb78a49Sdrh   }
10453f913576Sdrh #endif /* SQLITE_OMIT_DECLTYPE */
1046fcb78a49Sdrh }
1047fcb78a49Sdrh 
1048fcb78a49Sdrh /*
1049fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
1050fcb78a49Sdrh ** in the result set.  This information is used to provide the
1051fcabd464Sdrh ** azCol[] values in the callback.
105282c3d636Sdrh */
1053832508b7Sdrh static void generateColumnNames(
1054832508b7Sdrh   Parse *pParse,      /* Parser context */
1055ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
1056832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
1057832508b7Sdrh ){
1058d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
10596a3ea0e6Sdrh   int i, j;
10609bb575fdSdrh   sqlite3 *db = pParse->db;
1061fcabd464Sdrh   int fullNames, shortNames;
1062fcabd464Sdrh 
1063fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN
10643cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
10653cf86063Sdanielk1977   if( pParse->explain ){
106661de0d1bSdanielk1977     return;
10673cf86063Sdanielk1977   }
10685338a5f7Sdanielk1977 #endif
10693cf86063Sdanielk1977 
1070d6502758Sdrh   assert( v!=0 );
107117435752Sdrh   if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
1072d8bc7086Sdrh   pParse->colNamesSet = 1;
1073fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
1074fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
107522322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
107682c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
107782c3d636Sdrh     Expr *p;
10785a38705eSdrh     p = pEList->a[i].pExpr;
10795a38705eSdrh     if( p==0 ) continue;
108082c3d636Sdrh     if( pEList->a[i].zName ){
108182c3d636Sdrh       char *zName = pEList->a[i].zName;
1082955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
1083*f018cc2eSdrh     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
10846a3ea0e6Sdrh       Table *pTab;
108597665873Sdrh       char *zCol;
10868aff1015Sdrh       int iCol = p->iColumn;
10876a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
10886a3ea0e6Sdrh       assert( j<pTabList->nSrc );
10896a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
10908aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
109197665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1092b1363206Sdrh       if( iCol<0 ){
109347a6db2bSdrh         zCol = "rowid";
1094b1363206Sdrh       }else{
1095b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
1096b1363206Sdrh       }
1097e49b146fSdrh       if( !shortNames && !fullNames ){
1098955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
1099fcabd464Sdrh       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
110082c3d636Sdrh         char *zName = 0;
110182c3d636Sdrh         char *zTab;
110282c3d636Sdrh 
11036a3ea0e6Sdrh         zTab = pTabList->a[j].zAlias;
1104fcabd464Sdrh         if( fullNames || zTab==0 ) zTab = pTab->zName;
1105f089aa45Sdrh         zName = sqlite3MPrintf(db, "%s.%s", zTab, zCol);
110666a5167bSdrh         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P4_DYNAMIC);
110782c3d636Sdrh       }else{
1108955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
110982c3d636Sdrh       }
11101bee3d7bSdrh     }else{
1111e49b146fSdrh       sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
111282c3d636Sdrh     }
111382c3d636Sdrh   }
111476d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
11155080aaa7Sdrh }
111682c3d636Sdrh 
111793758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
111882c3d636Sdrh /*
1119d8bc7086Sdrh ** Name of the connection operator, used for error messages.
1120d8bc7086Sdrh */
1121d8bc7086Sdrh static const char *selectOpName(int id){
1122d8bc7086Sdrh   char *z;
1123d8bc7086Sdrh   switch( id ){
1124d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
1125d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
1126d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
1127d8bc7086Sdrh     default:           z = "UNION";       break;
1128d8bc7086Sdrh   }
1129d8bc7086Sdrh   return z;
1130d8bc7086Sdrh }
113193758c8dSdanielk1977 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1132d8bc7086Sdrh 
1133d8bc7086Sdrh /*
11347d10d5a6Sdrh ** Given a an expression list (which is really the list of expressions
11357d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate
11367d10d5a6Sdrh ** column names for a table that would hold the expression list.
11377d10d5a6Sdrh **
11387d10d5a6Sdrh ** All column names will be unique.
11397d10d5a6Sdrh **
11407d10d5a6Sdrh ** Only the column names are computed.  Column.zType, Column.zColl,
11417d10d5a6Sdrh ** and other fields of Column are zeroed.
11427d10d5a6Sdrh **
11437d10d5a6Sdrh ** Return SQLITE_OK on success.  If a memory allocation error occurs,
11447d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
1145315555caSdrh */
11467d10d5a6Sdrh static int selectColumnsFromExprList(
11477d10d5a6Sdrh   Parse *pParse,          /* Parsing context */
11487d10d5a6Sdrh   ExprList *pEList,       /* Expr list from which to derive column names */
11497d10d5a6Sdrh   int *pnCol,             /* Write the number of columns here */
11507d10d5a6Sdrh   Column **paCol          /* Write the new column list here */
11517d10d5a6Sdrh ){
115217435752Sdrh   sqlite3 *db = pParse->db;
11537d10d5a6Sdrh   int i, j, cnt;
11547d10d5a6Sdrh   Column *aCol, *pCol;
11557d10d5a6Sdrh   int nCol;
1156a3460585Sdrh   Expr *p;
115791bb0eedSdrh   char *zName;
11582564ef97Sdrh   int nName;
115979d5f63fSdrh 
11607d10d5a6Sdrh   *pnCol = nCol = pEList->nExpr;
11617d10d5a6Sdrh   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
11627d10d5a6Sdrh   if( aCol==0 ) return SQLITE_NOMEM;
11637d10d5a6Sdrh   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
116479d5f63fSdrh     /* Get an appropriate name for the column
116579d5f63fSdrh     */
116679d5f63fSdrh     p = pEList->a[i].pExpr;
1167290c1948Sdrh     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
116891bb0eedSdrh     if( (zName = pEList->a[i].zName)!=0 ){
116979d5f63fSdrh       /* If the column contains an "AS <name>" phrase, use <name> as the name */
117017435752Sdrh       zName = sqlite3DbStrDup(db, zName);
11717d10d5a6Sdrh     }else{
11727d10d5a6Sdrh       Expr *pCol = p;
1173f0209f74Sdrh       Table *pTab;
11747d10d5a6Sdrh       while( pCol->op==TK_DOT ) pCol = pCol->pRight;
1175f0209f74Sdrh       if( pCol->op==TK_COLUMN && (pTab = pCol->pTab)!=0 ){
117693a960a0Sdrh         /* For columns use the column name name */
11777d10d5a6Sdrh         int iCol = pCol->iColumn;
1178f0209f74Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
1179f0209f74Sdrh         zName = sqlite3MPrintf(db, "%s",
1180f0209f74Sdrh                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
118193a960a0Sdrh       }else{
118279d5f63fSdrh         /* Use the original text of the column expression as its name */
11837d10d5a6Sdrh         zName = sqlite3MPrintf(db, "%T", &pCol->span);
11847d10d5a6Sdrh       }
118522f70c32Sdrh     }
11867ce72f69Sdrh     if( db->mallocFailed ){
1187633e6d57Sdrh       sqlite3DbFree(db, zName);
11887ce72f69Sdrh       break;
1189dd5b2fa5Sdrh     }
11907751940dSdanielk1977     sqlite3Dequote(zName);
119179d5f63fSdrh 
119279d5f63fSdrh     /* Make sure the column name is unique.  If the name is not unique,
119379d5f63fSdrh     ** append a integer to the name so that it becomes unique.
119479d5f63fSdrh     */
11952564ef97Sdrh     nName = strlen(zName);
119679d5f63fSdrh     for(j=cnt=0; j<i; j++){
119779d5f63fSdrh       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
1198633e6d57Sdrh         char *zNewName;
11992564ef97Sdrh         zName[nName] = 0;
1200633e6d57Sdrh         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
1201633e6d57Sdrh         sqlite3DbFree(db, zName);
1202633e6d57Sdrh         zName = zNewName;
120379d5f63fSdrh         j = -1;
1204dd5b2fa5Sdrh         if( zName==0 ) break;
120579d5f63fSdrh       }
120679d5f63fSdrh     }
120791bb0eedSdrh     pCol->zName = zName;
12087d10d5a6Sdrh   }
12097d10d5a6Sdrh   if( db->mallocFailed ){
12107d10d5a6Sdrh     int j;
12117d10d5a6Sdrh     for(j=0; j<i; j++){
12127d10d5a6Sdrh       sqlite3DbFree(db, aCol[j].zName);
12137d10d5a6Sdrh     }
12147d10d5a6Sdrh     sqlite3DbFree(db, aCol);
12157d10d5a6Sdrh     *paCol = 0;
12167d10d5a6Sdrh     *pnCol = 0;
12177d10d5a6Sdrh     return SQLITE_NOMEM;
12187d10d5a6Sdrh   }
12197d10d5a6Sdrh   return SQLITE_OK;
12207d10d5a6Sdrh }
1221e014a838Sdanielk1977 
12227d10d5a6Sdrh /*
12237d10d5a6Sdrh ** Add type and collation information to a column list based on
12247d10d5a6Sdrh ** a SELECT statement.
12257d10d5a6Sdrh **
12267d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList().
12277d10d5a6Sdrh ** The column list has only names, not types or collations.  This
12287d10d5a6Sdrh ** routine goes through and adds the types and collations.
12297d10d5a6Sdrh **
12307d10d5a6Sdrh ** This routine requires that all indentifiers in the SELECT
12317d10d5a6Sdrh ** statement be resolved.
123279d5f63fSdrh */
12337d10d5a6Sdrh static void selectAddColumnTypeAndCollation(
12347d10d5a6Sdrh   Parse *pParse,        /* Parsing contexts */
12357d10d5a6Sdrh   int nCol,             /* Number of columns */
12367d10d5a6Sdrh   Column *aCol,         /* List of columns */
12377d10d5a6Sdrh   Select *pSelect       /* SELECT used to determine types and collations */
12387d10d5a6Sdrh ){
12397d10d5a6Sdrh   sqlite3 *db = pParse->db;
12407d10d5a6Sdrh   NameContext sNC;
12417d10d5a6Sdrh   Column *pCol;
12427d10d5a6Sdrh   CollSeq *pColl;
12437d10d5a6Sdrh   int i;
12447d10d5a6Sdrh   Expr *p;
12457d10d5a6Sdrh   struct ExprList_item *a;
12467d10d5a6Sdrh 
12477d10d5a6Sdrh   assert( pSelect!=0 );
12487d10d5a6Sdrh   assert( (pSelect->selFlags & SF_Resolved)!=0 );
12497d10d5a6Sdrh   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
12507d10d5a6Sdrh   if( db->mallocFailed ) return;
1251c43e8be8Sdrh   memset(&sNC, 0, sizeof(sNC));
1252b3bce662Sdanielk1977   sNC.pSrcList = pSelect->pSrc;
12537d10d5a6Sdrh   a = pSelect->pEList->a;
12547d10d5a6Sdrh   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
12557d10d5a6Sdrh     p = a[i].pExpr;
12567d10d5a6Sdrh     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
1257c60e9b82Sdanielk1977     pCol->affinity = sqlite3ExprAffinity(p);
1258b3bf556eSdanielk1977     pColl = sqlite3ExprCollSeq(pParse, p);
1259b3bf556eSdanielk1977     if( pColl ){
126017435752Sdrh       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
12610202b29eSdanielk1977     }
126222f70c32Sdrh   }
12637d10d5a6Sdrh }
12647d10d5a6Sdrh 
12657d10d5a6Sdrh /*
12667d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes
12677d10d5a6Sdrh ** the result set of that SELECT.
12687d10d5a6Sdrh */
12697d10d5a6Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
12707d10d5a6Sdrh   Table *pTab;
12717d10d5a6Sdrh   sqlite3 *db = pParse->db;
12727d10d5a6Sdrh   int savedFlags;
12737d10d5a6Sdrh 
12747d10d5a6Sdrh   savedFlags = db->flags;
12757d10d5a6Sdrh   db->flags &= ~SQLITE_FullColNames;
12767d10d5a6Sdrh   db->flags |= SQLITE_ShortColNames;
12777d10d5a6Sdrh   sqlite3SelectPrep(pParse, pSelect, 0);
12787d10d5a6Sdrh   if( pParse->nErr ) return 0;
12797d10d5a6Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
12807d10d5a6Sdrh   db->flags = savedFlags;
12817d10d5a6Sdrh   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
12827d10d5a6Sdrh   if( pTab==0 ){
12837d10d5a6Sdrh     return 0;
12847d10d5a6Sdrh   }
12857d10d5a6Sdrh   pTab->db = db;
12867d10d5a6Sdrh   pTab->nRef = 1;
12877d10d5a6Sdrh   pTab->zName = 0;
12887d10d5a6Sdrh   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
12897d10d5a6Sdrh   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
129022f70c32Sdrh   pTab->iPKey = -1;
12917ce72f69Sdrh   if( db->mallocFailed ){
12927ce72f69Sdrh     sqlite3DeleteTable(pTab);
12937ce72f69Sdrh     return 0;
12947ce72f69Sdrh   }
129522f70c32Sdrh   return pTab;
129622f70c32Sdrh }
129722f70c32Sdrh 
129822f70c32Sdrh /*
1299d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1300d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1301d8bc7086Sdrh */
13024adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1303d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1304d8bc7086Sdrh   if( v==0 ){
13054adee20fSdanielk1977     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1306949f9cd5Sdrh #ifndef SQLITE_OMIT_TRACE
1307949f9cd5Sdrh     if( v ){
1308949f9cd5Sdrh       sqlite3VdbeAddOp0(v, OP_Trace);
1309949f9cd5Sdrh     }
1310949f9cd5Sdrh #endif
1311d8bc7086Sdrh   }
1312d8bc7086Sdrh   return v;
1313d8bc7086Sdrh }
1314d8bc7086Sdrh 
131515007a99Sdrh 
1316d8bc7086Sdrh /*
13177b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
1318ec7429aeSdrh ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
13197b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
1320a2dc3b1aSdanielk1977 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1321a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute
1322a2dc3b1aSdanielk1977 ** the limit and offset.  If there is no limit and/or offset, then
1323a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative.
13247b58daeaSdrh **
1325d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if
1326ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset.  iLimit and
13277b58daeaSdrh ** iOffset should have been preset to appropriate default values
13287b58daeaSdrh ** (usually but not always -1) prior to calling this routine.
1329ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
13307b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
13317b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
13327b58daeaSdrh ** SELECT statements.
13337b58daeaSdrh */
1334ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
133502afc861Sdrh   Vdbe *v = 0;
133602afc861Sdrh   int iLimit = 0;
133715007a99Sdrh   int iOffset;
1338b7654111Sdrh   int addr1;
13390acb7e48Sdrh   if( p->iLimit ) return;
134015007a99Sdrh 
13417b58daeaSdrh   /*
13427b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
13437b58daeaSdrh   ** contraversy about what the correct behavior should be.
13447b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
13457b58daeaSdrh   ** no rows.
13467b58daeaSdrh   */
1347a2dc3b1aSdanielk1977   if( p->pLimit ){
13480a07c107Sdrh     p->iLimit = iLimit = ++pParse->nMem;
134915007a99Sdrh     v = sqlite3GetVdbe(pParse);
13507b58daeaSdrh     if( v==0 ) return;
1351b7654111Sdrh     sqlite3ExprCode(pParse, p->pLimit, iLimit);
1352b7654111Sdrh     sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
1353d4e70ebdSdrh     VdbeComment((v, "LIMIT counter"));
13543c84ddffSdrh     sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
13557b58daeaSdrh   }
1356a2dc3b1aSdanielk1977   if( p->pOffset ){
13570a07c107Sdrh     p->iOffset = iOffset = ++pParse->nMem;
1358b7654111Sdrh     if( p->pLimit ){
1359b7654111Sdrh       pParse->nMem++;   /* Allocate an extra register for limit+offset */
1360b7654111Sdrh     }
136115007a99Sdrh     v = sqlite3GetVdbe(pParse);
13627b58daeaSdrh     if( v==0 ) return;
1363b7654111Sdrh     sqlite3ExprCode(pParse, p->pOffset, iOffset);
1364b7654111Sdrh     sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
1365d4e70ebdSdrh     VdbeComment((v, "OFFSET counter"));
13663c84ddffSdrh     addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
1367b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
136815007a99Sdrh     sqlite3VdbeJumpHere(v, addr1);
1369d59ba6ceSdrh     if( p->pLimit ){
1370b7654111Sdrh       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
1371d4e70ebdSdrh       VdbeComment((v, "LIMIT+OFFSET"));
1372b7654111Sdrh       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
1373b7654111Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
1374b7654111Sdrh       sqlite3VdbeJumpHere(v, addr1);
1375b7654111Sdrh     }
1376d59ba6ceSdrh   }
13777b58daeaSdrh }
13787b58daeaSdrh 
1379b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1380fbc4ee7bSdrh /*
1381fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
1382fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
1383fbc4ee7bSdrh ** the column has no default collating sequence.
1384fbc4ee7bSdrh **
1385fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
1386fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
1387fbc4ee7bSdrh */
1388dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1389fbc4ee7bSdrh   CollSeq *pRet;
1390dc1bdc4fSdanielk1977   if( p->pPrior ){
1391dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1392fbc4ee7bSdrh   }else{
1393fbc4ee7bSdrh     pRet = 0;
1394dc1bdc4fSdanielk1977   }
1395fbc4ee7bSdrh   if( pRet==0 ){
1396dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1397dc1bdc4fSdanielk1977   }
1398dc1bdc4fSdanielk1977   return pRet;
1399d3d39e93Sdrh }
1400b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1401d3d39e93Sdrh 
1402b21e7c70Sdrh /* Forward reference */
1403b21e7c70Sdrh static int multiSelectOrderBy(
1404b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
1405b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
1406a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
1407b21e7c70Sdrh );
1408b21e7c70Sdrh 
1409b21e7c70Sdrh 
1410b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1411d3d39e93Sdrh /*
141216ee60ffSdrh ** This routine is called to process a compound query form from
141316ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
141416ee60ffSdrh ** INTERSECT
1415c926afbcSdrh **
1416e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1417e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1418e78e8284Sdrh ** in which case this routine will be called recursively.
1419e78e8284Sdrh **
1420e78e8284Sdrh ** The results of the total query are to be written into a destination
1421e78e8284Sdrh ** of type eDest with parameter iParm.
1422e78e8284Sdrh **
1423e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1424e78e8284Sdrh **
1425e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1426e78e8284Sdrh **
1427e78e8284Sdrh ** This statement is parsed up as follows:
1428e78e8284Sdrh **
1429e78e8284Sdrh **     SELECT c FROM t3
1430e78e8284Sdrh **      |
1431e78e8284Sdrh **      `----->  SELECT b FROM t2
1432e78e8284Sdrh **                |
14334b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1434e78e8284Sdrh **
1435e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1436e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1437e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1438e78e8284Sdrh **
1439e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1440e78e8284Sdrh ** individual selects always group from left to right.
144182c3d636Sdrh */
144284ac9d02Sdanielk1977 static int multiSelect(
1443fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
1444fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
1445a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
144684ac9d02Sdanielk1977 ){
144784ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
144810e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
144910e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
14501013c932Sdrh   SelectDest dest;      /* Alternative data destination */
1451eca7e01aSdanielk1977   Select *pDelete = 0;  /* Chain of simple selects to delete */
1452633e6d57Sdrh   sqlite3 *db;          /* Database connection */
145382c3d636Sdrh 
14547b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1455fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
145682c3d636Sdrh   */
1457701bb3b4Sdrh   assert( p && p->pPrior );  /* Calling function guarantees this much */
1458633e6d57Sdrh   db = pParse->db;
1459d8bc7086Sdrh   pPrior = p->pPrior;
14600342b1f5Sdrh   assert( pPrior->pRightmost!=pPrior );
14610342b1f5Sdrh   assert( pPrior->pRightmost==p->pRightmost );
1462bc10377aSdrh   dest = *pDest;
1463d8bc7086Sdrh   if( pPrior->pOrderBy ){
14644adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1465da93d238Sdrh       selectOpName(p->op));
146684ac9d02Sdanielk1977     rc = 1;
146784ac9d02Sdanielk1977     goto multi_select_end;
146882c3d636Sdrh   }
1469a2dc3b1aSdanielk1977   if( pPrior->pLimit ){
14704adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
14717b58daeaSdrh       selectOpName(p->op));
147284ac9d02Sdanielk1977     rc = 1;
147384ac9d02Sdanielk1977     goto multi_select_end;
14747b58daeaSdrh   }
147582c3d636Sdrh 
14764adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
1477701bb3b4Sdrh   assert( v!=0 );  /* The VDBE already created by calling function */
1478d8bc7086Sdrh 
14791cc3d75fSdrh   /* Create the destination temporary table if necessary
14801cc3d75fSdrh   */
14816c8c8ce0Sdanielk1977   if( dest.eDest==SRT_EphemTab ){
1482b4964b72Sdanielk1977     assert( p->pEList );
1483f6e369a1Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
14846c8c8ce0Sdanielk1977     dest.eDest = SRT_Table;
14851cc3d75fSdrh   }
14861cc3d75fSdrh 
1487f6e369a1Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
1488f6e369a1Sdrh   ** in their result sets.
1489f6e369a1Sdrh   */
1490f6e369a1Sdrh   assert( p->pEList && pPrior->pEList );
1491f6e369a1Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
1492f6e369a1Sdrh     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
1493f6e369a1Sdrh       " do not have the same number of result columns", selectOpName(p->op));
1494f6e369a1Sdrh     rc = 1;
1495f6e369a1Sdrh     goto multi_select_end;
1496f6e369a1Sdrh   }
1497f6e369a1Sdrh 
1498a9671a22Sdrh   /* Compound SELECTs that have an ORDER BY clause are handled separately.
1499a9671a22Sdrh   */
1500f6e369a1Sdrh   if( p->pOrderBy ){
1501a9671a22Sdrh     return multiSelectOrderBy(pParse, p, pDest);
1502f6e369a1Sdrh   }
1503f6e369a1Sdrh 
1504f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1505d8bc7086Sdrh   */
150682c3d636Sdrh   switch( p->op ){
1507f46f905aSdrh     case TK_ALL: {
1508ec7429aeSdrh       int addr = 0;
1509a2dc3b1aSdanielk1977       assert( !pPrior->pLimit );
1510a2dc3b1aSdanielk1977       pPrior->pLimit = p->pLimit;
1511a2dc3b1aSdanielk1977       pPrior->pOffset = p->pOffset;
15127d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &dest);
1513ad68cb6bSdanielk1977       p->pLimit = 0;
1514ad68cb6bSdanielk1977       p->pOffset = 0;
151584ac9d02Sdanielk1977       if( rc ){
151684ac9d02Sdanielk1977         goto multi_select_end;
151784ac9d02Sdanielk1977       }
1518f46f905aSdrh       p->pPrior = 0;
15197b58daeaSdrh       p->iLimit = pPrior->iLimit;
15207b58daeaSdrh       p->iOffset = pPrior->iOffset;
152192b01d53Sdrh       if( p->iLimit ){
15223c84ddffSdrh         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
1523d4e70ebdSdrh         VdbeComment((v, "Jump ahead if LIMIT reached"));
1524ec7429aeSdrh       }
15257d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &dest);
1526eca7e01aSdanielk1977       pDelete = p->pPrior;
1527f46f905aSdrh       p->pPrior = pPrior;
152884ac9d02Sdanielk1977       if( rc ){
152984ac9d02Sdanielk1977         goto multi_select_end;
153084ac9d02Sdanielk1977       }
1531ec7429aeSdrh       if( addr ){
1532ec7429aeSdrh         sqlite3VdbeJumpHere(v, addr);
1533ec7429aeSdrh       }
1534f46f905aSdrh       break;
1535f46f905aSdrh     }
153682c3d636Sdrh     case TK_EXCEPT:
153782c3d636Sdrh     case TK_UNION: {
1538d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1539742f947bSdanielk1977       int op = 0;      /* One of the SRT_ operations to apply to self */
1540d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
1541a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
1542dc1bdc4fSdanielk1977       int addr;
15436c8c8ce0Sdanielk1977       SelectDest uniondest;
154482c3d636Sdrh 
154593a960a0Sdrh       priorOp = SRT_Union;
1546a9671a22Sdrh       if( dest.eDest==priorOp && !p->pLimit && !p->pOffset ){
1547d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1548c926afbcSdrh         ** right.
1549d8bc7086Sdrh         */
15506c8c8ce0Sdanielk1977         unionTab = dest.iParm;
155182c3d636Sdrh       }else{
1552d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1553d8bc7086Sdrh         ** intermediate results.
1554d8bc7086Sdrh         */
155582c3d636Sdrh         unionTab = pParse->nTab++;
155693a960a0Sdrh         assert( p->pOrderBy==0 );
155766a5167bSdrh         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
1558b9bb7c18Sdrh         assert( p->addrOpenEphm[0] == -1 );
1559b9bb7c18Sdrh         p->addrOpenEphm[0] = addr;
15607d10d5a6Sdrh         p->pRightmost->selFlags |= SF_UsesEphemeral;
156184ac9d02Sdanielk1977         assert( p->pEList );
1562d8bc7086Sdrh       }
1563d8bc7086Sdrh 
1564d8bc7086Sdrh       /* Code the SELECT statements to our left
1565d8bc7086Sdrh       */
1566b3bce662Sdanielk1977       assert( !pPrior->pOrderBy );
15671013c932Sdrh       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
15687d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &uniondest);
156984ac9d02Sdanielk1977       if( rc ){
157084ac9d02Sdanielk1977         goto multi_select_end;
157184ac9d02Sdanielk1977       }
1572d8bc7086Sdrh 
1573d8bc7086Sdrh       /* Code the current SELECT statement
1574d8bc7086Sdrh       */
15754cfb22f7Sdrh       if( p->op==TK_EXCEPT ){
15764cfb22f7Sdrh         op = SRT_Except;
15774cfb22f7Sdrh       }else{
15784cfb22f7Sdrh         assert( p->op==TK_UNION );
15794cfb22f7Sdrh         op = SRT_Union;
1580d8bc7086Sdrh       }
158182c3d636Sdrh       p->pPrior = 0;
1582a2dc3b1aSdanielk1977       pLimit = p->pLimit;
1583a2dc3b1aSdanielk1977       p->pLimit = 0;
1584a2dc3b1aSdanielk1977       pOffset = p->pOffset;
1585a2dc3b1aSdanielk1977       p->pOffset = 0;
15866c8c8ce0Sdanielk1977       uniondest.eDest = op;
15877d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &uniondest);
15885bd1bf2eSdrh       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
15895bd1bf2eSdrh       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
1590633e6d57Sdrh       sqlite3ExprListDelete(db, p->pOrderBy);
1591eca7e01aSdanielk1977       pDelete = p->pPrior;
159282c3d636Sdrh       p->pPrior = pPrior;
1593a9671a22Sdrh       p->pOrderBy = 0;
1594633e6d57Sdrh       sqlite3ExprDelete(db, p->pLimit);
1595a2dc3b1aSdanielk1977       p->pLimit = pLimit;
1596a2dc3b1aSdanielk1977       p->pOffset = pOffset;
159792b01d53Sdrh       p->iLimit = 0;
159892b01d53Sdrh       p->iOffset = 0;
159984ac9d02Sdanielk1977       if( rc ){
160084ac9d02Sdanielk1977         goto multi_select_end;
160184ac9d02Sdanielk1977       }
160284ac9d02Sdanielk1977 
1603d8bc7086Sdrh 
1604d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1605d8bc7086Sdrh       ** it is that we currently need.
1606d8bc7086Sdrh       */
16076c8c8ce0Sdanielk1977       if( dest.eDest!=priorOp || unionTab!=dest.iParm ){
16086b56344dSdrh         int iCont, iBreak, iStart;
160982c3d636Sdrh         assert( p->pEList );
16107d10d5a6Sdrh         if( dest.eDest==SRT_Output ){
161192378253Sdrh           Select *pFirst = p;
161292378253Sdrh           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
161392378253Sdrh           generateColumnNames(pParse, 0, pFirst->pEList);
161441202ccaSdrh         }
16154adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
16164adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
1617ec7429aeSdrh         computeLimitRegisters(pParse, p, iBreak);
161866a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
16194adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
1620d2b3e23bSdrh         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
1621a9671a22Sdrh                         0, -1, &dest, iCont, iBreak);
16224adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
162366a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
16244adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
162566a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
162682c3d636Sdrh       }
162782c3d636Sdrh       break;
162882c3d636Sdrh     }
162982c3d636Sdrh     case TK_INTERSECT: {
163082c3d636Sdrh       int tab1, tab2;
16316b56344dSdrh       int iCont, iBreak, iStart;
1632a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset;
1633dc1bdc4fSdanielk1977       int addr;
16341013c932Sdrh       SelectDest intersectdest;
16359cbf3425Sdrh       int r1;
163682c3d636Sdrh 
1637d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
16386206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
1639d8bc7086Sdrh       ** by allocating the tables we will need.
1640d8bc7086Sdrh       */
164182c3d636Sdrh       tab1 = pParse->nTab++;
164282c3d636Sdrh       tab2 = pParse->nTab++;
164393a960a0Sdrh       assert( p->pOrderBy==0 );
1644dc1bdc4fSdanielk1977 
164566a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
1646b9bb7c18Sdrh       assert( p->addrOpenEphm[0] == -1 );
1647b9bb7c18Sdrh       p->addrOpenEphm[0] = addr;
16487d10d5a6Sdrh       p->pRightmost->selFlags |= SF_UsesEphemeral;
164984ac9d02Sdanielk1977       assert( p->pEList );
1650d8bc7086Sdrh 
1651d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1652d8bc7086Sdrh       */
16531013c932Sdrh       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
16547d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &intersectdest);
165584ac9d02Sdanielk1977       if( rc ){
165684ac9d02Sdanielk1977         goto multi_select_end;
165784ac9d02Sdanielk1977       }
1658d8bc7086Sdrh 
1659d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1660d8bc7086Sdrh       */
166166a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
1662b9bb7c18Sdrh       assert( p->addrOpenEphm[1] == -1 );
1663b9bb7c18Sdrh       p->addrOpenEphm[1] = addr;
166482c3d636Sdrh       p->pPrior = 0;
1665a2dc3b1aSdanielk1977       pLimit = p->pLimit;
1666a2dc3b1aSdanielk1977       p->pLimit = 0;
1667a2dc3b1aSdanielk1977       pOffset = p->pOffset;
1668a2dc3b1aSdanielk1977       p->pOffset = 0;
16696c8c8ce0Sdanielk1977       intersectdest.iParm = tab2;
16707d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &intersectdest);
1671eca7e01aSdanielk1977       pDelete = p->pPrior;
167282c3d636Sdrh       p->pPrior = pPrior;
1673633e6d57Sdrh       sqlite3ExprDelete(db, p->pLimit);
1674a2dc3b1aSdanielk1977       p->pLimit = pLimit;
1675a2dc3b1aSdanielk1977       p->pOffset = pOffset;
167684ac9d02Sdanielk1977       if( rc ){
167784ac9d02Sdanielk1977         goto multi_select_end;
167884ac9d02Sdanielk1977       }
1679d8bc7086Sdrh 
1680d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1681d8bc7086Sdrh       ** tables.
1682d8bc7086Sdrh       */
168382c3d636Sdrh       assert( p->pEList );
16847d10d5a6Sdrh       if( dest.eDest==SRT_Output ){
168592378253Sdrh         Select *pFirst = p;
168692378253Sdrh         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
168792378253Sdrh         generateColumnNames(pParse, 0, pFirst->pEList);
168841202ccaSdrh       }
16894adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
16904adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
1691ec7429aeSdrh       computeLimitRegisters(pParse, p, iBreak);
169266a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
16939cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
16949cbf3425Sdrh       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
16959cbf3425Sdrh       sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1);
16969cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
1697d2b3e23bSdrh       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
1698a9671a22Sdrh                       0, -1, &dest, iCont, iBreak);
16994adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
170066a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
17014adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
170266a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
170366a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
170482c3d636Sdrh       break;
170582c3d636Sdrh     }
170682c3d636Sdrh   }
17078cdbf836Sdrh 
1708a9671a22Sdrh   /* Compute collating sequences used by
1709a9671a22Sdrh   ** temporary tables needed to implement the compound select.
1710a9671a22Sdrh   ** Attach the KeyInfo structure to all temporary tables.
17118cdbf836Sdrh   **
17128cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
17138cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
17148cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
17158cdbf836Sdrh   ** no temp tables are required.
1716fbc4ee7bSdrh   */
17177d10d5a6Sdrh   if( p->selFlags & SF_UsesEphemeral ){
1718fbc4ee7bSdrh     int i;                        /* Loop counter */
1719fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
17200342b1f5Sdrh     Select *pLoop;                /* For looping through SELECT statements */
1721f68d7d17Sdrh     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
172293a960a0Sdrh     int nCol;                     /* Number of columns in result set */
1723fbc4ee7bSdrh 
17240342b1f5Sdrh     assert( p->pRightmost==p );
172593a960a0Sdrh     nCol = p->pEList->nExpr;
1726633e6d57Sdrh     pKeyInfo = sqlite3DbMallocZero(db,
1727a9671a22Sdrh                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
1728dc1bdc4fSdanielk1977     if( !pKeyInfo ){
1729dc1bdc4fSdanielk1977       rc = SQLITE_NOMEM;
1730dc1bdc4fSdanielk1977       goto multi_select_end;
1731dc1bdc4fSdanielk1977     }
1732dc1bdc4fSdanielk1977 
1733633e6d57Sdrh     pKeyInfo->enc = ENC(db);
1734dc1bdc4fSdanielk1977     pKeyInfo->nField = nCol;
1735dc1bdc4fSdanielk1977 
17360342b1f5Sdrh     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
17370342b1f5Sdrh       *apColl = multiSelectCollSeq(pParse, p, i);
17380342b1f5Sdrh       if( 0==*apColl ){
1739633e6d57Sdrh         *apColl = db->pDfltColl;
1740dc1bdc4fSdanielk1977       }
1741dc1bdc4fSdanielk1977     }
1742dc1bdc4fSdanielk1977 
17430342b1f5Sdrh     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
17440342b1f5Sdrh       for(i=0; i<2; i++){
1745b9bb7c18Sdrh         int addr = pLoop->addrOpenEphm[i];
17460342b1f5Sdrh         if( addr<0 ){
17470342b1f5Sdrh           /* If [0] is unused then [1] is also unused.  So we can
17480342b1f5Sdrh           ** always safely abort as soon as the first unused slot is found */
1749b9bb7c18Sdrh           assert( pLoop->addrOpenEphm[1]<0 );
17500342b1f5Sdrh           break;
17510342b1f5Sdrh         }
17520342b1f5Sdrh         sqlite3VdbeChangeP2(v, addr, nCol);
175366a5167bSdrh         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
17540ee5a1e7Sdrh         pLoop->addrOpenEphm[i] = -1;
17550342b1f5Sdrh       }
1756dc1bdc4fSdanielk1977     }
1757633e6d57Sdrh     sqlite3DbFree(db, pKeyInfo);
1758dc1bdc4fSdanielk1977   }
1759dc1bdc4fSdanielk1977 
1760dc1bdc4fSdanielk1977 multi_select_end:
17611013c932Sdrh   pDest->iMem = dest.iMem;
1762ad27e761Sdrh   pDest->nMem = dest.nMem;
1763633e6d57Sdrh   sqlite3SelectDelete(db, pDelete);
176484ac9d02Sdanielk1977   return rc;
17652282792aSdrh }
1766b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
17672282792aSdrh 
1768b21e7c70Sdrh /*
1769b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a
1770b21e7c70Sdrh ** SELECT statment.
17710acb7e48Sdrh **
17720acb7e48Sdrh ** The data to be output is contained in pIn->iMem.  There are
17730acb7e48Sdrh ** pIn->nMem columns to be output.  pDest is where the output should
17740acb7e48Sdrh ** be sent.
17750acb7e48Sdrh **
17760acb7e48Sdrh ** regReturn is the number of the register holding the subroutine
17770acb7e48Sdrh ** return address.
17780acb7e48Sdrh **
17790acb7e48Sdrh ** If regPrev>0 then it is a the first register in a vector that
17800acb7e48Sdrh ** records the previous output.  mem[regPrev] is a flag that is false
17810acb7e48Sdrh ** if there has been no previous output.  If regPrev>0 then code is
17820acb7e48Sdrh ** generated to suppress duplicates.  pKeyInfo is used for comparing
17830acb7e48Sdrh ** keys.
17840acb7e48Sdrh **
17850acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to
17860acb7e48Sdrh ** iBreak.
1787b21e7c70Sdrh */
17880acb7e48Sdrh static int generateOutputSubroutine(
178992b01d53Sdrh   Parse *pParse,          /* Parsing context */
179092b01d53Sdrh   Select *p,              /* The SELECT statement */
179192b01d53Sdrh   SelectDest *pIn,        /* Coroutine supplying data */
179292b01d53Sdrh   SelectDest *pDest,      /* Where to send the data */
179392b01d53Sdrh   int regReturn,          /* The return address register */
17940acb7e48Sdrh   int regPrev,            /* Previous result register.  No uniqueness if 0 */
17950acb7e48Sdrh   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
17960acb7e48Sdrh   int p4type,             /* The p4 type for pKeyInfo */
179792b01d53Sdrh   int iBreak              /* Jump here if we hit the LIMIT */
1798b21e7c70Sdrh ){
1799b21e7c70Sdrh   Vdbe *v = pParse->pVdbe;
180092b01d53Sdrh   int iContinue;
180192b01d53Sdrh   int addr;
1802b21e7c70Sdrh 
180392b01d53Sdrh   addr = sqlite3VdbeCurrentAddr(v);
180492b01d53Sdrh   iContinue = sqlite3VdbeMakeLabel(v);
18050acb7e48Sdrh 
18060acb7e48Sdrh   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
18070acb7e48Sdrh   */
18080acb7e48Sdrh   if( regPrev ){
18090acb7e48Sdrh     int j1, j2;
18100acb7e48Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
18110acb7e48Sdrh     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
18120acb7e48Sdrh                               (char*)pKeyInfo, p4type);
18130acb7e48Sdrh     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
18140acb7e48Sdrh     sqlite3VdbeJumpHere(v, j1);
18150acb7e48Sdrh     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
18160acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
18170acb7e48Sdrh   }
18181f9caa41Sdanielk1977   if( pParse->db->mallocFailed ) return 0;
18190acb7e48Sdrh 
18200acb7e48Sdrh   /* Suppress the the first OFFSET entries if there is an OFFSET clause
18210acb7e48Sdrh   */
182292b01d53Sdrh   codeOffset(v, p, iContinue);
1823b21e7c70Sdrh 
1824b21e7c70Sdrh   switch( pDest->eDest ){
1825b21e7c70Sdrh     /* Store the result as data using a unique key.
1826b21e7c70Sdrh     */
1827b21e7c70Sdrh     case SRT_Table:
1828b21e7c70Sdrh     case SRT_EphemTab: {
1829b21e7c70Sdrh       int r1 = sqlite3GetTempReg(pParse);
1830b21e7c70Sdrh       int r2 = sqlite3GetTempReg(pParse);
183192b01d53Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
183292b01d53Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
183392b01d53Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
1834b21e7c70Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1835b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r2);
1836b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
1837b21e7c70Sdrh       break;
1838b21e7c70Sdrh     }
1839b21e7c70Sdrh 
1840b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1841b21e7c70Sdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
1842b21e7c70Sdrh     ** then there should be a single item on the stack.  Write this
1843b21e7c70Sdrh     ** item into the set table with bogus data.
1844b21e7c70Sdrh     */
1845b21e7c70Sdrh     case SRT_Set: {
18466fccc35aSdrh       int r1;
184792b01d53Sdrh       assert( pIn->nMem==1 );
184892b01d53Sdrh       p->affinity =
184992b01d53Sdrh          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
1850b21e7c70Sdrh       r1 = sqlite3GetTempReg(pParse);
185192b01d53Sdrh       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
185292b01d53Sdrh       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
185392b01d53Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
1854b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
1855b21e7c70Sdrh       break;
1856b21e7c70Sdrh     }
1857b21e7c70Sdrh 
185885e9e22bSdrh #if 0  /* Never occurs on an ORDER BY query */
1859b21e7c70Sdrh     /* If any row exist in the result set, record that fact and abort.
1860b21e7c70Sdrh     */
1861b21e7c70Sdrh     case SRT_Exists: {
186292b01d53Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
1863b21e7c70Sdrh       /* The LIMIT clause will terminate the loop for us */
1864b21e7c70Sdrh       break;
1865b21e7c70Sdrh     }
186685e9e22bSdrh #endif
1867b21e7c70Sdrh 
1868b21e7c70Sdrh     /* If this is a scalar select that is part of an expression, then
1869b21e7c70Sdrh     ** store the results in the appropriate memory cell and break out
1870b21e7c70Sdrh     ** of the scan loop.
1871b21e7c70Sdrh     */
1872b21e7c70Sdrh     case SRT_Mem: {
187392b01d53Sdrh       assert( pIn->nMem==1 );
187492b01d53Sdrh       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
1875b21e7c70Sdrh       /* The LIMIT clause will jump out of the loop for us */
1876b21e7c70Sdrh       break;
1877b21e7c70Sdrh     }
1878b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
1879b21e7c70Sdrh 
18807d10d5a6Sdrh     /* The results are stored in a sequence of registers
18817d10d5a6Sdrh     ** starting at pDest->iMem.  Then the co-routine yields.
1882b21e7c70Sdrh     */
188392b01d53Sdrh     case SRT_Coroutine: {
188492b01d53Sdrh       if( pDest->iMem==0 ){
188592b01d53Sdrh         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
188692b01d53Sdrh         pDest->nMem = pIn->nMem;
1887b21e7c70Sdrh       }
188892b01d53Sdrh       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
188992b01d53Sdrh       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
189092b01d53Sdrh       break;
189192b01d53Sdrh     }
189292b01d53Sdrh 
18937d10d5a6Sdrh     /* Results are stored in a sequence of registers.  Then the
18947d10d5a6Sdrh     ** OP_ResultRow opcode is used to cause sqlite3_step() to return
18957d10d5a6Sdrh     ** the next row of result.
18967d10d5a6Sdrh     */
18977d10d5a6Sdrh     case SRT_Output: {
189892b01d53Sdrh       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
189992b01d53Sdrh       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
1900b21e7c70Sdrh       break;
1901b21e7c70Sdrh     }
1902b21e7c70Sdrh 
1903b21e7c70Sdrh #if !defined(SQLITE_OMIT_TRIGGER)
1904b21e7c70Sdrh     /* Discard the results.  This is used for SELECT statements inside
1905b21e7c70Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
1906b21e7c70Sdrh     ** user-defined functions that have side effects.  We do not care
1907b21e7c70Sdrh     ** about the actual results of the select.
1908b21e7c70Sdrh     */
1909b21e7c70Sdrh     default: {
1910b21e7c70Sdrh       break;
1911b21e7c70Sdrh     }
1912b21e7c70Sdrh #endif
1913b21e7c70Sdrh   }
191492b01d53Sdrh 
191592b01d53Sdrh   /* Jump to the end of the loop if the LIMIT is reached.
191692b01d53Sdrh   */
191792b01d53Sdrh   if( p->iLimit ){
191892b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
191992b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
192092b01d53Sdrh   }
192192b01d53Sdrh 
192292b01d53Sdrh   /* Generate the subroutine return
192392b01d53Sdrh   */
19240acb7e48Sdrh   sqlite3VdbeResolveLabel(v, iContinue);
192592b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
192692b01d53Sdrh 
192792b01d53Sdrh   return addr;
1928b21e7c70Sdrh }
1929b21e7c70Sdrh 
1930b21e7c70Sdrh /*
1931b21e7c70Sdrh ** Alternative compound select code generator for cases when there
1932b21e7c70Sdrh ** is an ORDER BY clause.
1933b21e7c70Sdrh **
1934b21e7c70Sdrh ** We assume a query of the following form:
1935b21e7c70Sdrh **
1936b21e7c70Sdrh **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
1937b21e7c70Sdrh **
1938b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
1939b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as
1940b21e7c70Sdrh ** co-routines.  Then run the co-routines in parallel and merge the results
1941b21e7c70Sdrh ** into the output.  In addition to the two coroutines (called selectA and
1942b21e7c70Sdrh ** selectB) there are 7 subroutines:
1943b21e7c70Sdrh **
1944b21e7c70Sdrh **    outA:    Move the output of the selectA coroutine into the output
1945b21e7c70Sdrh **             of the compound query.
1946b21e7c70Sdrh **
1947b21e7c70Sdrh **    outB:    Move the output of the selectB coroutine into the output
1948b21e7c70Sdrh **             of the compound query.  (Only generated for UNION and
1949b21e7c70Sdrh **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
1950b21e7c70Sdrh **             appears only in B.)
1951b21e7c70Sdrh **
1952b21e7c70Sdrh **    AltB:    Called when there is data from both coroutines and A<B.
1953b21e7c70Sdrh **
1954b21e7c70Sdrh **    AeqB:    Called when there is data from both coroutines and A==B.
1955b21e7c70Sdrh **
1956b21e7c70Sdrh **    AgtB:    Called when there is data from both coroutines and A>B.
1957b21e7c70Sdrh **
1958b21e7c70Sdrh **    EofA:    Called when data is exhausted from selectA.
1959b21e7c70Sdrh **
1960b21e7c70Sdrh **    EofB:    Called when data is exhausted from selectB.
1961b21e7c70Sdrh **
1962b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which
1963b21e7c70Sdrh ** <operator> is used:
1964b21e7c70Sdrh **
1965b21e7c70Sdrh **
1966b21e7c70Sdrh **             UNION ALL         UNION            EXCEPT          INTERSECT
1967b21e7c70Sdrh **          -------------  -----------------  --------------  -----------------
1968b21e7c70Sdrh **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
1969b21e7c70Sdrh **
19700acb7e48Sdrh **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
1971b21e7c70Sdrh **
1972b21e7c70Sdrh **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
1973b21e7c70Sdrh **
19740acb7e48Sdrh **   EofA:   outB, nextB      outB, nextB          halt             halt
1975b21e7c70Sdrh **
19760acb7e48Sdrh **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
19770acb7e48Sdrh **
19780acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
19790acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes
19800acb7e48Sdrh ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
19810acb7e48Sdrh ** following nextX causes a jump to the end of the select processing.
19820acb7e48Sdrh **
19830acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
19840acb7e48Sdrh ** within the output subroutine.  The regPrev register set holds the previously
19850acb7e48Sdrh ** output value.  A comparison is made against this value and the output
19860acb7e48Sdrh ** is skipped if the next results would be the same as the previous.
1987b21e7c70Sdrh **
1988b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven
1989b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom.  Like this:
1990b21e7c70Sdrh **
1991b21e7c70Sdrh **          goto Init
1992b21e7c70Sdrh **     coA: coroutine for left query (A)
1993b21e7c70Sdrh **     coB: coroutine for right query (B)
1994b21e7c70Sdrh **    outA: output one row of A
1995b21e7c70Sdrh **    outB: output one row of B (UNION and UNION ALL only)
1996b21e7c70Sdrh **    EofA: ...
1997b21e7c70Sdrh **    EofB: ...
1998b21e7c70Sdrh **    AltB: ...
1999b21e7c70Sdrh **    AeqB: ...
2000b21e7c70Sdrh **    AgtB: ...
2001b21e7c70Sdrh **    Init: initialize coroutine registers
2002b21e7c70Sdrh **          yield coA
2003b21e7c70Sdrh **          if eof(A) goto EofA
2004b21e7c70Sdrh **          yield coB
2005b21e7c70Sdrh **          if eof(B) goto EofB
2006b21e7c70Sdrh **    Cmpr: Compare A, B
2007b21e7c70Sdrh **          Jump AltB, AeqB, AgtB
2008b21e7c70Sdrh **     End: ...
2009b21e7c70Sdrh **
2010b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
2011b21e7c70Sdrh ** actually called using Gosub and they do not Return.  EofA and EofB loop
2012b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
2013b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB.
2014b21e7c70Sdrh */
2015de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
2016b21e7c70Sdrh static int multiSelectOrderBy(
2017b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
2018b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
2019a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
2020b21e7c70Sdrh ){
20210acb7e48Sdrh   int i, j;             /* Loop counters */
2022b21e7c70Sdrh   Select *pPrior;       /* Another SELECT immediately to our left */
2023b21e7c70Sdrh   Vdbe *v;              /* Generate code to this VDBE */
2024b21e7c70Sdrh   SelectDest destA;     /* Destination for coroutine A */
2025b21e7c70Sdrh   SelectDest destB;     /* Destination for coroutine B */
202692b01d53Sdrh   int regAddrA;         /* Address register for select-A coroutine */
202792b01d53Sdrh   int regEofA;          /* Flag to indicate when select-A is complete */
202892b01d53Sdrh   int regAddrB;         /* Address register for select-B coroutine */
202992b01d53Sdrh   int regEofB;          /* Flag to indicate when select-B is complete */
203092b01d53Sdrh   int addrSelectA;      /* Address of the select-A coroutine */
203192b01d53Sdrh   int addrSelectB;      /* Address of the select-B coroutine */
203292b01d53Sdrh   int regOutA;          /* Address register for the output-A subroutine */
203392b01d53Sdrh   int regOutB;          /* Address register for the output-B subroutine */
203492b01d53Sdrh   int addrOutA;         /* Address of the output-A subroutine */
203592b01d53Sdrh   int addrOutB;         /* Address of the output-B subroutine */
203692b01d53Sdrh   int addrEofA;         /* Address of the select-A-exhausted subroutine */
203792b01d53Sdrh   int addrEofB;         /* Address of the select-B-exhausted subroutine */
203892b01d53Sdrh   int addrAltB;         /* Address of the A<B subroutine */
203992b01d53Sdrh   int addrAeqB;         /* Address of the A==B subroutine */
204092b01d53Sdrh   int addrAgtB;         /* Address of the A>B subroutine */
204192b01d53Sdrh   int regLimitA;        /* Limit register for select-A */
204292b01d53Sdrh   int regLimitB;        /* Limit register for select-A */
20430acb7e48Sdrh   int regPrev;          /* A range of registers to hold previous output */
204492b01d53Sdrh   int savedLimit;       /* Saved value of p->iLimit */
204592b01d53Sdrh   int savedOffset;      /* Saved value of p->iOffset */
204692b01d53Sdrh   int labelCmpr;        /* Label for the start of the merge algorithm */
204792b01d53Sdrh   int labelEnd;         /* Label for the end of the overall SELECT stmt */
20480acb7e48Sdrh   int j1;               /* Jump instructions that get retargetted */
204992b01d53Sdrh   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
20500acb7e48Sdrh   KeyInfo *pKeyDup;     /* Comparison information for duplicate removal */
20510acb7e48Sdrh   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
20520acb7e48Sdrh   sqlite3 *db;          /* Database connection */
20530acb7e48Sdrh   ExprList *pOrderBy;   /* The ORDER BY clause */
20540acb7e48Sdrh   int nOrderBy;         /* Number of terms in the ORDER BY clause */
20550acb7e48Sdrh   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
2056b21e7c70Sdrh 
205792b01d53Sdrh   assert( p->pOrderBy!=0 );
20580acb7e48Sdrh   db = pParse->db;
205992b01d53Sdrh   v = pParse->pVdbe;
206092b01d53Sdrh   if( v==0 ) return SQLITE_NOMEM;
206192b01d53Sdrh   labelEnd = sqlite3VdbeMakeLabel(v);
206292b01d53Sdrh   labelCmpr = sqlite3VdbeMakeLabel(v);
20630acb7e48Sdrh 
2064b21e7c70Sdrh 
206592b01d53Sdrh   /* Patch up the ORDER BY clause
206692b01d53Sdrh   */
206792b01d53Sdrh   op = p->op;
2068b21e7c70Sdrh   pPrior = p->pPrior;
206992b01d53Sdrh   assert( pPrior->pOrderBy==0 );
20700acb7e48Sdrh   pOrderBy = p->pOrderBy;
207193a960a0Sdrh   assert( pOrderBy );
20720acb7e48Sdrh   nOrderBy = pOrderBy->nExpr;
207393a960a0Sdrh 
20740acb7e48Sdrh   /* For operators other than UNION ALL we have to make sure that
20750acb7e48Sdrh   ** the ORDER BY clause covers every term of the result set.  Add
20760acb7e48Sdrh   ** terms to the ORDER BY clause as necessary.
20770acb7e48Sdrh   */
20780acb7e48Sdrh   if( op!=TK_ALL ){
20790acb7e48Sdrh     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
20807d10d5a6Sdrh       struct ExprList_item *pItem;
20817d10d5a6Sdrh       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
20827d10d5a6Sdrh         assert( pItem->iCol>0 );
20837d10d5a6Sdrh         if( pItem->iCol==i ) break;
20840acb7e48Sdrh       }
20850acb7e48Sdrh       if( j==nOrderBy ){
20860acb7e48Sdrh         Expr *pNew = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, 0);
20870acb7e48Sdrh         if( pNew==0 ) return SQLITE_NOMEM;
20880acb7e48Sdrh         pNew->flags |= EP_IntValue;
20890acb7e48Sdrh         pNew->iTable = i;
20900acb7e48Sdrh         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew, 0);
20917d10d5a6Sdrh         pOrderBy->a[nOrderBy++].iCol = i;
20920acb7e48Sdrh       }
20930acb7e48Sdrh     }
20940acb7e48Sdrh   }
20950acb7e48Sdrh 
20960acb7e48Sdrh   /* Compute the comparison permutation and keyinfo that is used with
20970acb7e48Sdrh   ** the permutation in order to comparisons to determine if the next
20980acb7e48Sdrh   ** row of results comes from selectA or selectB.  Also add explicit
20990acb7e48Sdrh   ** collations to the ORDER BY clause terms so that when the subqueries
21000acb7e48Sdrh   ** to the right and the left are evaluated, they use the correct
21010acb7e48Sdrh   ** collation.
21020acb7e48Sdrh   */
21030acb7e48Sdrh   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
21040acb7e48Sdrh   if( aPermute ){
21057d10d5a6Sdrh     struct ExprList_item *pItem;
21067d10d5a6Sdrh     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
21077d10d5a6Sdrh       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
21087d10d5a6Sdrh       aPermute[i] = pItem->iCol - 1;
21090acb7e48Sdrh     }
21100acb7e48Sdrh     pKeyMerge =
21110acb7e48Sdrh       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
21120acb7e48Sdrh     if( pKeyMerge ){
21130acb7e48Sdrh       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
21140acb7e48Sdrh       pKeyMerge->nField = nOrderBy;
21150acb7e48Sdrh       pKeyMerge->enc = ENC(db);
21160acb7e48Sdrh       for(i=0; i<nOrderBy; i++){
21170acb7e48Sdrh         CollSeq *pColl;
21180acb7e48Sdrh         Expr *pTerm = pOrderBy->a[i].pExpr;
21190acb7e48Sdrh         if( pTerm->flags & EP_ExpCollate ){
21200acb7e48Sdrh           pColl = pTerm->pColl;
21210acb7e48Sdrh         }else{
21220acb7e48Sdrh           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
21230acb7e48Sdrh           pTerm->flags |= EP_ExpCollate;
21240acb7e48Sdrh           pTerm->pColl = pColl;
21250acb7e48Sdrh         }
21260acb7e48Sdrh         pKeyMerge->aColl[i] = pColl;
21270acb7e48Sdrh         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
21280acb7e48Sdrh       }
21290acb7e48Sdrh     }
21300acb7e48Sdrh   }else{
21310acb7e48Sdrh     pKeyMerge = 0;
21320acb7e48Sdrh   }
21330acb7e48Sdrh 
21340acb7e48Sdrh   /* Reattach the ORDER BY clause to the query.
21350acb7e48Sdrh   */
21360acb7e48Sdrh   p->pOrderBy = pOrderBy;
21370acb7e48Sdrh   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy);
21380acb7e48Sdrh 
21390acb7e48Sdrh   /* Allocate a range of temporary registers and the KeyInfo needed
21400acb7e48Sdrh   ** for the logic that removes duplicate result rows when the
21410acb7e48Sdrh   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
21420acb7e48Sdrh   */
21430acb7e48Sdrh   if( op==TK_ALL ){
21440acb7e48Sdrh     regPrev = 0;
21450acb7e48Sdrh   }else{
21460acb7e48Sdrh     int nExpr = p->pEList->nExpr;
21470acb7e48Sdrh     assert( nOrderBy>=nExpr );
21480acb7e48Sdrh     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
21490acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
21500acb7e48Sdrh     pKeyDup = sqlite3DbMallocZero(db,
21510acb7e48Sdrh                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
21520acb7e48Sdrh     if( pKeyDup ){
21530acb7e48Sdrh       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
21540acb7e48Sdrh       pKeyDup->nField = nExpr;
21550acb7e48Sdrh       pKeyDup->enc = ENC(db);
21560acb7e48Sdrh       for(i=0; i<nExpr; i++){
21570acb7e48Sdrh         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
21580acb7e48Sdrh         pKeyDup->aSortOrder[i] = 0;
21590acb7e48Sdrh       }
21600acb7e48Sdrh     }
21610acb7e48Sdrh   }
216292b01d53Sdrh 
216392b01d53Sdrh   /* Separate the left and the right query from one another
216492b01d53Sdrh   */
216592b01d53Sdrh   p->pPrior = 0;
216692b01d53Sdrh   pPrior->pRightmost = 0;
21677d10d5a6Sdrh   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
21680acb7e48Sdrh   if( pPrior->pPrior==0 ){
21697d10d5a6Sdrh     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
21700acb7e48Sdrh   }
217192b01d53Sdrh 
217292b01d53Sdrh   /* Compute the limit registers */
217392b01d53Sdrh   computeLimitRegisters(pParse, p, labelEnd);
21740acb7e48Sdrh   if( p->iLimit && op==TK_ALL ){
217592b01d53Sdrh     regLimitA = ++pParse->nMem;
217692b01d53Sdrh     regLimitB = ++pParse->nMem;
217792b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
217892b01d53Sdrh                                   regLimitA);
217992b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
218092b01d53Sdrh   }else{
218192b01d53Sdrh     regLimitA = regLimitB = 0;
218292b01d53Sdrh   }
2183633e6d57Sdrh   sqlite3ExprDelete(db, p->pLimit);
21840acb7e48Sdrh   p->pLimit = 0;
2185633e6d57Sdrh   sqlite3ExprDelete(db, p->pOffset);
21860acb7e48Sdrh   p->pOffset = 0;
218792b01d53Sdrh 
2188b21e7c70Sdrh   regAddrA = ++pParse->nMem;
2189b21e7c70Sdrh   regEofA = ++pParse->nMem;
2190b21e7c70Sdrh   regAddrB = ++pParse->nMem;
2191b21e7c70Sdrh   regEofB = ++pParse->nMem;
2192b21e7c70Sdrh   regOutA = ++pParse->nMem;
2193b21e7c70Sdrh   regOutB = ++pParse->nMem;
2194b21e7c70Sdrh   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
2195b21e7c70Sdrh   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
2196b21e7c70Sdrh 
219792b01d53Sdrh   /* Jump past the various subroutines and coroutines to the main
219892b01d53Sdrh   ** merge loop
219992b01d53Sdrh   */
2200b21e7c70Sdrh   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
2201b21e7c70Sdrh   addrSelectA = sqlite3VdbeCurrentAddr(v);
220292b01d53Sdrh 
22030acb7e48Sdrh 
220492b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement to the
22050acb7e48Sdrh   ** left of the compound operator - the "A" select.
22060acb7e48Sdrh   */
2207b21e7c70Sdrh   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
220892b01d53Sdrh   pPrior->iLimit = regLimitA;
22097d10d5a6Sdrh   sqlite3Select(pParse, pPrior, &destA);
2210b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
221192b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2212b21e7c70Sdrh   VdbeNoopComment((v, "End coroutine for left SELECT"));
2213b21e7c70Sdrh 
221492b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement on
221592b01d53Sdrh   ** the right - the "B" select
221692b01d53Sdrh   */
2217b21e7c70Sdrh   addrSelectB = sqlite3VdbeCurrentAddr(v);
2218b21e7c70Sdrh   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
221992b01d53Sdrh   savedLimit = p->iLimit;
222092b01d53Sdrh   savedOffset = p->iOffset;
222192b01d53Sdrh   p->iLimit = regLimitB;
222292b01d53Sdrh   p->iOffset = 0;
22237d10d5a6Sdrh   sqlite3Select(pParse, p, &destB);
222492b01d53Sdrh   p->iLimit = savedLimit;
222592b01d53Sdrh   p->iOffset = savedOffset;
2226b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
222792b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
2228b21e7c70Sdrh   VdbeNoopComment((v, "End coroutine for right SELECT"));
2229b21e7c70Sdrh 
223092b01d53Sdrh   /* Generate a subroutine that outputs the current row of the A
22310acb7e48Sdrh   ** select as the next output row of the compound select.
223292b01d53Sdrh   */
2233b21e7c70Sdrh   VdbeNoopComment((v, "Output routine for A"));
22340acb7e48Sdrh   addrOutA = generateOutputSubroutine(pParse,
22350acb7e48Sdrh                  p, &destA, pDest, regOutA,
22360acb7e48Sdrh                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
2237b21e7c70Sdrh 
223892b01d53Sdrh   /* Generate a subroutine that outputs the current row of the B
22390acb7e48Sdrh   ** select as the next output row of the compound select.
224092b01d53Sdrh   */
22410acb7e48Sdrh   if( op==TK_ALL || op==TK_UNION ){
2242b21e7c70Sdrh     VdbeNoopComment((v, "Output routine for B"));
22430acb7e48Sdrh     addrOutB = generateOutputSubroutine(pParse,
22440acb7e48Sdrh                  p, &destB, pDest, regOutB,
22450acb7e48Sdrh                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
22460acb7e48Sdrh   }
2247b21e7c70Sdrh 
224892b01d53Sdrh   /* Generate a subroutine to run when the results from select A
224992b01d53Sdrh   ** are exhausted and only data in select B remains.
225092b01d53Sdrh   */
225192b01d53Sdrh   VdbeNoopComment((v, "eof-A subroutine"));
225292b01d53Sdrh   if( op==TK_EXCEPT || op==TK_INTERSECT ){
22530acb7e48Sdrh     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
225492b01d53Sdrh   }else{
22550acb7e48Sdrh     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
2256b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
225792b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
22580acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
2259b21e7c70Sdrh   }
2260b21e7c70Sdrh 
226192b01d53Sdrh   /* Generate a subroutine to run when the results from select B
226292b01d53Sdrh   ** are exhausted and only data in select A remains.
226392b01d53Sdrh   */
2264b21e7c70Sdrh   if( op==TK_INTERSECT ){
226592b01d53Sdrh     addrEofB = addrEofA;
2266b21e7c70Sdrh   }else{
226792b01d53Sdrh     VdbeNoopComment((v, "eof-B subroutine"));
22680acb7e48Sdrh     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
2269b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
227092b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
22710acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
2272b21e7c70Sdrh   }
2273b21e7c70Sdrh 
227492b01d53Sdrh   /* Generate code to handle the case of A<B
227592b01d53Sdrh   */
2276b21e7c70Sdrh   VdbeNoopComment((v, "A-lt-B subroutine"));
22770acb7e48Sdrh   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
227892b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2279b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
228092b01d53Sdrh   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2281b21e7c70Sdrh 
228292b01d53Sdrh   /* Generate code to handle the case of A==B
228392b01d53Sdrh   */
2284b21e7c70Sdrh   if( op==TK_ALL ){
2285b21e7c70Sdrh     addrAeqB = addrAltB;
22860acb7e48Sdrh   }else if( op==TK_INTERSECT ){
22870acb7e48Sdrh     addrAeqB = addrAltB;
22880acb7e48Sdrh     addrAltB++;
228992b01d53Sdrh   }else{
2290b21e7c70Sdrh     VdbeNoopComment((v, "A-eq-B subroutine"));
22910acb7e48Sdrh     addrAeqB =
229292b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
229392b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
229492b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
229592b01d53Sdrh   }
2296b21e7c70Sdrh 
229792b01d53Sdrh   /* Generate code to handle the case of A>B
229892b01d53Sdrh   */
2299b21e7c70Sdrh   VdbeNoopComment((v, "A-gt-B subroutine"));
2300b21e7c70Sdrh   addrAgtB = sqlite3VdbeCurrentAddr(v);
2301b21e7c70Sdrh   if( op==TK_ALL || op==TK_UNION ){
2302b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
230392b01d53Sdrh   }
23040acb7e48Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
2305b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
230692b01d53Sdrh   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2307b21e7c70Sdrh 
230892b01d53Sdrh   /* This code runs once to initialize everything.
230992b01d53Sdrh   */
2310b21e7c70Sdrh   sqlite3VdbeJumpHere(v, j1);
2311b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
2312b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
231392b01d53Sdrh   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
23140acb7e48Sdrh   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
2315b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
2316b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
231792b01d53Sdrh 
231892b01d53Sdrh   /* Implement the main merge loop
231992b01d53Sdrh   */
232092b01d53Sdrh   sqlite3VdbeResolveLabel(v, labelCmpr);
23210acb7e48Sdrh   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
23220acb7e48Sdrh   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
23230acb7e48Sdrh                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
2324b21e7c70Sdrh   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
232592b01d53Sdrh 
23260acb7e48Sdrh   /* Release temporary registers
23270acb7e48Sdrh   */
23280acb7e48Sdrh   if( regPrev ){
23290acb7e48Sdrh     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
23300acb7e48Sdrh   }
23310acb7e48Sdrh 
233292b01d53Sdrh   /* Jump to the this point in order to terminate the query.
233392b01d53Sdrh   */
2334b21e7c70Sdrh   sqlite3VdbeResolveLabel(v, labelEnd);
2335b21e7c70Sdrh 
233692b01d53Sdrh   /* Set the number of output columns
233792b01d53Sdrh   */
23387d10d5a6Sdrh   if( pDest->eDest==SRT_Output ){
23390acb7e48Sdrh     Select *pFirst = pPrior;
234092b01d53Sdrh     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
234192b01d53Sdrh     generateColumnNames(pParse, 0, pFirst->pEList);
2342b21e7c70Sdrh   }
234392b01d53Sdrh 
23440acb7e48Sdrh   /* Reassembly the compound query so that it will be freed correctly
23450acb7e48Sdrh   ** by the calling function */
23465e7ad508Sdanielk1977   if( p->pPrior ){
2347633e6d57Sdrh     sqlite3SelectDelete(db, p->pPrior);
23485e7ad508Sdanielk1977   }
23490acb7e48Sdrh   p->pPrior = pPrior;
235092b01d53Sdrh 
235192b01d53Sdrh   /*** TBD:  Insert subroutine calls to close cursors on incomplete
235292b01d53Sdrh   **** subqueries ****/
235392b01d53Sdrh   return SQLITE_OK;
235492b01d53Sdrh }
2355de3e41e3Sdanielk1977 #endif
2356b21e7c70Sdrh 
23573514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
235817435752Sdrh /* Forward Declarations */
235917435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*);
236017435752Sdrh static void substSelect(sqlite3*, Select *, int, ExprList *);
236117435752Sdrh 
23622282792aSdrh /*
2363832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
23646a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
236584e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
23666a3ea0e6Sdrh ** unchanged.)
2367832508b7Sdrh **
2368832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
2369832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
2370832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
2371832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
2372832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
2373832508b7Sdrh ** of the subquery rather the result set of the subquery.
2374832508b7Sdrh */
237517435752Sdrh static void substExpr(
237617435752Sdrh   sqlite3 *db,        /* Report malloc errors to this connection */
237717435752Sdrh   Expr *pExpr,        /* Expr in which substitution occurs */
237817435752Sdrh   int iTable,         /* Table to be substituted */
237917435752Sdrh   ExprList *pEList    /* Substitute expressions */
238017435752Sdrh ){
2381832508b7Sdrh   if( pExpr==0 ) return;
238250350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
238350350a15Sdrh     if( pExpr->iColumn<0 ){
238450350a15Sdrh       pExpr->op = TK_NULL;
238550350a15Sdrh     }else{
2386832508b7Sdrh       Expr *pNew;
238784e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
2388832508b7Sdrh       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
2389832508b7Sdrh       pNew = pEList->a[pExpr->iColumn].pExpr;
2390832508b7Sdrh       assert( pNew!=0 );
2391832508b7Sdrh       pExpr->op = pNew->op;
2392d94a6698Sdrh       assert( pExpr->pLeft==0 );
239317435752Sdrh       pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
2394d94a6698Sdrh       assert( pExpr->pRight==0 );
239517435752Sdrh       pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
2396d94a6698Sdrh       assert( pExpr->pList==0 );
239717435752Sdrh       pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
2398832508b7Sdrh       pExpr->iTable = pNew->iTable;
2399fbbe005aSdanielk1977       pExpr->pTab = pNew->pTab;
2400832508b7Sdrh       pExpr->iColumn = pNew->iColumn;
2401832508b7Sdrh       pExpr->iAgg = pNew->iAgg;
240217435752Sdrh       sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
240317435752Sdrh       sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
240417435752Sdrh       pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
2405a1cb183dSdanielk1977       pExpr->flags = pNew->flags;
240650350a15Sdrh     }
2407832508b7Sdrh   }else{
240817435752Sdrh     substExpr(db, pExpr->pLeft, iTable, pEList);
240917435752Sdrh     substExpr(db, pExpr->pRight, iTable, pEList);
241017435752Sdrh     substSelect(db, pExpr->pSelect, iTable, pEList);
241117435752Sdrh     substExprList(db, pExpr->pList, iTable, pEList);
2412832508b7Sdrh   }
2413832508b7Sdrh }
241417435752Sdrh static void substExprList(
241517435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
241617435752Sdrh   ExprList *pList,     /* List to scan and in which to make substitutes */
241717435752Sdrh   int iTable,          /* Table to be substituted */
241817435752Sdrh   ExprList *pEList     /* Substitute values */
241917435752Sdrh ){
2420832508b7Sdrh   int i;
2421832508b7Sdrh   if( pList==0 ) return;
2422832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
242317435752Sdrh     substExpr(db, pList->a[i].pExpr, iTable, pEList);
2424832508b7Sdrh   }
2425832508b7Sdrh }
242617435752Sdrh static void substSelect(
242717435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
242817435752Sdrh   Select *p,           /* SELECT statement in which to make substitutions */
242917435752Sdrh   int iTable,          /* Table to be replaced */
243017435752Sdrh   ExprList *pEList     /* Substitute values */
243117435752Sdrh ){
2432588a9a1aSdrh   SrcList *pSrc;
2433588a9a1aSdrh   struct SrcList_item *pItem;
2434588a9a1aSdrh   int i;
2435b3bce662Sdanielk1977   if( !p ) return;
243617435752Sdrh   substExprList(db, p->pEList, iTable, pEList);
243717435752Sdrh   substExprList(db, p->pGroupBy, iTable, pEList);
243817435752Sdrh   substExprList(db, p->pOrderBy, iTable, pEList);
243917435752Sdrh   substExpr(db, p->pHaving, iTable, pEList);
244017435752Sdrh   substExpr(db, p->pWhere, iTable, pEList);
244117435752Sdrh   substSelect(db, p->pPrior, iTable, pEList);
2442588a9a1aSdrh   pSrc = p->pSrc;
2443588a9a1aSdrh   if( pSrc ){
2444588a9a1aSdrh     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
2445588a9a1aSdrh       substSelect(db, pItem->pSelect, iTable, pEList);
2446588a9a1aSdrh     }
2447588a9a1aSdrh   }
2448b3bce662Sdanielk1977 }
24493514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
2450832508b7Sdrh 
24513514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
2452832508b7Sdrh /*
24531350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
24541350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
24551350b030Sdrh ** occurs.
24561350b030Sdrh **
24571350b030Sdrh ** To understand the concept of flattening, consider the following
24581350b030Sdrh ** query:
24591350b030Sdrh **
24601350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
24611350b030Sdrh **
24621350b030Sdrh ** The default way of implementing this query is to execute the
24631350b030Sdrh ** subquery first and store the results in a temporary table, then
24641350b030Sdrh ** run the outer query on that temporary table.  This requires two
24651350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
24661350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
2467832508b7Sdrh ** optimized.
24681350b030Sdrh **
2469832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
24701350b030Sdrh ** a single flat select, like this:
24711350b030Sdrh **
24721350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
24731350b030Sdrh **
24741350b030Sdrh ** The code generated for this simpification gives the same result
2475832508b7Sdrh ** but only has to scan the data once.  And because indices might
2476832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
2477832508b7Sdrh ** avoided.
24781350b030Sdrh **
2479832508b7Sdrh ** Flattening is only attempted if all of the following are true:
24801350b030Sdrh **
2481832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
24821350b030Sdrh **
2483832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
2484832508b7Sdrh **
24852b300d5dSdrh **   (3)  The subquery is not the right operand of a left outer join
24862b300d5dSdrh **        (Originally ticket #306.  Strenghtened by ticket #3300)
2487832508b7Sdrh **
2488832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
2489832508b7Sdrh **
2490832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
2491832508b7Sdrh **        aggregates.
2492832508b7Sdrh **
2493832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
2494832508b7Sdrh **        DISTINCT.
2495832508b7Sdrh **
249608192d5fSdrh **   (7)  The subquery has a FROM clause.
249708192d5fSdrh **
2498df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
2499df199a25Sdrh **
2500df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
2501df199a25Sdrh **        aggregates.
2502df199a25Sdrh **
2503df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
2504df199a25Sdrh **        use LIMIT.
2505df199a25Sdrh **
2506174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
2507174b6195Sdrh **
25082b300d5dSdrh **  (12)  Not implemented.  Subsumed into restriction (3).  Was previously
25092b300d5dSdrh **        a separate restriction deriving from ticket #350.
25103fc673e6Sdrh **
2511ac83963aSdrh **  (13)  The subquery and outer query do not both use LIMIT
2512ac83963aSdrh **
2513ac83963aSdrh **  (14)  The subquery does not use OFFSET
2514ac83963aSdrh **
2515ad91c6cdSdrh **  (15)  The outer query is not part of a compound select or the
2516ad91c6cdSdrh **        subquery does not have both an ORDER BY and a LIMIT clause.
2517ad91c6cdSdrh **        (See ticket #2339)
2518ad91c6cdSdrh **
2519c52e355dSdrh **  (16)  The outer query is not an aggregate or the subquery does
2520c52e355dSdrh **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
2521c52e355dSdrh **        until we introduced the group_concat() function.
2522c52e355dSdrh **
2523f23329a2Sdanielk1977 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
25244914cf92Sdanielk1977 **        compound clause made up entirely of non-aggregate queries, and
2525f23329a2Sdanielk1977 **        the parent query:
2526f23329a2Sdanielk1977 **
2527f23329a2Sdanielk1977 **          * is not itself part of a compound select,
2528f23329a2Sdanielk1977 **          * is not an aggregate or DISTINCT query, and
2529f23329a2Sdanielk1977 **          * has no other tables or sub-selects in the FROM clause.
2530f23329a2Sdanielk1977 **
25314914cf92Sdanielk1977 **        The parent and sub-query may contain WHERE clauses. Subject to
25324914cf92Sdanielk1977 **        rules (11), (13) and (14), they may also contain ORDER BY,
25334914cf92Sdanielk1977 **        LIMIT and OFFSET clauses.
2534f23329a2Sdanielk1977 **
253549fc1f60Sdanielk1977 **  (18)  If the sub-query is a compound select, then all terms of the
253649fc1f60Sdanielk1977 **        ORDER by clause of the parent must be simple references to
253749fc1f60Sdanielk1977 **        columns of the sub-query.
253849fc1f60Sdanielk1977 **
2539229cf702Sdrh **  (19)  The subquery does not use LIMIT or the outer query does not
2540229cf702Sdrh **        have a WHERE clause.
2541229cf702Sdrh **
2542832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
2543832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
2544832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
2545832508b7Sdrh **
2546665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
2547832508b7Sdrh ** If flattening is attempted this routine returns 1.
2548832508b7Sdrh **
2549832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
2550832508b7Sdrh ** the subquery before this routine runs.
25511350b030Sdrh */
25528c74a8caSdrh static int flattenSubquery(
2553524cc21eSdanielk1977   Parse *pParse,       /* Parsing context */
25548c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
25558c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
25568c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
25578c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
25588c74a8caSdrh ){
2559524cc21eSdanielk1977   const char *zSavedAuthContext = pParse->zAuthContext;
2560f23329a2Sdanielk1977   Select *pParent;
25610bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
2562f23329a2Sdanielk1977   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
2563ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
2564ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
25650bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
25666a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
256791bb0eedSdrh   int i;              /* Loop counter */
256891bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
256991bb0eedSdrh   struct SrcList_item *pSubitem;   /* The subquery */
2570524cc21eSdanielk1977   sqlite3 *db = pParse->db;
25711350b030Sdrh 
2572832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
2573832508b7Sdrh   */
2574832508b7Sdrh   if( p==0 ) return 0;
2575832508b7Sdrh   pSrc = p->pSrc;
2576ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
257791bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
257849fc1f60Sdanielk1977   iParent = pSubitem->iCursor;
257991bb0eedSdrh   pSub = pSubitem->pSelect;
2580832508b7Sdrh   assert( pSub!=0 );
2581ac83963aSdrh   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
2582ac83963aSdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
2583832508b7Sdrh   pSubSrc = pSub->pSrc;
2584832508b7Sdrh   assert( pSubSrc );
2585ac83963aSdrh   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
2586ac83963aSdrh   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
2587ac83963aSdrh   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
2588ac83963aSdrh   ** became arbitrary expressions, we were forced to add restrictions (13)
2589ac83963aSdrh   ** and (14). */
2590ac83963aSdrh   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
2591ac83963aSdrh   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
2592ad91c6cdSdrh   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
2593ad91c6cdSdrh     return 0;                                            /* Restriction (15) */
2594ad91c6cdSdrh   }
2595ac83963aSdrh   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
25967d10d5a6Sdrh   if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit)
2597ac83963aSdrh          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
2598df199a25Sdrh      return 0;
2599df199a25Sdrh   }
26007d10d5a6Sdrh   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
26017d10d5a6Sdrh      return 0;         /* Restriction (6)  */
26027d10d5a6Sdrh   }
26037d10d5a6Sdrh   if( p->pOrderBy && pSub->pOrderBy ){
2604ac83963aSdrh      return 0;                                           /* Restriction (11) */
2605ac83963aSdrh   }
2606c52e355dSdrh   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
2607229cf702Sdrh   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
2608832508b7Sdrh 
26092b300d5dSdrh   /* OBSOLETE COMMENT 1:
26102b300d5dSdrh   ** Restriction 3:  If the subquery is a join, make sure the subquery is
26118af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
26128af4d3acSdrh   ** is not allowed:
26138af4d3acSdrh   **
26148af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
26158af4d3acSdrh   **
26168af4d3acSdrh   ** If we flatten the above, we would get
26178af4d3acSdrh   **
26188af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
26198af4d3acSdrh   **
26208af4d3acSdrh   ** which is not at all the same thing.
26212b300d5dSdrh   **
26222b300d5dSdrh   ** OBSOLETE COMMENT 2:
26232b300d5dSdrh   ** Restriction 12:  If the subquery is the right operand of a left outer
26243fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
26253fc673e6Sdrh   ** An examples of why this is not allowed:
26263fc673e6Sdrh   **
26273fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
26283fc673e6Sdrh   **
26293fc673e6Sdrh   ** If we flatten the above, we would get
26303fc673e6Sdrh   **
26313fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
26323fc673e6Sdrh   **
26333fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
26343fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
26352b300d5dSdrh   **
26362b300d5dSdrh   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
26372b300d5dSdrh   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
26382b300d5dSdrh   ** is fraught with danger.  Best to avoid the whole thing.  If the
26392b300d5dSdrh   ** subquery is the right term of a LEFT JOIN, then do not flatten.
26403fc673e6Sdrh   */
26412b300d5dSdrh   if( (pSubitem->jointype & JT_OUTER)!=0 ){
26423fc673e6Sdrh     return 0;
26433fc673e6Sdrh   }
26443fc673e6Sdrh 
2645f23329a2Sdanielk1977   /* Restriction 17: If the sub-query is a compound SELECT, then it must
2646f23329a2Sdanielk1977   ** use only the UNION ALL operator. And none of the simple select queries
2647f23329a2Sdanielk1977   ** that make up the compound SELECT are allowed to be aggregate or distinct
2648f23329a2Sdanielk1977   ** queries.
2649f23329a2Sdanielk1977   */
2650f23329a2Sdanielk1977   if( pSub->pPrior ){
26517d10d5a6Sdrh     if( p->pPrior || isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
2652f23329a2Sdanielk1977       return 0;
2653f23329a2Sdanielk1977     }
2654f23329a2Sdanielk1977     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
26557d10d5a6Sdrh       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
265680b3c548Sdanielk1977        || (pSub1->pPrior && pSub1->op!=TK_ALL)
265780b3c548Sdanielk1977        || !pSub1->pSrc || pSub1->pSrc->nSrc!=1
265880b3c548Sdanielk1977       ){
2659f23329a2Sdanielk1977         return 0;
2660f23329a2Sdanielk1977       }
2661f23329a2Sdanielk1977     }
266249fc1f60Sdanielk1977 
266349fc1f60Sdanielk1977     /* Restriction 18. */
266449fc1f60Sdanielk1977     if( p->pOrderBy ){
266549fc1f60Sdanielk1977       int ii;
266649fc1f60Sdanielk1977       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
26677d10d5a6Sdrh         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
266849fc1f60Sdanielk1977       }
266949fc1f60Sdanielk1977     }
2670f23329a2Sdanielk1977   }
2671f23329a2Sdanielk1977 
26727d10d5a6Sdrh   /***** If we reach this point, flattening is permitted. *****/
26737d10d5a6Sdrh 
26747d10d5a6Sdrh   /* Authorize the subquery */
2675524cc21eSdanielk1977   pParse->zAuthContext = pSubitem->zName;
2676524cc21eSdanielk1977   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
2677524cc21eSdanielk1977   pParse->zAuthContext = zSavedAuthContext;
2678524cc21eSdanielk1977 
26797d10d5a6Sdrh   /* If the sub-query is a compound SELECT statement, then (by restrictions
26807d10d5a6Sdrh   ** 17 and 18 above) it must be a UNION ALL and the parent query must
26817d10d5a6Sdrh   ** be of the form:
2682f23329a2Sdanielk1977   **
2683f23329a2Sdanielk1977   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
2684f23329a2Sdanielk1977   **
2685f23329a2Sdanielk1977   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
2686f23329a2Sdanielk1977   ** creates N copies of the parent query without any ORDER BY, LIMIT or
2687f23329a2Sdanielk1977   ** OFFSET clauses and joins them to the left-hand-side of the original
2688f23329a2Sdanielk1977   ** using UNION ALL operators. In this case N is the number of simple
2689f23329a2Sdanielk1977   ** select statements in the compound sub-query.
2690f23329a2Sdanielk1977   */
2691f23329a2Sdanielk1977   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
2692f23329a2Sdanielk1977     Select *pNew;
2693f23329a2Sdanielk1977     ExprList *pOrderBy = p->pOrderBy;
26944b86ef1dSdanielk1977     Expr *pLimit = p->pLimit;
26954b86ef1dSdanielk1977     Expr *pOffset = p->pOffset;
2696f23329a2Sdanielk1977     Select *pPrior = p->pPrior;
2697f23329a2Sdanielk1977     p->pOrderBy = 0;
2698f23329a2Sdanielk1977     p->pSrc = 0;
2699f23329a2Sdanielk1977     p->pPrior = 0;
27004b86ef1dSdanielk1977     p->pLimit = 0;
2701f23329a2Sdanielk1977     pNew = sqlite3SelectDup(db, p);
2702f23329a2Sdanielk1977     pNew->pPrior = pPrior;
2703f23329a2Sdanielk1977     p->pPrior = pNew;
2704f23329a2Sdanielk1977     p->pOrderBy = pOrderBy;
2705f23329a2Sdanielk1977     p->op = TK_ALL;
2706f23329a2Sdanielk1977     p->pSrc = pSrc;
27074b86ef1dSdanielk1977     p->pLimit = pLimit;
27084b86ef1dSdanielk1977     p->pOffset = pOffset;
2709f23329a2Sdanielk1977     p->pRightmost = 0;
2710f23329a2Sdanielk1977     pNew->pRightmost = 0;
2711f23329a2Sdanielk1977   }
2712f23329a2Sdanielk1977 
27137d10d5a6Sdrh   /* Begin flattening the iFrom-th entry of the FROM clause
27147d10d5a6Sdrh   ** in the outer query.
2715832508b7Sdrh   */
2716f23329a2Sdanielk1977   pSub = pSub1 = pSubitem->pSelect;
2717f23329a2Sdanielk1977   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
2718f23329a2Sdanielk1977     int nSubSrc = pSubSrc->nSrc;
2719f23329a2Sdanielk1977     int jointype = 0;
2720f23329a2Sdanielk1977     pSubSrc = pSub->pSrc;
2721f23329a2Sdanielk1977     pSrc = pParent->pSrc;
2722c31c2eb8Sdrh 
2723c31c2eb8Sdrh     /* Move all of the FROM elements of the subquery into the
2724c31c2eb8Sdrh     ** the FROM clause of the outer query.  Before doing this, remember
2725c31c2eb8Sdrh     ** the cursor number for the original outer query FROM element in
2726c31c2eb8Sdrh     ** iParent.  The iParent cursor will never be used.  Subsequent code
2727c31c2eb8Sdrh     ** will scan expressions looking for iParent references and replace
2728c31c2eb8Sdrh     ** those references with expressions that resolve to the subquery FROM
2729c31c2eb8Sdrh     ** elements we are now copying in.
2730c31c2eb8Sdrh     */
2731f23329a2Sdanielk1977     if( pSrc ){
2732588a9a1aSdrh       Table *pTabToDel;
2733f23329a2Sdanielk1977       pSubitem = &pSrc->a[iFrom];
2734f23329a2Sdanielk1977       nSubSrc = pSubSrc->nSrc;
2735f23329a2Sdanielk1977       jointype = pSubitem->jointype;
2736633e6d57Sdrh       sqlite3DbFree(db, pSubitem->zDatabase);
2737633e6d57Sdrh       sqlite3DbFree(db, pSubitem->zName);
2738633e6d57Sdrh       sqlite3DbFree(db, pSubitem->zAlias);
2739cfa063b3Sdrh       pSubitem->zDatabase = 0;
2740cfa063b3Sdrh       pSubitem->zName = 0;
2741cfa063b3Sdrh       pSubitem->zAlias = 0;
2742588a9a1aSdrh 
2743588a9a1aSdrh       /* If the FROM element is a subquery, defer deleting the Table
2744588a9a1aSdrh       ** object associated with that subquery until code generation is
2745588a9a1aSdrh       ** complete, since there may still exist Expr.pTab entires that
2746588a9a1aSdrh       ** refer to the subquery even after flattening.  Ticket #3346.
2747588a9a1aSdrh       */
2748588a9a1aSdrh       if( (pTabToDel = pSubitem->pTab)!=0 ){
2749588a9a1aSdrh         if( pTabToDel->nRef==1 ){
2750588a9a1aSdrh           pTabToDel->pNextZombie = pParse->pZombieTab;
2751588a9a1aSdrh           pParse->pZombieTab = pTabToDel;
2752588a9a1aSdrh         }else{
2753588a9a1aSdrh           pTabToDel->nRef--;
2754588a9a1aSdrh         }
2755588a9a1aSdrh       }
2756588a9a1aSdrh       pSubitem->pTab = 0;
2757f23329a2Sdanielk1977     }
2758f23329a2Sdanielk1977     if( nSubSrc!=1 || !pSrc ){
2759c31c2eb8Sdrh       int extra = nSubSrc - 1;
2760f23329a2Sdanielk1977       for(i=(pSrc?1:0); i<nSubSrc; i++){
276117435752Sdrh         pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0);
2762cfa063b3Sdrh         if( pSrc==0 ){
2763f23329a2Sdanielk1977           pParent->pSrc = 0;
2764cfa063b3Sdrh           return 1;
2765cfa063b3Sdrh         }
2766c31c2eb8Sdrh       }
2767f23329a2Sdanielk1977       pParent->pSrc = pSrc;
2768c31c2eb8Sdrh       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2769c31c2eb8Sdrh         pSrc->a[i] = pSrc->a[i-extra];
2770c31c2eb8Sdrh       }
2771c31c2eb8Sdrh     }
2772c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
2773c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
2774c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2775c31c2eb8Sdrh     }
277661dfc31dSdrh     pSrc->a[iFrom].jointype = jointype;
2777c31c2eb8Sdrh 
2778c31c2eb8Sdrh     /* Now begin substituting subquery result set expressions for
2779c31c2eb8Sdrh     ** references to the iParent in the outer query.
2780c31c2eb8Sdrh     **
2781c31c2eb8Sdrh     ** Example:
2782c31c2eb8Sdrh     **
2783c31c2eb8Sdrh     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2784c31c2eb8Sdrh     **   \                     \_____________ subquery __________/          /
2785c31c2eb8Sdrh     **    \_____________________ outer query ______________________________/
2786c31c2eb8Sdrh     **
2787c31c2eb8Sdrh     ** We look at every expression in the outer query and every place we see
2788c31c2eb8Sdrh     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2789c31c2eb8Sdrh     */
2790f23329a2Sdanielk1977     pList = pParent->pEList;
2791832508b7Sdrh     for(i=0; i<pList->nExpr; i++){
27926977fea8Sdrh       Expr *pExpr;
27936977fea8Sdrh       if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
279417435752Sdrh         pList->a[i].zName =
279517435752Sdrh                sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
2796832508b7Sdrh       }
2797832508b7Sdrh     }
2798f23329a2Sdanielk1977     substExprList(db, pParent->pEList, iParent, pSub->pEList);
27991b2e0329Sdrh     if( isAgg ){
2800f23329a2Sdanielk1977       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
2801f23329a2Sdanielk1977       substExpr(db, pParent->pHaving, iParent, pSub->pEList);
28021b2e0329Sdrh     }
2803174b6195Sdrh     if( pSub->pOrderBy ){
2804f23329a2Sdanielk1977       assert( pParent->pOrderBy==0 );
2805f23329a2Sdanielk1977       pParent->pOrderBy = pSub->pOrderBy;
2806174b6195Sdrh       pSub->pOrderBy = 0;
2807f23329a2Sdanielk1977     }else if( pParent->pOrderBy ){
2808f23329a2Sdanielk1977       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
2809174b6195Sdrh     }
2810832508b7Sdrh     if( pSub->pWhere ){
281117435752Sdrh       pWhere = sqlite3ExprDup(db, pSub->pWhere);
2812832508b7Sdrh     }else{
2813832508b7Sdrh       pWhere = 0;
2814832508b7Sdrh     }
2815832508b7Sdrh     if( subqueryIsAgg ){
2816f23329a2Sdanielk1977       assert( pParent->pHaving==0 );
2817f23329a2Sdanielk1977       pParent->pHaving = pParent->pWhere;
2818f23329a2Sdanielk1977       pParent->pWhere = pWhere;
2819f23329a2Sdanielk1977       substExpr(db, pParent->pHaving, iParent, pSub->pEList);
2820f23329a2Sdanielk1977       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
282117435752Sdrh                                   sqlite3ExprDup(db, pSub->pHaving));
2822f23329a2Sdanielk1977       assert( pParent->pGroupBy==0 );
2823f23329a2Sdanielk1977       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
2824832508b7Sdrh     }else{
2825f23329a2Sdanielk1977       substExpr(db, pParent->pWhere, iParent, pSub->pEList);
2826f23329a2Sdanielk1977       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
2827832508b7Sdrh     }
2828c31c2eb8Sdrh 
2829c31c2eb8Sdrh     /* The flattened query is distinct if either the inner or the
2830c31c2eb8Sdrh     ** outer query is distinct.
2831c31c2eb8Sdrh     */
28327d10d5a6Sdrh     pParent->selFlags |= pSub->selFlags & SF_Distinct;
28338c74a8caSdrh 
2834a58fdfb1Sdanielk1977     /*
2835a58fdfb1Sdanielk1977     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2836ac83963aSdrh     **
2837ac83963aSdrh     ** One is tempted to try to add a and b to combine the limits.  But this
2838ac83963aSdrh     ** does not work if either limit is negative.
2839a58fdfb1Sdanielk1977     */
2840a2dc3b1aSdanielk1977     if( pSub->pLimit ){
2841f23329a2Sdanielk1977       pParent->pLimit = pSub->pLimit;
2842a2dc3b1aSdanielk1977       pSub->pLimit = 0;
2843df199a25Sdrh     }
2844f23329a2Sdanielk1977   }
28458c74a8caSdrh 
2846c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
2847c31c2eb8Sdrh   ** success.
2848c31c2eb8Sdrh   */
2849633e6d57Sdrh   sqlite3SelectDelete(db, pSub1);
2850f23329a2Sdanielk1977 
2851832508b7Sdrh   return 1;
28521350b030Sdrh }
28533514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
28541350b030Sdrh 
28551350b030Sdrh /*
2856a9d1ccb9Sdanielk1977 ** Analyze the SELECT statement passed as an argument to see if it
285708c88eb0Sdrh ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
2858a9d1ccb9Sdanielk1977 ** it is, or 0 otherwise. At present, a query is considered to be
2859a9d1ccb9Sdanielk1977 ** a min()/max() query if:
2860a9d1ccb9Sdanielk1977 **
2861738bdcfbSdanielk1977 **   1. There is a single object in the FROM clause.
2862738bdcfbSdanielk1977 **
2863738bdcfbSdanielk1977 **   2. There is a single expression in the result set, and it is
2864738bdcfbSdanielk1977 **      either min(x) or max(x), where x is a column reference.
2865a9d1ccb9Sdanielk1977 */
2866a9d1ccb9Sdanielk1977 static int minMaxQuery(Parse *pParse, Select *p){
2867a9d1ccb9Sdanielk1977   Expr *pExpr;
2868a9d1ccb9Sdanielk1977   ExprList *pEList = p->pEList;
2869a9d1ccb9Sdanielk1977 
287008c88eb0Sdrh   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
2871a9d1ccb9Sdanielk1977   pExpr = pEList->a[0].pExpr;
2872a9d1ccb9Sdanielk1977   pEList = pExpr->pList;
2873a9d1ccb9Sdanielk1977   if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0;
287408c88eb0Sdrh   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
287508c88eb0Sdrh   if( pExpr->token.n!=3 ) return WHERE_ORDERBY_NORMAL;
2876a9d1ccb9Sdanielk1977   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
287708c88eb0Sdrh     return WHERE_ORDERBY_MIN;
2878a9d1ccb9Sdanielk1977   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
287908c88eb0Sdrh     return WHERE_ORDERBY_MAX;
2880a9d1ccb9Sdanielk1977   }
288108c88eb0Sdrh   return WHERE_ORDERBY_NORMAL;
2882a9d1ccb9Sdanielk1977 }
2883a9d1ccb9Sdanielk1977 
2884a9d1ccb9Sdanielk1977 /*
28857d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement.
28867d10d5a6Sdrh ** "Expanding" means to do the following:
28877d10d5a6Sdrh **
28887d10d5a6Sdrh **    (1)  Make sure VDBE cursor numbers have been assigned to every
28897d10d5a6Sdrh **         element of the FROM clause.
28907d10d5a6Sdrh **
28917d10d5a6Sdrh **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
28927d10d5a6Sdrh **         defines FROM clause.  When views appear in the FROM clause,
28937d10d5a6Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
28947d10d5a6Sdrh **         that implements the view.  A copy is made of the view's SELECT
28957d10d5a6Sdrh **         statement so that we can freely modify or delete that statement
28967d10d5a6Sdrh **         without worrying about messing up the presistent representation
28977d10d5a6Sdrh **         of the view.
28987d10d5a6Sdrh **
28997d10d5a6Sdrh **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
29007d10d5a6Sdrh **         on joins and the ON and USING clause of joins.
29017d10d5a6Sdrh **
29027d10d5a6Sdrh **    (4)  Scan the list of columns in the result set (pEList) looking
29037d10d5a6Sdrh **         for instances of the "*" operator or the TABLE.* operator.
29047d10d5a6Sdrh **         If found, expand each "*" to be every column in every table
29057d10d5a6Sdrh **         and TABLE.* to be every column in TABLE.
29067d10d5a6Sdrh **
2907b3bce662Sdanielk1977 */
29087d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){
29097d10d5a6Sdrh   Parse *pParse = pWalker->pParse;
29107d10d5a6Sdrh   int i, j, k;
29117d10d5a6Sdrh   SrcList *pTabList;
29127d10d5a6Sdrh   ExprList *pEList;
29137d10d5a6Sdrh   struct SrcList_item *pFrom;
29147d10d5a6Sdrh   sqlite3 *db = pParse->db;
29157d10d5a6Sdrh 
29167d10d5a6Sdrh   if( db->mallocFailed  ){
29177d10d5a6Sdrh     return WRC_Abort;
29187d10d5a6Sdrh   }
29197d10d5a6Sdrh   if( p->pSrc==0 || (p->selFlags & SF_Expanded)!=0 ){
29207d10d5a6Sdrh     return WRC_Prune;
29217d10d5a6Sdrh   }
29227d10d5a6Sdrh   p->selFlags |= SF_Expanded;
29237d10d5a6Sdrh   pTabList = p->pSrc;
29247d10d5a6Sdrh   pEList = p->pEList;
29257d10d5a6Sdrh 
29267d10d5a6Sdrh   /* Make sure cursor numbers have been assigned to all entries in
29277d10d5a6Sdrh   ** the FROM clause of the SELECT statement.
29287d10d5a6Sdrh   */
29297d10d5a6Sdrh   sqlite3SrcListAssignCursors(pParse, pTabList);
29307d10d5a6Sdrh 
29317d10d5a6Sdrh   /* Look up every table named in the FROM clause of the select.  If
29327d10d5a6Sdrh   ** an entry of the FROM clause is a subquery instead of a table or view,
29337d10d5a6Sdrh   ** then create a transient table structure to describe the subquery.
29347d10d5a6Sdrh   */
29357d10d5a6Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
29367d10d5a6Sdrh     Table *pTab;
29377d10d5a6Sdrh     if( pFrom->pTab!=0 ){
29387d10d5a6Sdrh       /* This statement has already been prepared.  There is no need
29397d10d5a6Sdrh       ** to go further. */
29407d10d5a6Sdrh       assert( i==0 );
29417d10d5a6Sdrh       return WRC_Prune;
29427d10d5a6Sdrh     }
29437d10d5a6Sdrh     if( pFrom->zName==0 ){
29447d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
29457d10d5a6Sdrh       Select *pSel = pFrom->pSelect;
29467d10d5a6Sdrh       /* A sub-query in the FROM clause of a SELECT */
29477d10d5a6Sdrh       assert( pSel!=0 );
29487d10d5a6Sdrh       assert( pFrom->pTab==0 );
29497d10d5a6Sdrh       sqlite3WalkSelect(pWalker, pSel);
29507d10d5a6Sdrh       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
29517d10d5a6Sdrh       if( pTab==0 ) return WRC_Abort;
29527d10d5a6Sdrh       pTab->db = db;
29537d10d5a6Sdrh       pTab->nRef = 1;
29547d10d5a6Sdrh       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
29557d10d5a6Sdrh       while( pSel->pPrior ){ pSel = pSel->pPrior; }
29567d10d5a6Sdrh       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
29577d10d5a6Sdrh       pTab->iPKey = -1;
29587d10d5a6Sdrh       pTab->tabFlags |= TF_Ephemeral;
29597d10d5a6Sdrh #endif
29607d10d5a6Sdrh     }else{
29617d10d5a6Sdrh       /* An ordinary table or view name in the FROM clause */
29627d10d5a6Sdrh       assert( pFrom->pTab==0 );
29637d10d5a6Sdrh       pFrom->pTab = pTab =
29647d10d5a6Sdrh         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
29657d10d5a6Sdrh       if( pTab==0 ) return WRC_Abort;
29667d10d5a6Sdrh       pTab->nRef++;
29677d10d5a6Sdrh #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
29687d10d5a6Sdrh       if( pTab->pSelect || IsVirtual(pTab) ){
29697d10d5a6Sdrh         /* We reach here if the named table is a really a view */
29707d10d5a6Sdrh         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
29717d10d5a6Sdrh 
29727d10d5a6Sdrh         /* If pFrom->pSelect!=0 it means we are dealing with a
29737d10d5a6Sdrh         ** view within a view.  The SELECT structure has already been
29747d10d5a6Sdrh         ** copied by the outer view so we can skip the copy step here
29757d10d5a6Sdrh         ** in the inner view.
29767d10d5a6Sdrh         */
29777d10d5a6Sdrh         if( pFrom->pSelect==0 ){
29787d10d5a6Sdrh           pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
29797d10d5a6Sdrh           sqlite3WalkSelect(pWalker, pFrom->pSelect);
29807d10d5a6Sdrh         }
29817d10d5a6Sdrh       }
29827d10d5a6Sdrh #endif
29837d10d5a6Sdrh     }
29847d10d5a6Sdrh   }
29857d10d5a6Sdrh 
29867d10d5a6Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
29877d10d5a6Sdrh   */
29887d10d5a6Sdrh   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
29897d10d5a6Sdrh     return WRC_Abort;
29907d10d5a6Sdrh   }
29917d10d5a6Sdrh 
29927d10d5a6Sdrh   /* For every "*" that occurs in the column list, insert the names of
29937d10d5a6Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
29947d10d5a6Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
29957d10d5a6Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
29967d10d5a6Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
29977d10d5a6Sdrh   ** each one to the list of all columns in all tables.
29987d10d5a6Sdrh   **
29997d10d5a6Sdrh   ** The first loop just checks to see if there are any "*" operators
30007d10d5a6Sdrh   ** that need expanding.
30017d10d5a6Sdrh   */
30027d10d5a6Sdrh   for(k=0; k<pEList->nExpr; k++){
30037d10d5a6Sdrh     Expr *pE = pEList->a[k].pExpr;
30047d10d5a6Sdrh     if( pE->op==TK_ALL ) break;
30057d10d5a6Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
30067d10d5a6Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
30077d10d5a6Sdrh   }
30087d10d5a6Sdrh   if( k<pEList->nExpr ){
30097d10d5a6Sdrh     /*
30107d10d5a6Sdrh     ** If we get here it means the result set contains one or more "*"
30117d10d5a6Sdrh     ** operators that need to be expanded.  Loop through each expression
30127d10d5a6Sdrh     ** in the result set and expand them one by one.
30137d10d5a6Sdrh     */
30147d10d5a6Sdrh     struct ExprList_item *a = pEList->a;
30157d10d5a6Sdrh     ExprList *pNew = 0;
30167d10d5a6Sdrh     int flags = pParse->db->flags;
30177d10d5a6Sdrh     int longNames = (flags & SQLITE_FullColNames)!=0
30187d10d5a6Sdrh                       && (flags & SQLITE_ShortColNames)==0;
30197d10d5a6Sdrh 
30207d10d5a6Sdrh     for(k=0; k<pEList->nExpr; k++){
30217d10d5a6Sdrh       Expr *pE = a[k].pExpr;
30227d10d5a6Sdrh       if( pE->op!=TK_ALL &&
30237d10d5a6Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
30247d10d5a6Sdrh         /* This particular expression does not need to be expanded.
30257d10d5a6Sdrh         */
30267d10d5a6Sdrh         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
30277d10d5a6Sdrh         if( pNew ){
30287d10d5a6Sdrh           pNew->a[pNew->nExpr-1].zName = a[k].zName;
30297d10d5a6Sdrh         }
30307d10d5a6Sdrh         a[k].pExpr = 0;
30317d10d5a6Sdrh         a[k].zName = 0;
30327d10d5a6Sdrh       }else{
30337d10d5a6Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
30347d10d5a6Sdrh         ** expanded. */
30357d10d5a6Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
30367d10d5a6Sdrh         char *zTName;            /* text of name of TABLE */
30377d10d5a6Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
30387d10d5a6Sdrh           zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
30397d10d5a6Sdrh         }else{
30407d10d5a6Sdrh           zTName = 0;
30417d10d5a6Sdrh         }
30427d10d5a6Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
30437d10d5a6Sdrh           Table *pTab = pFrom->pTab;
30447d10d5a6Sdrh           char *zTabName = pFrom->zAlias;
30457d10d5a6Sdrh           if( zTabName==0 || zTabName[0]==0 ){
30467d10d5a6Sdrh             zTabName = pTab->zName;
30477d10d5a6Sdrh           }
30487d10d5a6Sdrh           if( db->mallocFailed ) break;
30497d10d5a6Sdrh           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
30507d10d5a6Sdrh             continue;
30517d10d5a6Sdrh           }
30527d10d5a6Sdrh           tableSeen = 1;
30537d10d5a6Sdrh           for(j=0; j<pTab->nCol; j++){
30547d10d5a6Sdrh             Expr *pExpr, *pRight;
30557d10d5a6Sdrh             char *zName = pTab->aCol[j].zName;
30567d10d5a6Sdrh 
30577d10d5a6Sdrh             /* If a column is marked as 'hidden' (currently only possible
30587d10d5a6Sdrh             ** for virtual tables), do not include it in the expanded
30597d10d5a6Sdrh             ** result-set list.
30607d10d5a6Sdrh             */
30617d10d5a6Sdrh             if( IsHiddenColumn(&pTab->aCol[j]) ){
30627d10d5a6Sdrh               assert(IsVirtual(pTab));
30637d10d5a6Sdrh               continue;
30647d10d5a6Sdrh             }
30657d10d5a6Sdrh 
30667d10d5a6Sdrh             if( i>0 ){
30677d10d5a6Sdrh               struct SrcList_item *pLeft = &pTabList->a[i-1];
30687d10d5a6Sdrh               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
30697d10d5a6Sdrh                         columnIndex(pLeft->pTab, zName)>=0 ){
30707d10d5a6Sdrh                 /* In a NATURAL join, omit the join columns from the
30717d10d5a6Sdrh                 ** table on the right */
30727d10d5a6Sdrh                 continue;
30737d10d5a6Sdrh               }
30747d10d5a6Sdrh               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
30757d10d5a6Sdrh                 /* In a join with a USING clause, omit columns in the
30767d10d5a6Sdrh                 ** using clause from the table on the right. */
30777d10d5a6Sdrh                 continue;
30787d10d5a6Sdrh               }
30797d10d5a6Sdrh             }
30807d10d5a6Sdrh             pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
30817d10d5a6Sdrh             if( pRight==0 ) break;
30827d10d5a6Sdrh             setQuotedToken(pParse, &pRight->token, zName);
30837d10d5a6Sdrh             if( longNames || pTabList->nSrc>1 ){
30847d10d5a6Sdrh               Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
30857d10d5a6Sdrh               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
30867d10d5a6Sdrh               if( pExpr==0 ) break;
30877d10d5a6Sdrh               setQuotedToken(pParse, &pLeft->token, zTabName);
30887d10d5a6Sdrh               setToken(&pExpr->span,
30897d10d5a6Sdrh                   sqlite3MPrintf(db, "%s.%s", zTabName, zName));
30907d10d5a6Sdrh               pExpr->span.dyn = 1;
30917d10d5a6Sdrh               pExpr->token.z = 0;
30927d10d5a6Sdrh               pExpr->token.n = 0;
30937d10d5a6Sdrh               pExpr->token.dyn = 0;
30947d10d5a6Sdrh             }else{
30957d10d5a6Sdrh               pExpr = pRight;
30967d10d5a6Sdrh               pExpr->span = pExpr->token;
30977d10d5a6Sdrh               pExpr->span.dyn = 0;
30987d10d5a6Sdrh             }
30997d10d5a6Sdrh             if( longNames ){
31007d10d5a6Sdrh               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
31017d10d5a6Sdrh             }else{
31027d10d5a6Sdrh               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
31037d10d5a6Sdrh             }
31047d10d5a6Sdrh           }
31057d10d5a6Sdrh         }
31067d10d5a6Sdrh         if( !tableSeen ){
31077d10d5a6Sdrh           if( zTName ){
31087d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
31097d10d5a6Sdrh           }else{
31107d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no tables specified");
31117d10d5a6Sdrh           }
31127d10d5a6Sdrh         }
31137d10d5a6Sdrh         sqlite3DbFree(db, zTName);
31147d10d5a6Sdrh       }
31157d10d5a6Sdrh     }
31167d10d5a6Sdrh     sqlite3ExprListDelete(db, pEList);
31177d10d5a6Sdrh     p->pEList = pNew;
31187d10d5a6Sdrh   }
31197d10d5a6Sdrh #if SQLITE_MAX_COLUMN
31207d10d5a6Sdrh   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
31217d10d5a6Sdrh     sqlite3ErrorMsg(pParse, "too many columns in result set");
31227d10d5a6Sdrh   }
31237d10d5a6Sdrh #endif
31247d10d5a6Sdrh   return WRC_Continue;
31257d10d5a6Sdrh }
31267d10d5a6Sdrh 
31277d10d5a6Sdrh /*
31287d10d5a6Sdrh ** No-op routine for the parse-tree walker.
31297d10d5a6Sdrh **
31307d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees
31317d10d5a6Sdrh ** are walked without any actions being taken at each node.  Presumably,
31327d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then
31337d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every
31347d10d5a6Sdrh ** subquery in the parser tree.
31357d10d5a6Sdrh */
31367d10d5a6Sdrh static int exprWalkNoop(Walker *pWalker, Expr *pExpr){
31377d10d5a6Sdrh   return WRC_Continue;
31387d10d5a6Sdrh }
31397d10d5a6Sdrh 
31407d10d5a6Sdrh /*
31417d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries.
31427d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT
31437d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above.
31447d10d5a6Sdrh **
31457d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a
31467d10d5a6Sdrh ** SELECT statement.  The SELECT statement must be expanded before
31477d10d5a6Sdrh ** name resolution is performed.
31487d10d5a6Sdrh **
31497d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse.
31507d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr
31517d10d5a6Sdrh ** and/or pParse->db->mallocFailed.
31527d10d5a6Sdrh */
31537d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
31547d10d5a6Sdrh   Walker w;
31557d10d5a6Sdrh   w.xSelectCallback = selectExpander;
31567d10d5a6Sdrh   w.xExprCallback = exprWalkNoop;
31577d10d5a6Sdrh   w.pParse = pParse;
31587d10d5a6Sdrh   sqlite3WalkSelect(&w, pSelect);
31597d10d5a6Sdrh }
31607d10d5a6Sdrh 
31617d10d5a6Sdrh 
31627d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
31637d10d5a6Sdrh /*
31647d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
31657d10d5a6Sdrh ** interface.
31667d10d5a6Sdrh **
31677d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl
31687d10d5a6Sdrh ** information to the Table structure that represents the result set
31697d10d5a6Sdrh ** of that subquery.
31707d10d5a6Sdrh **
31717d10d5a6Sdrh ** The Table structure that represents the result set was constructed
31727d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted
31737d10d5a6Sdrh ** at that point because identifiers had not yet been resolved.  This
31747d10d5a6Sdrh ** routine is called after identifier resolution.
31757d10d5a6Sdrh */
31767d10d5a6Sdrh static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
31777d10d5a6Sdrh   Parse *pParse;
31787d10d5a6Sdrh   int i;
31797d10d5a6Sdrh   SrcList *pTabList;
31807d10d5a6Sdrh   struct SrcList_item *pFrom;
31817d10d5a6Sdrh 
31829d8b3072Sdrh   assert( p->selFlags & SF_Resolved );
31837d10d5a6Sdrh   if( (p->selFlags & SF_HasTypeInfo)==0 ){
31847d10d5a6Sdrh     p->selFlags |= SF_HasTypeInfo;
31857d10d5a6Sdrh     pParse = pWalker->pParse;
31867d10d5a6Sdrh     pTabList = p->pSrc;
31877d10d5a6Sdrh     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
31887d10d5a6Sdrh       Table *pTab = pFrom->pTab;
31897d10d5a6Sdrh       if( pTab && (pTab->tabFlags & TF_Ephemeral)!=0 ){
31907d10d5a6Sdrh         /* A sub-query in the FROM clause of a SELECT */
31917d10d5a6Sdrh         Select *pSel = pFrom->pSelect;
31927d10d5a6Sdrh         assert( pSel );
31937d10d5a6Sdrh         while( pSel->pPrior ) pSel = pSel->pPrior;
31947d10d5a6Sdrh         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
31957d10d5a6Sdrh       }
31967d10d5a6Sdrh     }
31977d10d5a6Sdrh   }
31987d10d5a6Sdrh   return WRC_Continue;
31997d10d5a6Sdrh }
32007d10d5a6Sdrh #endif
32017d10d5a6Sdrh 
32027d10d5a6Sdrh 
32037d10d5a6Sdrh /*
32047d10d5a6Sdrh ** This routine adds datatype and collating sequence information to
32057d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a
32067d10d5a6Sdrh ** SELECT statement.
32077d10d5a6Sdrh **
32087d10d5a6Sdrh ** Use this routine after name resolution.
32097d10d5a6Sdrh */
32107d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
32117d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
32127d10d5a6Sdrh   Walker w;
32137d10d5a6Sdrh   w.xSelectCallback = selectAddSubqueryTypeInfo;
32147d10d5a6Sdrh   w.xExprCallback = exprWalkNoop;
32157d10d5a6Sdrh   w.pParse = pParse;
32167d10d5a6Sdrh   sqlite3WalkSelect(&w, pSelect);
32177d10d5a6Sdrh #endif
32187d10d5a6Sdrh }
32197d10d5a6Sdrh 
32207d10d5a6Sdrh 
32217d10d5a6Sdrh /*
32227d10d5a6Sdrh ** This routine sets of a SELECT statement for processing.  The
32237d10d5a6Sdrh ** following is accomplished:
32247d10d5a6Sdrh **
32257d10d5a6Sdrh **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
32267d10d5a6Sdrh **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
32277d10d5a6Sdrh **     *  ON and USING clauses are shifted into WHERE statements
32287d10d5a6Sdrh **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
32297d10d5a6Sdrh **     *  Identifiers in expression are matched to tables.
32307d10d5a6Sdrh **
32317d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT.
32327d10d5a6Sdrh */
32337d10d5a6Sdrh void sqlite3SelectPrep(
3234b3bce662Sdanielk1977   Parse *pParse,         /* The parser context */
3235b3bce662Sdanielk1977   Select *p,             /* The SELECT statement being coded. */
32367d10d5a6Sdrh   NameContext *pOuterNC  /* Name context for container */
3237b3bce662Sdanielk1977 ){
32387d10d5a6Sdrh   sqlite3 *db;
32397d10d5a6Sdrh   if( p==0 ) return;
32407d10d5a6Sdrh   db = pParse->db;
32417d10d5a6Sdrh   if( p->selFlags & SF_HasTypeInfo ) return;
32427d10d5a6Sdrh   if( pParse->nErr || db->mallocFailed ) return;
32437d10d5a6Sdrh   sqlite3SelectExpand(pParse, p);
32447d10d5a6Sdrh   if( pParse->nErr || db->mallocFailed ) return;
32457d10d5a6Sdrh   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
32467d10d5a6Sdrh   if( pParse->nErr || db->mallocFailed ) return;
32477d10d5a6Sdrh   sqlite3SelectAddTypeInfo(pParse, p);
3248f6bbe022Sdrh }
3249b3bce662Sdanielk1977 
3250b3bce662Sdanielk1977 /*
325113449892Sdrh ** Reset the aggregate accumulator.
325213449892Sdrh **
325313449892Sdrh ** The aggregate accumulator is a set of memory cells that hold
325413449892Sdrh ** intermediate results while calculating an aggregate.  This
325513449892Sdrh ** routine simply stores NULLs in all of those memory cells.
3256b3bce662Sdanielk1977 */
325713449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
325813449892Sdrh   Vdbe *v = pParse->pVdbe;
325913449892Sdrh   int i;
3260c99130fdSdrh   struct AggInfo_func *pFunc;
326113449892Sdrh   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
326213449892Sdrh     return;
326313449892Sdrh   }
326413449892Sdrh   for(i=0; i<pAggInfo->nColumn; i++){
32654c583128Sdrh     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
326613449892Sdrh   }
3267c99130fdSdrh   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
32684c583128Sdrh     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
3269c99130fdSdrh     if( pFunc->iDistinct>=0 ){
3270c99130fdSdrh       Expr *pE = pFunc->pExpr;
3271c99130fdSdrh       if( pE->pList==0 || pE->pList->nExpr!=1 ){
3272c99130fdSdrh         sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
3273c99130fdSdrh            "by an expression");
3274c99130fdSdrh         pFunc->iDistinct = -1;
3275c99130fdSdrh       }else{
3276c99130fdSdrh         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
327766a5167bSdrh         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
327866a5167bSdrh                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
3279c99130fdSdrh       }
3280c99130fdSdrh     }
328113449892Sdrh   }
3282b3bce662Sdanielk1977 }
3283b3bce662Sdanielk1977 
3284b3bce662Sdanielk1977 /*
328513449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function
328613449892Sdrh ** in the AggInfo structure.
3287b3bce662Sdanielk1977 */
328813449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
328913449892Sdrh   Vdbe *v = pParse->pVdbe;
329013449892Sdrh   int i;
329113449892Sdrh   struct AggInfo_func *pF;
329213449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
3293a10a34b8Sdrh     ExprList *pList = pF->pExpr->pList;
329466a5167bSdrh     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
329566a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
3296b3bce662Sdanielk1977   }
329713449892Sdrh }
329813449892Sdrh 
329913449892Sdrh /*
330013449892Sdrh ** Update the accumulator memory cells for an aggregate based on
330113449892Sdrh ** the current cursor position.
330213449892Sdrh */
330313449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
330413449892Sdrh   Vdbe *v = pParse->pVdbe;
330513449892Sdrh   int i;
330613449892Sdrh   struct AggInfo_func *pF;
330713449892Sdrh   struct AggInfo_col *pC;
330813449892Sdrh 
330913449892Sdrh   pAggInfo->directMode = 1;
331013449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
331113449892Sdrh     int nArg;
3312c99130fdSdrh     int addrNext = 0;
331398757157Sdrh     int regAgg;
331413449892Sdrh     ExprList *pList = pF->pExpr->pList;
331513449892Sdrh     if( pList ){
331613449892Sdrh       nArg = pList->nExpr;
3317892d3179Sdrh       regAgg = sqlite3GetTempRange(pParse, nArg);
3318191b54cbSdrh       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
331913449892Sdrh     }else{
332013449892Sdrh       nArg = 0;
332198757157Sdrh       regAgg = 0;
332213449892Sdrh     }
3323c99130fdSdrh     if( pF->iDistinct>=0 ){
3324c99130fdSdrh       addrNext = sqlite3VdbeMakeLabel(v);
3325c99130fdSdrh       assert( nArg==1 );
33262dcef11bSdrh       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
3327c99130fdSdrh     }
332813449892Sdrh     if( pF->pFunc->needCollSeq ){
332913449892Sdrh       CollSeq *pColl = 0;
333013449892Sdrh       struct ExprList_item *pItem;
333113449892Sdrh       int j;
333243617e9aSdrh       assert( pList!=0 );  /* pList!=0 if pF->pFunc->needCollSeq is true */
333343617e9aSdrh       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
333413449892Sdrh         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
333513449892Sdrh       }
333613449892Sdrh       if( !pColl ){
333713449892Sdrh         pColl = pParse->db->pDfltColl;
333813449892Sdrh       }
333966a5167bSdrh       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
334013449892Sdrh     }
334198757157Sdrh     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
334266a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
334398757157Sdrh     sqlite3VdbeChangeP5(v, nArg);
3344892d3179Sdrh     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
3345da250ea5Sdrh     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
3346c99130fdSdrh     if( addrNext ){
3347c99130fdSdrh       sqlite3VdbeResolveLabel(v, addrNext);
3348c99130fdSdrh     }
334913449892Sdrh   }
335013449892Sdrh   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
3351389a1adbSdrh     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
335213449892Sdrh   }
335313449892Sdrh   pAggInfo->directMode = 0;
335413449892Sdrh }
335513449892Sdrh 
3356b3bce662Sdanielk1977 /*
33577d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument.
33589bb61fe7Sdrh **
3359fef5208cSdrh ** The results are distributed in various ways depending on the
33606c8c8ce0Sdanielk1977 ** contents of the SelectDest structure pointed to by argument pDest
33616c8c8ce0Sdanielk1977 ** as follows:
3362fef5208cSdrh **
33636c8c8ce0Sdanielk1977 **     pDest->eDest    Result
3364fef5208cSdrh **     ------------    -------------------------------------------
33657d10d5a6Sdrh **     SRT_Output      Generate a row of output (using the OP_ResultRow
33667d10d5a6Sdrh **                     opcode) for each row in the result set.
3367fef5208cSdrh **
33687d10d5a6Sdrh **     SRT_Mem         Only valid if the result is a single column.
33697d10d5a6Sdrh **                     Store the first column of the first result row
33707d10d5a6Sdrh **                     in register pDest->iParm then abandon the rest
33717d10d5a6Sdrh **                     of the query.  This destination implies "LIMIT 1".
3372fef5208cSdrh **
33737d10d5a6Sdrh **     SRT_Set         The result must be a single column.  Store each
33747d10d5a6Sdrh **                     row of result as the key in table pDest->iParm.
33757d10d5a6Sdrh **                     Apply the affinity pDest->affinity before storing
33767d10d5a6Sdrh **                     results.  Used to implement "IN (SELECT ...)".
3377fef5208cSdrh **
33786c8c8ce0Sdanielk1977 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
337982c3d636Sdrh **
33806c8c8ce0Sdanielk1977 **     SRT_Except      Remove results from the temporary table pDest->iParm.
3381c4a3c779Sdrh **
33827d10d5a6Sdrh **     SRT_Table       Store results in temporary table pDest->iParm.
33837d10d5a6Sdrh **                     This is like SRT_EphemTab except that the table
33847d10d5a6Sdrh **                     is assumed to already be open.
33859bb61fe7Sdrh **
33866c8c8ce0Sdanielk1977 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
33876c8c8ce0Sdanielk1977 **                     the result there. The cursor is left open after
33887d10d5a6Sdrh **                     returning.  This is like SRT_Table except that
33897d10d5a6Sdrh **                     this destination uses OP_OpenEphemeral to create
33907d10d5a6Sdrh **                     the table first.
33916c8c8ce0Sdanielk1977 **
33927d10d5a6Sdrh **     SRT_Coroutine   Generate a co-routine that returns a new row of
33937d10d5a6Sdrh **                     results each time it is invoked.  The entry point
33947d10d5a6Sdrh **                     of the co-routine is stored in register pDest->iParm.
33956c8c8ce0Sdanielk1977 **
33966c8c8ce0Sdanielk1977 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
33976c8c8ce0Sdanielk1977 **                     set is not empty.
33986c8c8ce0Sdanielk1977 **
33997d10d5a6Sdrh **     SRT_Discard     Throw the results away.  This is used by SELECT
34007d10d5a6Sdrh **                     statements within triggers whose only purpose is
34017d10d5a6Sdrh **                     the side-effects of functions.
3402e78e8284Sdrh **
34039bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
34049bb61fe7Sdrh ** encountered, then an appropriate error message is left in
34059bb61fe7Sdrh ** pParse->zErrMsg.
34069bb61fe7Sdrh **
34079bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
34089bb61fe7Sdrh ** calling function needs to do that.
34099bb61fe7Sdrh */
34104adee20fSdanielk1977 int sqlite3Select(
3411cce7d176Sdrh   Parse *pParse,         /* The parser context */
34129bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
34137d10d5a6Sdrh   SelectDest *pDest      /* What to do with the query results */
3414cce7d176Sdrh ){
341513449892Sdrh   int i, j;              /* Loop counters */
341613449892Sdrh   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
341713449892Sdrh   Vdbe *v;               /* The virtual machine under construction */
3418b3bce662Sdanielk1977   int isAgg;             /* True for select lists like "count(*)" */
3419a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
3420ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
34219bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
34229bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
34232282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
34242282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
342519a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
342619a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
34271d83f052Sdrh   int rc = 1;            /* Value to return from this function */
3428b9bb7c18Sdrh   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
342913449892Sdrh   AggInfo sAggInfo;      /* Information used by aggregate queries */
3430ec7429aeSdrh   int iEnd;              /* Address of the end of the query */
343117435752Sdrh   sqlite3 *db;           /* The database connection */
34329bb61fe7Sdrh 
343317435752Sdrh   db = pParse->db;
343417435752Sdrh   if( p==0 || db->mallocFailed || pParse->nErr ){
34356f7adc8aSdrh     return 1;
34366f7adc8aSdrh   }
34374adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
343813449892Sdrh   memset(&sAggInfo, 0, sizeof(sAggInfo));
3439daffd0e5Sdrh 
34409a99334dSdrh   pOrderBy = p->pOrderBy;
34416c8c8ce0Sdanielk1977   if( IgnorableOrderby(pDest) ){
34429a99334dSdrh     p->pOrderBy = 0;
34439ed1dfa8Sdanielk1977 
34449ed1dfa8Sdanielk1977     /* In these cases the DISTINCT operator makes no difference to the
34459ed1dfa8Sdanielk1977     ** results, so remove it if it were specified.
34469ed1dfa8Sdanielk1977     */
34479ed1dfa8Sdanielk1977     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
34489ed1dfa8Sdanielk1977            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
34497d10d5a6Sdrh     p->selFlags &= ~SF_Distinct;
34509a99334dSdrh   }
34517d10d5a6Sdrh   sqlite3SelectPrep(pParse, p, 0);
34527d10d5a6Sdrh   if( pParse->nErr ){
34539a99334dSdrh     goto select_end;
34549a99334dSdrh   }
34559a99334dSdrh   p->pOrderBy = pOrderBy;
34569a99334dSdrh 
3457daf79acbSdanielk1977 
345882c3d636Sdrh   /* Make local copies of the parameters for this query.
345982c3d636Sdrh   */
34609bb61fe7Sdrh   pTabList = p->pSrc;
34617d10d5a6Sdrh   isAgg = (p->selFlags & SF_Aggregate)!=0;
3462b3bce662Sdanielk1977   pEList = p->pEList;
3463b3bce662Sdanielk1977   if( pEList==0 ) goto select_end;
34649bb61fe7Sdrh 
34659bb61fe7Sdrh   /*
34669bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
34679bb61fe7Sdrh   ** errors before this routine starts.
34689bb61fe7Sdrh   */
34691d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
3470cce7d176Sdrh 
3471c926afbcSdrh   /* ORDER BY is ignored for some destinations.
34722282792aSdrh   */
34736c8c8ce0Sdanielk1977   if( IgnorableOrderby(pDest) ){
3474acd4c695Sdrh     pOrderBy = 0;
34752282792aSdrh   }
34762282792aSdrh 
3477d820cb1bSdrh   /* Begin generating code.
3478d820cb1bSdrh   */
34794adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
3480d820cb1bSdrh   if( v==0 ) goto select_end;
3481d820cb1bSdrh 
3482d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
3483d820cb1bSdrh   */
348451522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3485f23329a2Sdanielk1977   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
348613449892Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
34871013c932Sdrh     SelectDest dest;
3488daf79acbSdanielk1977     Select *pSub = pItem->pSelect;
3489f23329a2Sdanielk1977     int isAggSub;
3490c31c2eb8Sdrh 
3491daf79acbSdanielk1977     if( pSub==0 || pItem->isPopulated ) continue;
3492daf79acbSdanielk1977 
3493fc976065Sdanielk1977     /* Increment Parse.nHeight by the height of the largest expression
3494fc976065Sdanielk1977     ** tree refered to by this, the parent select. The child select
3495fc976065Sdanielk1977     ** may contain expression trees of at most
3496fc976065Sdanielk1977     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
3497fc976065Sdanielk1977     ** more conservative than necessary, but much easier than enforcing
3498fc976065Sdanielk1977     ** an exact limit.
3499fc976065Sdanielk1977     */
3500fc976065Sdanielk1977     pParse->nHeight += sqlite3SelectExprHeight(p);
3501daf79acbSdanielk1977 
3502daf79acbSdanielk1977     /* Check to see if the subquery can be absorbed into the parent. */
35037d10d5a6Sdrh     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
3504524cc21eSdanielk1977     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
3505f23329a2Sdanielk1977       if( isAggSub ){
35067d10d5a6Sdrh         isAgg = 1;
35077d10d5a6Sdrh         p->selFlags |= SF_Aggregate;
3508daf79acbSdanielk1977       }
3509daf79acbSdanielk1977       i = -1;
3510daf79acbSdanielk1977     }else{
35111013c932Sdrh       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
35127d10d5a6Sdrh       assert( pItem->isPopulated==0 );
35137d10d5a6Sdrh       sqlite3Select(pParse, pSub, &dest);
35147d10d5a6Sdrh       pItem->isPopulated = 1;
3515daf79acbSdanielk1977     }
3516524cc21eSdanielk1977     if( pParse->nErr || db->mallocFailed ){
3517cfa063b3Sdrh       goto select_end;
3518cfa063b3Sdrh     }
3519fc976065Sdanielk1977     pParse->nHeight -= sqlite3SelectExprHeight(p);
3520832508b7Sdrh     pTabList = p->pSrc;
35216c8c8ce0Sdanielk1977     if( !IgnorableOrderby(pDest) ){
3522832508b7Sdrh       pOrderBy = p->pOrderBy;
3523acd4c695Sdrh     }
3524daf79acbSdanielk1977   }
3525daf79acbSdanielk1977   pEList = p->pEList;
3526daf79acbSdanielk1977 #endif
3527daf79acbSdanielk1977   pWhere = p->pWhere;
3528832508b7Sdrh   pGroupBy = p->pGroupBy;
3529832508b7Sdrh   pHaving = p->pHaving;
35307d10d5a6Sdrh   isDistinct = (p->selFlags & SF_Distinct)!=0;
3531832508b7Sdrh 
3532f23329a2Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
3533f23329a2Sdanielk1977   /* If there is are a sequence of queries, do the earlier ones first.
3534f23329a2Sdanielk1977   */
3535f23329a2Sdanielk1977   if( p->pPrior ){
3536f23329a2Sdanielk1977     if( p->pRightmost==0 ){
3537f23329a2Sdanielk1977       Select *pLoop, *pRight = 0;
3538f23329a2Sdanielk1977       int cnt = 0;
3539f23329a2Sdanielk1977       int mxSelect;
3540f23329a2Sdanielk1977       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
3541f23329a2Sdanielk1977         pLoop->pRightmost = p;
3542f23329a2Sdanielk1977         pLoop->pNext = pRight;
3543f23329a2Sdanielk1977         pRight = pLoop;
3544f23329a2Sdanielk1977       }
3545f23329a2Sdanielk1977       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
3546f23329a2Sdanielk1977       if( mxSelect && cnt>mxSelect ){
3547f23329a2Sdanielk1977         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
3548f23329a2Sdanielk1977         return 1;
3549f23329a2Sdanielk1977       }
3550f23329a2Sdanielk1977     }
3551a9671a22Sdrh     return multiSelect(pParse, p, pDest);
3552f23329a2Sdanielk1977   }
3553f23329a2Sdanielk1977 #endif
3554f23329a2Sdanielk1977 
35554914cf92Sdanielk1977   /* If writing to memory or generating a set
35564914cf92Sdanielk1977   ** only a single column may be output.
35574914cf92Sdanielk1977   */
35584914cf92Sdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
35594914cf92Sdanielk1977   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
35604914cf92Sdanielk1977     goto select_end;
35614914cf92Sdanielk1977   }
35624914cf92Sdanielk1977 #endif
35634914cf92Sdanielk1977 
35640318d441Sdanielk1977   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
35657d10d5a6Sdrh   ** GROUP BY might use an index, DISTINCT never does.
35663c4809a2Sdanielk1977   */
35677d10d5a6Sdrh   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct && !p->pGroupBy ){
35683c4809a2Sdanielk1977     p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
35693c4809a2Sdanielk1977     pGroupBy = p->pGroupBy;
35707d10d5a6Sdrh     p->selFlags &= ~SF_Distinct;
35713c4809a2Sdanielk1977     isDistinct = 0;
35723c4809a2Sdanielk1977   }
35733c4809a2Sdanielk1977 
35748b4c40d8Sdrh   /* If there is an ORDER BY clause, then this sorting
35758b4c40d8Sdrh   ** index might end up being unused if the data can be
35769d2985c7Sdrh   ** extracted in pre-sorted order.  If that is the case, then the
3577b9bb7c18Sdrh   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
35789d2985c7Sdrh   ** we figure out that the sorting index is not needed.  The addrSortIndex
35799d2985c7Sdrh   ** variable is used to facilitate that change.
35807cedc8d4Sdanielk1977   */
35817cedc8d4Sdanielk1977   if( pOrderBy ){
35820342b1f5Sdrh     KeyInfo *pKeyInfo;
35830342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
35849d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
3585b9bb7c18Sdrh     p->addrOpenEphm[2] = addrSortIndex =
358666a5167bSdrh       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
358766a5167bSdrh                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
358866a5167bSdrh                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
35899d2985c7Sdrh   }else{
35909d2985c7Sdrh     addrSortIndex = -1;
35917cedc8d4Sdanielk1977   }
35927cedc8d4Sdanielk1977 
35932d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
35942d0794e3Sdrh   */
35956c8c8ce0Sdanielk1977   if( pDest->eDest==SRT_EphemTab ){
359666a5167bSdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
35972d0794e3Sdrh   }
35982d0794e3Sdrh 
3599f42bacc2Sdrh   /* Set the limiter.
3600f42bacc2Sdrh   */
3601f42bacc2Sdrh   iEnd = sqlite3VdbeMakeLabel(v);
3602f42bacc2Sdrh   computeLimitRegisters(pParse, p, iEnd);
3603f42bacc2Sdrh 
3604dece1a84Sdrh   /* Open a virtual index to use for the distinct set.
3605cce7d176Sdrh   */
360619a775c2Sdrh   if( isDistinct ){
36070342b1f5Sdrh     KeyInfo *pKeyInfo;
36083c4809a2Sdanielk1977     assert( isAgg || pGroupBy );
3609832508b7Sdrh     distinct = pParse->nTab++;
36100342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
361166a5167bSdrh     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
361266a5167bSdrh                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
3613832508b7Sdrh   }else{
3614832508b7Sdrh     distinct = -1;
3615efb7251dSdrh   }
3616832508b7Sdrh 
361713449892Sdrh   /* Aggregate and non-aggregate queries are handled differently */
361813449892Sdrh   if( !isAgg && pGroupBy==0 ){
361913449892Sdrh     /* This case is for non-aggregate queries
362013449892Sdrh     ** Begin the database scan
3621832508b7Sdrh     */
3622a9d1ccb9Sdanielk1977     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
36231d83f052Sdrh     if( pWInfo==0 ) goto select_end;
3624cce7d176Sdrh 
3625b9bb7c18Sdrh     /* If sorting index that was created by a prior OP_OpenEphemeral
3626b9bb7c18Sdrh     ** instruction ended up not being needed, then change the OP_OpenEphemeral
36279d2985c7Sdrh     ** into an OP_Noop.
36289d2985c7Sdrh     */
36299d2985c7Sdrh     if( addrSortIndex>=0 && pOrderBy==0 ){
3630f8875400Sdrh       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
3631b9bb7c18Sdrh       p->addrOpenEphm[2] = -1;
36329d2985c7Sdrh     }
36339d2985c7Sdrh 
363413449892Sdrh     /* Use the standard inner loop
3635cce7d176Sdrh     */
36363c4809a2Sdanielk1977     assert(!isDistinct);
3637d2b3e23bSdrh     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
3638a9671a22Sdrh                     pWInfo->iContinue, pWInfo->iBreak);
36392282792aSdrh 
3640cce7d176Sdrh     /* End the database scan loop.
3641cce7d176Sdrh     */
36424adee20fSdanielk1977     sqlite3WhereEnd(pWInfo);
364313449892Sdrh   }else{
364413449892Sdrh     /* This is the processing for aggregate queries */
364513449892Sdrh     NameContext sNC;    /* Name context for processing aggregate information */
364613449892Sdrh     int iAMem;          /* First Mem address for storing current GROUP BY */
364713449892Sdrh     int iBMem;          /* First Mem address for previous GROUP BY */
364813449892Sdrh     int iUseFlag;       /* Mem address holding flag indicating that at least
364913449892Sdrh                         ** one row of the input to the aggregator has been
365013449892Sdrh                         ** processed */
365113449892Sdrh     int iAbortFlag;     /* Mem address which causes query abort if positive */
365213449892Sdrh     int groupBySort;    /* Rows come from source in GROUP BY order */
3653cce7d176Sdrh 
365413449892Sdrh 
365513449892Sdrh     /* The following variables hold addresses or labels for parts of the
365613449892Sdrh     ** virtual machine program we are putting together */
365713449892Sdrh     int addrOutputRow;      /* Start of subroutine that outputs a result row */
365816ee60ffSdrh     int regOutputRow;       /* Return address register for output subroutine */
365913449892Sdrh     int addrSetAbort;       /* Set the abort flag and return */
366013449892Sdrh     int addrInitializeLoop; /* Start of code that initializes the input loop */
366113449892Sdrh     int addrTopOfLoop;      /* Top of the input loop */
366213449892Sdrh     int addrEnd;            /* End of all processing */
3663b9bb7c18Sdrh     int addrSortingIdx;     /* The OP_OpenEphemeral for the sorting index */
3664e313382eSdrh     int addrReset;          /* Subroutine for resetting the accumulator */
36652eb95377Sdrh     int regReset;           /* Return address register for reset subroutine */
366613449892Sdrh 
366713449892Sdrh     addrEnd = sqlite3VdbeMakeLabel(v);
366813449892Sdrh 
366913449892Sdrh     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
367013449892Sdrh     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
367113449892Sdrh     ** SELECT statement.
36722282792aSdrh     */
367313449892Sdrh     memset(&sNC, 0, sizeof(sNC));
367413449892Sdrh     sNC.pParse = pParse;
367513449892Sdrh     sNC.pSrcList = pTabList;
367613449892Sdrh     sNC.pAggInfo = &sAggInfo;
367713449892Sdrh     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
36789d2985c7Sdrh     sAggInfo.pGroupBy = pGroupBy;
3679d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pEList);
3680d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
3681d2b3e23bSdrh     if( pHaving ){
3682d2b3e23bSdrh       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
368313449892Sdrh     }
368413449892Sdrh     sAggInfo.nAccumulator = sAggInfo.nColumn;
368513449892Sdrh     for(i=0; i<sAggInfo.nFunc; i++){
3686d2b3e23bSdrh       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList);
368713449892Sdrh     }
368817435752Sdrh     if( db->mallocFailed ) goto select_end;
368913449892Sdrh 
369013449892Sdrh     /* Processing for aggregates with GROUP BY is very different and
36913c4809a2Sdanielk1977     ** much more complex than aggregates without a GROUP BY.
369213449892Sdrh     */
369313449892Sdrh     if( pGroupBy ){
369413449892Sdrh       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
369516ee60ffSdrh       int j1;
369613449892Sdrh 
369713449892Sdrh       /* Create labels that we will be needing
369813449892Sdrh       */
369913449892Sdrh       addrInitializeLoop = sqlite3VdbeMakeLabel(v);
370013449892Sdrh 
370113449892Sdrh       /* If there is a GROUP BY clause we might need a sorting index to
370213449892Sdrh       ** implement it.  Allocate that sorting index now.  If it turns out
3703b9bb7c18Sdrh       ** that we do not need it after all, the OpenEphemeral instruction
370413449892Sdrh       ** will be converted into a Noop.
370513449892Sdrh       */
370613449892Sdrh       sAggInfo.sortingIdx = pParse->nTab++;
370713449892Sdrh       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
3708cd3e8f7cSdanielk1977       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
3709cd3e8f7cSdanielk1977           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
3710cd3e8f7cSdanielk1977           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
371113449892Sdrh 
371213449892Sdrh       /* Initialize memory locations used by GROUP BY aggregate processing
371313449892Sdrh       */
37140a07c107Sdrh       iUseFlag = ++pParse->nMem;
37150a07c107Sdrh       iAbortFlag = ++pParse->nMem;
37160a07c107Sdrh       iAMem = pParse->nMem + 1;
371713449892Sdrh       pParse->nMem += pGroupBy->nExpr;
37180a07c107Sdrh       iBMem = pParse->nMem + 1;
371913449892Sdrh       pParse->nMem += pGroupBy->nExpr;
37204c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
3721d4e70ebdSdrh       VdbeComment((v, "clear abort flag"));
37224c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
3723d4e70ebdSdrh       VdbeComment((v, "indicate accumulator empty"));
372466a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrInitializeLoop);
372513449892Sdrh 
372613449892Sdrh       /* Generate a subroutine that outputs a single row of the result
372713449892Sdrh       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
372813449892Sdrh       ** is less than or equal to zero, the subroutine is a no-op.  If
372913449892Sdrh       ** the processing calls for the query to abort, this subroutine
373013449892Sdrh       ** increments the iAbortFlag memory location before returning in
373113449892Sdrh       ** order to signal the caller to abort.
373213449892Sdrh       */
373313449892Sdrh       addrSetAbort = sqlite3VdbeCurrentAddr(v);
37344c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
3735d4e70ebdSdrh       VdbeComment((v, "set abort flag"));
37362eb95377Sdrh       regOutputRow = ++pParse->nMem;
37372eb95377Sdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
373813449892Sdrh       addrOutputRow = sqlite3VdbeCurrentAddr(v);
37393c84ddffSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
3740d4e70ebdSdrh       VdbeComment((v, "Groupby result generator entry point"));
37412eb95377Sdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
374213449892Sdrh       finalizeAggFunctions(pParse, &sAggInfo);
374313449892Sdrh       if( pHaving ){
374435573356Sdrh         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
374513449892Sdrh       }
3746d2b3e23bSdrh       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
37476c8c8ce0Sdanielk1977                       distinct, pDest,
3748a9671a22Sdrh                       addrOutputRow+1, addrSetAbort);
37492eb95377Sdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
3750d4e70ebdSdrh       VdbeComment((v, "end groupby result generator"));
375113449892Sdrh 
3752e313382eSdrh       /* Generate a subroutine that will reset the group-by accumulator
3753e313382eSdrh       */
3754e313382eSdrh       addrReset = sqlite3VdbeCurrentAddr(v);
37552eb95377Sdrh       regReset = ++pParse->nMem;
3756e313382eSdrh       resetAccumulator(pParse, &sAggInfo);
37572eb95377Sdrh       sqlite3VdbeAddOp1(v, OP_Return, regReset);
3758e313382eSdrh 
375913449892Sdrh       /* Begin a loop that will extract all source rows in GROUP BY order.
376013449892Sdrh       ** This might involve two separate loops with an OP_Sort in between, or
376113449892Sdrh       ** it might be a single loop that uses an index to extract information
376213449892Sdrh       ** in the right order to begin with.
376313449892Sdrh       */
376413449892Sdrh       sqlite3VdbeResolveLabel(v, addrInitializeLoop);
37652eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
3766a9d1ccb9Sdanielk1977       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
37675360ad34Sdrh       if( pWInfo==0 ) goto select_end;
376813449892Sdrh       if( pGroupBy==0 ){
376913449892Sdrh         /* The optimizer is able to deliver rows in group by order so
3770b9bb7c18Sdrh         ** we do not have to sort.  The OP_OpenEphemeral table will be
377113449892Sdrh         ** cancelled later because we still need to use the pKeyInfo
377213449892Sdrh         */
377313449892Sdrh         pGroupBy = p->pGroupBy;
377413449892Sdrh         groupBySort = 0;
377513449892Sdrh       }else{
377613449892Sdrh         /* Rows are coming out in undetermined order.  We have to push
377713449892Sdrh         ** each row into a sorting index, terminate the first loop,
377813449892Sdrh         ** then loop over the sorting index in order to get the output
377913449892Sdrh         ** in sorted order
378013449892Sdrh         */
3781892d3179Sdrh         int regBase;
3782892d3179Sdrh         int regRecord;
3783892d3179Sdrh         int nCol;
3784892d3179Sdrh         int nGroupBy;
3785892d3179Sdrh 
378613449892Sdrh         groupBySort = 1;
3787892d3179Sdrh         nGroupBy = pGroupBy->nExpr;
3788892d3179Sdrh         nCol = nGroupBy + 1;
3789892d3179Sdrh         j = nGroupBy+1;
379013449892Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
3791892d3179Sdrh           if( sAggInfo.aCol[i].iSorterColumn>=j ){
3792892d3179Sdrh             nCol++;
379313449892Sdrh             j++;
379413449892Sdrh           }
3795892d3179Sdrh         }
3796892d3179Sdrh         regBase = sqlite3GetTempRange(pParse, nCol);
3797191b54cbSdrh         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
3798892d3179Sdrh         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
3799892d3179Sdrh         j = nGroupBy+1;
3800892d3179Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
3801892d3179Sdrh           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
3802892d3179Sdrh           if( pCol->iSorterColumn>=j ){
3803e55cbd72Sdrh             int r1 = j + regBase;
38046a012f04Sdrh             int r2;
3805701bb3b4Sdrh 
38066a012f04Sdrh             r2 = sqlite3ExprCodeGetColumn(pParse,
38076a012f04Sdrh                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
38086a012f04Sdrh             if( r1!=r2 ){
38096a012f04Sdrh               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
38106a012f04Sdrh             }
38116a012f04Sdrh             j++;
3812892d3179Sdrh           }
3813892d3179Sdrh         }
3814892d3179Sdrh         regRecord = sqlite3GetTempReg(pParse);
38151db639ceSdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
3816892d3179Sdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
3817892d3179Sdrh         sqlite3ReleaseTempReg(pParse, regRecord);
3818892d3179Sdrh         sqlite3ReleaseTempRange(pParse, regBase, nCol);
381913449892Sdrh         sqlite3WhereEnd(pWInfo);
382066a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
3821d4e70ebdSdrh         VdbeComment((v, "GROUP BY sort"));
382213449892Sdrh         sAggInfo.useSortingIdx = 1;
382313449892Sdrh       }
382413449892Sdrh 
382513449892Sdrh       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
382613449892Sdrh       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
382713449892Sdrh       ** Then compare the current GROUP BY terms against the GROUP BY terms
382813449892Sdrh       ** from the previous row currently stored in a0, a1, a2...
382913449892Sdrh       */
383013449892Sdrh       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
383113449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
383213449892Sdrh         if( groupBySort ){
38332dcef11bSdrh           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
383413449892Sdrh         }else{
383513449892Sdrh           sAggInfo.directMode = 1;
38362dcef11bSdrh           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
383713449892Sdrh         }
383813449892Sdrh       }
383916ee60ffSdrh       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
3840b21e7c70Sdrh                           (char*)pKeyInfo, P4_KEYINFO);
384116ee60ffSdrh       j1 = sqlite3VdbeCurrentAddr(v);
384216ee60ffSdrh       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
384313449892Sdrh 
384413449892Sdrh       /* Generate code that runs whenever the GROUP BY changes.
3845e00ee6ebSdrh       ** Changes in the GROUP BY are detected by the previous code
384613449892Sdrh       ** block.  If there were no changes, this block is skipped.
384713449892Sdrh       **
384813449892Sdrh       ** This code copies current group by terms in b0,b1,b2,...
384913449892Sdrh       ** over to a0,a1,a2.  It then calls the output subroutine
385013449892Sdrh       ** and resets the aggregate accumulator registers in preparation
385113449892Sdrh       ** for the next GROUP BY batch.
385213449892Sdrh       */
3853b21e7c70Sdrh       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
38542eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
3855d4e70ebdSdrh       VdbeComment((v, "output one row"));
38563c84ddffSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
3857d4e70ebdSdrh       VdbeComment((v, "check abort flag"));
38582eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
3859d4e70ebdSdrh       VdbeComment((v, "reset accumulator"));
386013449892Sdrh 
386113449892Sdrh       /* Update the aggregate accumulators based on the content of
386213449892Sdrh       ** the current row
386313449892Sdrh       */
386416ee60ffSdrh       sqlite3VdbeJumpHere(v, j1);
386513449892Sdrh       updateAccumulator(pParse, &sAggInfo);
38664c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
3867d4e70ebdSdrh       VdbeComment((v, "indicate data in accumulator"));
386813449892Sdrh 
386913449892Sdrh       /* End of the loop
387013449892Sdrh       */
387113449892Sdrh       if( groupBySort ){
387266a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
387313449892Sdrh       }else{
387413449892Sdrh         sqlite3WhereEnd(pWInfo);
3875f8875400Sdrh         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
387613449892Sdrh       }
387713449892Sdrh 
387813449892Sdrh       /* Output the final row of result
387913449892Sdrh       */
38802eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
3881d4e70ebdSdrh       VdbeComment((v, "output final row"));
388213449892Sdrh 
388313449892Sdrh     } /* endif pGroupBy */
388413449892Sdrh     else {
3885a9d1ccb9Sdanielk1977       ExprList *pMinMax = 0;
3886dba0137eSdanielk1977       ExprList *pDel = 0;
3887a9d1ccb9Sdanielk1977       u8 flag;
3888a9d1ccb9Sdanielk1977 
3889738bdcfbSdanielk1977       /* Check if the query is of one of the following forms:
3890738bdcfbSdanielk1977       **
3891738bdcfbSdanielk1977       **   SELECT min(x) FROM ...
3892738bdcfbSdanielk1977       **   SELECT max(x) FROM ...
3893738bdcfbSdanielk1977       **
3894738bdcfbSdanielk1977       ** If it is, then ask the code in where.c to attempt to sort results
3895738bdcfbSdanielk1977       ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
3896738bdcfbSdanielk1977       ** If where.c is able to produce results sorted in this order, then
3897738bdcfbSdanielk1977       ** add vdbe code to break out of the processing loop after the
3898738bdcfbSdanielk1977       ** first iteration (since the first iteration of the loop is
3899738bdcfbSdanielk1977       ** guaranteed to operate on the row with the minimum or maximum
3900738bdcfbSdanielk1977       ** value of x, the only row required).
3901738bdcfbSdanielk1977       **
3902738bdcfbSdanielk1977       ** A special flag must be passed to sqlite3WhereBegin() to slightly
3903738bdcfbSdanielk1977       ** modify behaviour as follows:
3904738bdcfbSdanielk1977       **
3905738bdcfbSdanielk1977       **   + If the query is a "SELECT min(x)", then the loop coded by
3906738bdcfbSdanielk1977       **     where.c should not iterate over any values with a NULL value
3907738bdcfbSdanielk1977       **     for x.
3908738bdcfbSdanielk1977       **
3909738bdcfbSdanielk1977       **   + The optimizer code in where.c (the thing that decides which
3910738bdcfbSdanielk1977       **     index or indices to use) should place a different priority on
3911738bdcfbSdanielk1977       **     satisfying the 'ORDER BY' clause than it does in other cases.
3912738bdcfbSdanielk1977       **     Refer to code and comments in where.c for details.
3913738bdcfbSdanielk1977       */
3914a9d1ccb9Sdanielk1977       flag = minMaxQuery(pParse, p);
3915a9d1ccb9Sdanielk1977       if( flag ){
39168cc74322Sdrh         pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList);
39170e359b30Sdrh         if( pMinMax && !db->mallocFailed ){
39180880a746Sdrh           pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN;
3919a9d1ccb9Sdanielk1977           pMinMax->a[0].pExpr->op = TK_COLUMN;
3920a9d1ccb9Sdanielk1977         }
39211013c932Sdrh       }
3922a9d1ccb9Sdanielk1977 
392313449892Sdrh       /* This case runs if the aggregate has no GROUP BY clause.  The
392413449892Sdrh       ** processing is much simpler since there is only a single row
392513449892Sdrh       ** of output.
392613449892Sdrh       */
392713449892Sdrh       resetAccumulator(pParse, &sAggInfo);
3928a9d1ccb9Sdanielk1977       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
3929dba0137eSdanielk1977       if( pWInfo==0 ){
3930633e6d57Sdrh         sqlite3ExprListDelete(db, pDel);
3931dba0137eSdanielk1977         goto select_end;
3932dba0137eSdanielk1977       }
393313449892Sdrh       updateAccumulator(pParse, &sAggInfo);
3934a9d1ccb9Sdanielk1977       if( !pMinMax && flag ){
3935a9d1ccb9Sdanielk1977         sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
393608c88eb0Sdrh         VdbeComment((v, "%s() by index",(flag==WHERE_ORDERBY_MIN?"min":"max")));
3937a9d1ccb9Sdanielk1977       }
393813449892Sdrh       sqlite3WhereEnd(pWInfo);
393913449892Sdrh       finalizeAggFunctions(pParse, &sAggInfo);
394013449892Sdrh       pOrderBy = 0;
39415774b806Sdrh       if( pHaving ){
394235573356Sdrh         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
39435774b806Sdrh       }
394413449892Sdrh       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
3945a9671a22Sdrh                       pDest, addrEnd, addrEnd);
3946a9d1ccb9Sdanielk1977 
3947633e6d57Sdrh       sqlite3ExprListDelete(db, pDel);
394813449892Sdrh     }
394913449892Sdrh     sqlite3VdbeResolveLabel(v, addrEnd);
395013449892Sdrh 
395113449892Sdrh   } /* endif aggregate query */
39522282792aSdrh 
3953cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
3954cce7d176Sdrh   ** and send them to the callback one by one.
3955cce7d176Sdrh   */
3956cce7d176Sdrh   if( pOrderBy ){
39576c8c8ce0Sdanielk1977     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
3958cce7d176Sdrh   }
39596a535340Sdrh 
3960ec7429aeSdrh   /* Jump here to skip this query
3961ec7429aeSdrh   */
3962ec7429aeSdrh   sqlite3VdbeResolveLabel(v, iEnd);
3963ec7429aeSdrh 
39641d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
39651d83f052Sdrh   ** to indicate no errors.
39661d83f052Sdrh   */
39671d83f052Sdrh   rc = 0;
39681d83f052Sdrh 
39691d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
39701d83f052Sdrh   ** successful coding of the SELECT.
39711d83f052Sdrh   */
39721d83f052Sdrh select_end:
3973955de52cSdanielk1977 
39747d10d5a6Sdrh   /* Identify column names if results of the SELECT are to be output.
3975955de52cSdanielk1977   */
39767d10d5a6Sdrh   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
3977955de52cSdanielk1977     generateColumnNames(pParse, pTabList, pEList);
3978955de52cSdanielk1977   }
3979955de52cSdanielk1977 
3980633e6d57Sdrh   sqlite3DbFree(db, sAggInfo.aCol);
3981633e6d57Sdrh   sqlite3DbFree(db, sAggInfo.aFunc);
39821d83f052Sdrh   return rc;
3983cce7d176Sdrh }
3984485f0039Sdrh 
398577a2a5e7Sdrh #if defined(SQLITE_DEBUG)
3986485f0039Sdrh /*
3987485f0039Sdrh *******************************************************************************
3988485f0039Sdrh ** The following code is used for testing and debugging only.  The code
3989485f0039Sdrh ** that follows does not appear in normal builds.
3990485f0039Sdrh **
3991485f0039Sdrh ** These routines are used to print out the content of all or part of a
3992485f0039Sdrh ** parse structures such as Select or Expr.  Such printouts are useful
3993485f0039Sdrh ** for helping to understand what is happening inside the code generator
3994485f0039Sdrh ** during the execution of complex SELECT statements.
3995485f0039Sdrh **
3996485f0039Sdrh ** These routine are not called anywhere from within the normal
3997485f0039Sdrh ** code base.  Then are intended to be called from within the debugger
3998485f0039Sdrh ** or from temporary "printf" statements inserted for debugging.
3999485f0039Sdrh */
4000dafc0ce8Sdrh void sqlite3PrintExpr(Expr *p){
4001485f0039Sdrh   if( p->token.z && p->token.n>0 ){
4002485f0039Sdrh     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
4003485f0039Sdrh   }else{
4004485f0039Sdrh     sqlite3DebugPrintf("(%d", p->op);
4005485f0039Sdrh   }
4006485f0039Sdrh   if( p->pLeft ){
4007485f0039Sdrh     sqlite3DebugPrintf(" ");
4008485f0039Sdrh     sqlite3PrintExpr(p->pLeft);
4009485f0039Sdrh   }
4010485f0039Sdrh   if( p->pRight ){
4011485f0039Sdrh     sqlite3DebugPrintf(" ");
4012485f0039Sdrh     sqlite3PrintExpr(p->pRight);
4013485f0039Sdrh   }
4014485f0039Sdrh   sqlite3DebugPrintf(")");
4015485f0039Sdrh }
4016dafc0ce8Sdrh void sqlite3PrintExprList(ExprList *pList){
4017485f0039Sdrh   int i;
4018485f0039Sdrh   for(i=0; i<pList->nExpr; i++){
4019485f0039Sdrh     sqlite3PrintExpr(pList->a[i].pExpr);
4020485f0039Sdrh     if( i<pList->nExpr-1 ){
4021485f0039Sdrh       sqlite3DebugPrintf(", ");
4022485f0039Sdrh     }
4023485f0039Sdrh   }
4024485f0039Sdrh }
4025dafc0ce8Sdrh void sqlite3PrintSelect(Select *p, int indent){
4026485f0039Sdrh   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
4027485f0039Sdrh   sqlite3PrintExprList(p->pEList);
4028485f0039Sdrh   sqlite3DebugPrintf("\n");
4029485f0039Sdrh   if( p->pSrc ){
4030485f0039Sdrh     char *zPrefix;
4031485f0039Sdrh     int i;
4032485f0039Sdrh     zPrefix = "FROM";
4033485f0039Sdrh     for(i=0; i<p->pSrc->nSrc; i++){
4034485f0039Sdrh       struct SrcList_item *pItem = &p->pSrc->a[i];
4035485f0039Sdrh       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
4036485f0039Sdrh       zPrefix = "";
4037485f0039Sdrh       if( pItem->pSelect ){
4038485f0039Sdrh         sqlite3DebugPrintf("(\n");
4039485f0039Sdrh         sqlite3PrintSelect(pItem->pSelect, indent+10);
4040485f0039Sdrh         sqlite3DebugPrintf("%*s)", indent+8, "");
4041485f0039Sdrh       }else if( pItem->zName ){
4042485f0039Sdrh         sqlite3DebugPrintf("%s", pItem->zName);
4043485f0039Sdrh       }
4044485f0039Sdrh       if( pItem->pTab ){
4045485f0039Sdrh         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
4046485f0039Sdrh       }
4047485f0039Sdrh       if( pItem->zAlias ){
4048485f0039Sdrh         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
4049485f0039Sdrh       }
4050485f0039Sdrh       if( i<p->pSrc->nSrc-1 ){
4051485f0039Sdrh         sqlite3DebugPrintf(",");
4052485f0039Sdrh       }
4053485f0039Sdrh       sqlite3DebugPrintf("\n");
4054485f0039Sdrh     }
4055485f0039Sdrh   }
4056485f0039Sdrh   if( p->pWhere ){
4057485f0039Sdrh     sqlite3DebugPrintf("%*s WHERE ", indent, "");
4058485f0039Sdrh     sqlite3PrintExpr(p->pWhere);
4059485f0039Sdrh     sqlite3DebugPrintf("\n");
4060485f0039Sdrh   }
4061485f0039Sdrh   if( p->pGroupBy ){
4062485f0039Sdrh     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
4063485f0039Sdrh     sqlite3PrintExprList(p->pGroupBy);
4064485f0039Sdrh     sqlite3DebugPrintf("\n");
4065485f0039Sdrh   }
4066485f0039Sdrh   if( p->pHaving ){
4067485f0039Sdrh     sqlite3DebugPrintf("%*s HAVING ", indent, "");
4068485f0039Sdrh     sqlite3PrintExpr(p->pHaving);
4069485f0039Sdrh     sqlite3DebugPrintf("\n");
4070485f0039Sdrh   }
4071485f0039Sdrh   if( p->pOrderBy ){
4072485f0039Sdrh     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
4073485f0039Sdrh     sqlite3PrintExprList(p->pOrderBy);
4074485f0039Sdrh     sqlite3DebugPrintf("\n");
4075485f0039Sdrh   }
4076485f0039Sdrh }
4077485f0039Sdrh /* End of the structure debug printing code
4078485f0039Sdrh *****************************************************************************/
4079485f0039Sdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
4080