xref: /sqlite-3.40.0/src/select.c (revision a686bfcf)
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*a686bfcfSdanielk1977 ** $Id: select.c,v 1.423 2008/03/31 17:41:18 danielk1977 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 */
24f0113000Sdanielk1977 static void clearSelect(Select *p){
25eda639e1Sdrh   sqlite3ExprListDelete(p->pEList);
26eda639e1Sdrh   sqlite3SrcListDelete(p->pSrc);
27eda639e1Sdrh   sqlite3ExprDelete(p->pWhere);
28eda639e1Sdrh   sqlite3ExprListDelete(p->pGroupBy);
29eda639e1Sdrh   sqlite3ExprDelete(p->pHaving);
30eda639e1Sdrh   sqlite3ExprListDelete(p->pOrderBy);
31eda639e1Sdrh   sqlite3SelectDelete(p->pPrior);
32eda639e1Sdrh   sqlite3ExprDelete(p->pLimit);
33eda639e1Sdrh   sqlite3ExprDelete(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;
829bb61fe7Sdrh   pNew->isDistinct = isDistinct;
8382c3d636Sdrh   pNew->op = TK_SELECT;
848103b7d2Sdrh   assert( pOffset==0 || pLimit!=0 );
85a2dc3b1aSdanielk1977   pNew->pLimit = pLimit;
86a2dc3b1aSdanielk1977   pNew->pOffset = pOffset;
877b58daeaSdrh   pNew->iLimit = -1;
887b58daeaSdrh   pNew->iOffset = -1;
89b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
90b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
91b9bb7c18Sdrh   pNew->addrOpenEphm[2] = -1;
92eda639e1Sdrh   if( pNew==&standin) {
93eda639e1Sdrh     clearSelect(pNew);
94eda639e1Sdrh     pNew = 0;
95daffd0e5Sdrh   }
969bb61fe7Sdrh   return pNew;
979bb61fe7Sdrh }
989bb61fe7Sdrh 
999bb61fe7Sdrh /*
100eda639e1Sdrh ** Delete the given Select structure and all of its substructures.
101eda639e1Sdrh */
102eda639e1Sdrh void sqlite3SelectDelete(Select *p){
103eda639e1Sdrh   if( p ){
104eda639e1Sdrh     clearSelect(p);
10517435752Sdrh     sqlite3_free(p);
106eda639e1Sdrh   }
107eda639e1Sdrh }
108eda639e1Sdrh 
109eda639e1Sdrh /*
11001f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
11101f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
11201f3f253Sdrh ** in terms of the following bit values:
11301f3f253Sdrh **
11401f3f253Sdrh **     JT_INNER
1153dec223cSdrh **     JT_CROSS
11601f3f253Sdrh **     JT_OUTER
11701f3f253Sdrh **     JT_NATURAL
11801f3f253Sdrh **     JT_LEFT
11901f3f253Sdrh **     JT_RIGHT
12001f3f253Sdrh **
12101f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
12201f3f253Sdrh **
12301f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
12401f3f253Sdrh ** a join type, but put an error in the pParse structure.
12501f3f253Sdrh */
1264adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
12701f3f253Sdrh   int jointype = 0;
12801f3f253Sdrh   Token *apAll[3];
12901f3f253Sdrh   Token *p;
1305719628aSdrh   static const struct {
131c182d163Sdrh     const char zKeyword[8];
132290c1948Sdrh     u8 nChar;
133290c1948Sdrh     u8 code;
13401f3f253Sdrh   } keywords[] = {
13501f3f253Sdrh     { "natural", 7, JT_NATURAL },
136195e6967Sdrh     { "left",    4, JT_LEFT|JT_OUTER },
137195e6967Sdrh     { "right",   5, JT_RIGHT|JT_OUTER },
138195e6967Sdrh     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
13901f3f253Sdrh     { "outer",   5, JT_OUTER },
14001f3f253Sdrh     { "inner",   5, JT_INNER },
1413dec223cSdrh     { "cross",   5, JT_INNER|JT_CROSS },
14201f3f253Sdrh   };
14301f3f253Sdrh   int i, j;
14401f3f253Sdrh   apAll[0] = pA;
14501f3f253Sdrh   apAll[1] = pB;
14601f3f253Sdrh   apAll[2] = pC;
147195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
14801f3f253Sdrh     p = apAll[i];
14901f3f253Sdrh     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
15001f3f253Sdrh       if( p->n==keywords[j].nChar
1512646da7eSdrh           && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
15201f3f253Sdrh         jointype |= keywords[j].code;
15301f3f253Sdrh         break;
15401f3f253Sdrh       }
15501f3f253Sdrh     }
15601f3f253Sdrh     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
15701f3f253Sdrh       jointype |= JT_ERROR;
15801f3f253Sdrh       break;
15901f3f253Sdrh     }
16001f3f253Sdrh   }
161ad2d8307Sdrh   if(
162ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
163195e6967Sdrh      (jointype & JT_ERROR)!=0
164ad2d8307Sdrh   ){
165ae29ffbeSdrh     const char *zSp1 = " ";
166ae29ffbeSdrh     const char *zSp2 = " ";
167ae29ffbeSdrh     if( pB==0 ){ zSp1++; }
168ae29ffbeSdrh     if( pC==0 ){ zSp2++; }
169ae29ffbeSdrh     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
170ae29ffbeSdrh        "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
17101f3f253Sdrh     jointype = JT_INNER;
172195e6967Sdrh   }else if( jointype & JT_RIGHT ){
1734adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
174da93d238Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported");
175195e6967Sdrh     jointype = JT_INNER;
17601f3f253Sdrh   }
17701f3f253Sdrh   return jointype;
17801f3f253Sdrh }
17901f3f253Sdrh 
18001f3f253Sdrh /*
181ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
182ad2d8307Sdrh ** is not contained in the table.
183ad2d8307Sdrh */
184ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
185ad2d8307Sdrh   int i;
186ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
1874adee20fSdanielk1977     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
188ad2d8307Sdrh   }
189ad2d8307Sdrh   return -1;
190ad2d8307Sdrh }
191ad2d8307Sdrh 
192ad2d8307Sdrh /*
19391bb0eedSdrh ** Set the value of a token to a '\000'-terminated string.
19491bb0eedSdrh */
19591bb0eedSdrh static void setToken(Token *p, const char *z){
1962646da7eSdrh   p->z = (u8*)z;
197261919ccSdanielk1977   p->n = z ? strlen(z) : 0;
19891bb0eedSdrh   p->dyn = 0;
19991bb0eedSdrh }
20091bb0eedSdrh 
201c182d163Sdrh /*
202f3b863edSdanielk1977 ** Set the token to the double-quoted and escaped version of the string pointed
203f3b863edSdanielk1977 ** to by z. For example;
204f3b863edSdanielk1977 **
205f3b863edSdanielk1977 **    {a"bc}  ->  {"a""bc"}
206f3b863edSdanielk1977 */
2071e536953Sdanielk1977 static void setQuotedToken(Parse *pParse, Token *p, const char *z){
208*a686bfcfSdanielk1977 
209*a686bfcfSdanielk1977   /* Check if the string contains any " characters. If it does, then
210*a686bfcfSdanielk1977   ** this function will malloc space to create a quoted version of
211*a686bfcfSdanielk1977   ** the string in. Otherwise, save a call to sqlite3MPrintf() by
212*a686bfcfSdanielk1977   ** just copying the pointer to the string.
213*a686bfcfSdanielk1977   */
214*a686bfcfSdanielk1977   const char *z2 = z;
215*a686bfcfSdanielk1977   while( *z2 ){
216*a686bfcfSdanielk1977     if( *z2=='"' ) break;
217*a686bfcfSdanielk1977     z2++;
218*a686bfcfSdanielk1977   }
219*a686bfcfSdanielk1977 
220*a686bfcfSdanielk1977   if( *z2 ){
221*a686bfcfSdanielk1977     /* String contains " characters - copy and quote the string. */
222*a686bfcfSdanielk1977     p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z);
223f3b863edSdanielk1977     if( p->z ){
224f3b863edSdanielk1977       p->n = strlen((char *)p->z);
225*a686bfcfSdanielk1977       p->dyn = 1;
226*a686bfcfSdanielk1977     }
2271e536953Sdanielk1977   }else{
228*a686bfcfSdanielk1977     /* String contains no " characters - copy the pointer. */
229*a686bfcfSdanielk1977     p->z = (u8*)z;
230*a686bfcfSdanielk1977     p->n = (z2 - z);
231*a686bfcfSdanielk1977     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 
24591bb0eedSdrh /*
246ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the
247ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2.
248ad2d8307Sdrh */
249ad2d8307Sdrh static void addWhereTerm(
25017435752Sdrh   Parse *pParse,           /* Parsing context */
251ad2d8307Sdrh   const char *zCol,        /* Name of the column */
252ad2d8307Sdrh   const Table *pTab1,      /* First table */
253030530deSdrh   const char *zAlias1,     /* Alias for first table.  May be NULL */
254ad2d8307Sdrh   const Table *pTab2,      /* Second table */
255030530deSdrh   const char *zAlias2,     /* Alias for second table.  May be NULL */
25622d6a53aSdrh   int iRightJoinTable,     /* VDBE cursor for the right table */
257ad27e761Sdrh   Expr **ppExpr,           /* Add the equality term to this expression */
258ad27e761Sdrh   int isOuterJoin          /* True if dealing with an OUTER join */
259ad2d8307Sdrh ){
260ad2d8307Sdrh   Expr *pE1a, *pE1b, *pE1c;
261ad2d8307Sdrh   Expr *pE2a, *pE2b, *pE2c;
262ad2d8307Sdrh   Expr *pE;
263ad2d8307Sdrh 
26417435752Sdrh   pE1a = sqlite3CreateIdExpr(pParse, zCol);
26517435752Sdrh   pE2a = sqlite3CreateIdExpr(pParse, zCol);
266030530deSdrh   if( zAlias1==0 ){
267030530deSdrh     zAlias1 = pTab1->zName;
268030530deSdrh   }
26917435752Sdrh   pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
270030530deSdrh   if( zAlias2==0 ){
271030530deSdrh     zAlias2 = pTab2->zName;
272030530deSdrh   }
27317435752Sdrh   pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
27417435752Sdrh   pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
27517435752Sdrh   pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
2761e536953Sdanielk1977   pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
277ad27e761Sdrh   if( pE && isOuterJoin ){
2781f16230bSdrh     ExprSetProperty(pE, EP_FromJoin);
27922d6a53aSdrh     pE->iRightJoinTable = iRightJoinTable;
280206f3d96Sdrh   }
281f4ce8ed0Sdrh   *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
282ad2d8307Sdrh }
283ad2d8307Sdrh 
284ad2d8307Sdrh /*
2851f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
28622d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the
28722d6a53aSdrh ** expression.
2881cc093c2Sdrh **
289e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
2901cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
2911f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
2921f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
2931f16230bSdrh ** WHERE clause during join processing but we need to remember that they
2941f16230bSdrh ** originated in the ON or USING clause.
29522d6a53aSdrh **
29622d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the
29722d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not
29822d6a53aSdrh ** explicitly mentioned in the expression.  That information is needed
29922d6a53aSdrh ** for cases like this:
30022d6a53aSdrh **
30122d6a53aSdrh **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
30222d6a53aSdrh **
30322d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5
30422d6a53aSdrh ** term until after the t2 loop of the join.  In that way, a
30522d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
30622d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately
30722d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in
30822d6a53aSdrh ** the output, which is incorrect.
3091cc093c2Sdrh */
31022d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){
3111cc093c2Sdrh   while( p ){
3121f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
31322d6a53aSdrh     p->iRightJoinTable = iTable;
31422d6a53aSdrh     setJoinExpr(p->pLeft, iTable);
3151cc093c2Sdrh     p = p->pRight;
3161cc093c2Sdrh   }
3171cc093c2Sdrh }
3181cc093c2Sdrh 
3191cc093c2Sdrh /*
320ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
321ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
322ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
323ad2d8307Sdrh **
32491bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure.
32591bb0eedSdrh ** The left most table is the first entry in Select.pSrc.  The right-most
32691bb0eedSdrh ** table is the last entry.  The join operator is held in the entry to
32791bb0eedSdrh ** the left.  Thus entry 0 contains the join operator for the join between
32891bb0eedSdrh ** entries 0 and 1.  Any ON or USING clauses associated with the join are
32991bb0eedSdrh ** also attached to the left entry.
33091bb0eedSdrh **
331ad2d8307Sdrh ** This routine returns the number of errors encountered.
332ad2d8307Sdrh */
333ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
33491bb0eedSdrh   SrcList *pSrc;                  /* All tables in the FROM clause */
33591bb0eedSdrh   int i, j;                       /* Loop counters */
33691bb0eedSdrh   struct SrcList_item *pLeft;     /* Left table being joined */
33791bb0eedSdrh   struct SrcList_item *pRight;    /* Right table being joined */
338ad2d8307Sdrh 
33991bb0eedSdrh   pSrc = p->pSrc;
34091bb0eedSdrh   pLeft = &pSrc->a[0];
34191bb0eedSdrh   pRight = &pLeft[1];
34291bb0eedSdrh   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
34391bb0eedSdrh     Table *pLeftTab = pLeft->pTab;
34491bb0eedSdrh     Table *pRightTab = pRight->pTab;
345ad27e761Sdrh     int isOuter;
34691bb0eedSdrh 
34791bb0eedSdrh     if( pLeftTab==0 || pRightTab==0 ) continue;
348ad27e761Sdrh     isOuter = (pRight->jointype & JT_OUTER)!=0;
349ad2d8307Sdrh 
350ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
351ad2d8307Sdrh     ** every column that the two tables have in common.
352ad2d8307Sdrh     */
35361dfc31dSdrh     if( pRight->jointype & JT_NATURAL ){
35461dfc31dSdrh       if( pRight->pOn || pRight->pUsing ){
3554adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
356ad2d8307Sdrh            "an ON or USING clause", 0);
357ad2d8307Sdrh         return 1;
358ad2d8307Sdrh       }
35991bb0eedSdrh       for(j=0; j<pLeftTab->nCol; j++){
36091bb0eedSdrh         char *zName = pLeftTab->aCol[j].zName;
36191bb0eedSdrh         if( columnIndex(pRightTab, zName)>=0 ){
3621e536953Sdanielk1977           addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
36322d6a53aSdrh                               pRightTab, pRight->zAlias,
364ad27e761Sdrh                               pRight->iCursor, &p->pWhere, isOuter);
36522d6a53aSdrh 
366ad2d8307Sdrh         }
367ad2d8307Sdrh       }
368ad2d8307Sdrh     }
369ad2d8307Sdrh 
370ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
371ad2d8307Sdrh     */
37261dfc31dSdrh     if( pRight->pOn && pRight->pUsing ){
3734adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
374da93d238Sdrh         "clauses in the same join");
375ad2d8307Sdrh       return 1;
376ad2d8307Sdrh     }
377ad2d8307Sdrh 
378ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
37991bb0eedSdrh     ** an AND operator.
380ad2d8307Sdrh     */
38161dfc31dSdrh     if( pRight->pOn ){
382ad27e761Sdrh       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
38317435752Sdrh       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
38461dfc31dSdrh       pRight->pOn = 0;
385ad2d8307Sdrh     }
386ad2d8307Sdrh 
387ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
388ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
389ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
390ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
391ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
392ad2d8307Sdrh     ** not contained in both tables to be joined.
393ad2d8307Sdrh     */
39461dfc31dSdrh     if( pRight->pUsing ){
39561dfc31dSdrh       IdList *pList = pRight->pUsing;
396ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
39791bb0eedSdrh         char *zName = pList->a[j].zName;
39891bb0eedSdrh         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
3994adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
40091bb0eedSdrh             "not present in both tables", zName);
401ad2d8307Sdrh           return 1;
402ad2d8307Sdrh         }
4031e536953Sdanielk1977         addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
40422d6a53aSdrh                             pRightTab, pRight->zAlias,
405ad27e761Sdrh                             pRight->iCursor, &p->pWhere, isOuter);
406ad2d8307Sdrh       }
407ad2d8307Sdrh     }
408ad2d8307Sdrh   }
409ad2d8307Sdrh   return 0;
410ad2d8307Sdrh }
411ad2d8307Sdrh 
412ad2d8307Sdrh /*
413c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
414c926afbcSdrh ** stack into the sorter.
415c926afbcSdrh */
416d59ba6ceSdrh static void pushOntoSorter(
417d59ba6ceSdrh   Parse *pParse,         /* Parser context */
418d59ba6ceSdrh   ExprList *pOrderBy,    /* The ORDER BY clause */
419b7654111Sdrh   Select *pSelect,       /* The whole SELECT statement */
420b7654111Sdrh   int regData            /* Register holding data to be sorted */
421d59ba6ceSdrh ){
422d59ba6ceSdrh   Vdbe *v = pParse->pVdbe;
423892d3179Sdrh   int nExpr = pOrderBy->nExpr;
424892d3179Sdrh   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
425892d3179Sdrh   int regRecord = sqlite3GetTempReg(pParse);
426892d3179Sdrh   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase);
427892d3179Sdrh   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
428b7654111Sdrh   sqlite3VdbeAddOp2(v, OP_Move, regData, regBase+nExpr+1);
4291db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
430892d3179Sdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
431892d3179Sdrh   sqlite3ReleaseTempReg(pParse, regRecord);
432892d3179Sdrh   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
433d59ba6ceSdrh   if( pSelect->iLimit>=0 ){
43415007a99Sdrh     int addr1, addr2;
435b7654111Sdrh     int iLimit;
436b7654111Sdrh     if( pSelect->pOffset ){
437b7654111Sdrh       iLimit = pSelect->iOffset+1;
438b7654111Sdrh     }else{
439b7654111Sdrh       iLimit = pSelect->iLimit;
440b7654111Sdrh     }
441b7654111Sdrh     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
442b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
4433c84ddffSdrh     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
444d59ba6ceSdrh     sqlite3VdbeJumpHere(v, addr1);
4453c84ddffSdrh     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
4463c84ddffSdrh     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
44715007a99Sdrh     sqlite3VdbeJumpHere(v, addr2);
448d59ba6ceSdrh     pSelect->iLimit = -1;
449d59ba6ceSdrh   }
450c926afbcSdrh }
451c926afbcSdrh 
452c926afbcSdrh /*
453ec7429aeSdrh ** Add code to implement the OFFSET
454ea48eb2eSdrh */
455ec7429aeSdrh static void codeOffset(
456bab39e13Sdrh   Vdbe *v,          /* Generate code into this VM */
457ea48eb2eSdrh   Select *p,        /* The SELECT statement being coded */
458b7654111Sdrh   int iContinue     /* Jump here to skip the current record */
459ea48eb2eSdrh ){
46013449892Sdrh   if( p->iOffset>=0 && iContinue!=0 ){
46115007a99Sdrh     int addr;
4628558cde1Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
4633c84ddffSdrh     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
46466a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
465d4e70ebdSdrh     VdbeComment((v, "skip OFFSET records"));
46615007a99Sdrh     sqlite3VdbeJumpHere(v, addr);
467ea48eb2eSdrh   }
468ea48eb2eSdrh }
469ea48eb2eSdrh 
470ea48eb2eSdrh /*
47198757157Sdrh ** Add code that will check to make sure the N registers starting at iMem
47298757157Sdrh ** form a distinct entry.  iTab is a sorting index that holds previously
473a2a49dc9Sdrh ** seen combinations of the N values.  A new entry is made in iTab
474a2a49dc9Sdrh ** if the current N values are new.
475a2a49dc9Sdrh **
476a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the
477a2a49dc9Sdrh ** stack if the top N elements are not distinct.
478a2a49dc9Sdrh */
479a2a49dc9Sdrh static void codeDistinct(
4802dcef11bSdrh   Parse *pParse,     /* Parsing and code generating context */
481a2a49dc9Sdrh   int iTab,          /* A sorting index used to test for distinctness */
482a2a49dc9Sdrh   int addrRepeat,    /* Jump to here if not distinct */
483477df4b3Sdrh   int N,             /* Number of elements */
484a2a49dc9Sdrh   int iMem           /* First element */
485a2a49dc9Sdrh ){
4862dcef11bSdrh   Vdbe *v;
4872dcef11bSdrh   int r1;
4882dcef11bSdrh 
4892dcef11bSdrh   v = pParse->pVdbe;
4902dcef11bSdrh   r1 = sqlite3GetTempReg(pParse);
4911db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
4922dcef11bSdrh   sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1);
4932dcef11bSdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
4942dcef11bSdrh   sqlite3ReleaseTempReg(pParse, r1);
495a2a49dc9Sdrh }
496a2a49dc9Sdrh 
497a2a49dc9Sdrh /*
498e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression
499e305f43fSdrh ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
500e305f43fSdrh ** column.  We do this in a subroutine because the error occurs in multiple
501e305f43fSdrh ** places.
502e305f43fSdrh */
5036c8c8ce0Sdanielk1977 static int checkForMultiColumnSelectError(
5046c8c8ce0Sdanielk1977   Parse *pParse,       /* Parse context. */
5056c8c8ce0Sdanielk1977   SelectDest *pDest,   /* Destination of SELECT results */
5066c8c8ce0Sdanielk1977   int nExpr            /* Number of result columns returned by SELECT */
5076c8c8ce0Sdanielk1977 ){
5086c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
509e305f43fSdrh   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
510e305f43fSdrh     sqlite3ErrorMsg(pParse, "only a single result allowed for "
511e305f43fSdrh        "a SELECT that is part of an expression");
512e305f43fSdrh     return 1;
513e305f43fSdrh   }else{
514e305f43fSdrh     return 0;
515e305f43fSdrh   }
516e305f43fSdrh }
517c99130fdSdrh 
518c99130fdSdrh /*
5192282792aSdrh ** This routine generates the code for the inside of the inner loop
5202282792aSdrh ** of a SELECT.
52182c3d636Sdrh **
52238640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
52338640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
52438640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
52538640e15Sdrh ** datatypes for each column.
5262282792aSdrh */
527d2b3e23bSdrh static void selectInnerLoop(
5282282792aSdrh   Parse *pParse,          /* The parser context */
529df199a25Sdrh   Select *p,              /* The complete select statement being coded */
5302282792aSdrh   ExprList *pEList,       /* List of values being extracted */
53182c3d636Sdrh   int srcTab,             /* Pull data from this table */
532967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
5332282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
5342282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
5356c8c8ce0Sdanielk1977   SelectDest *pDest,      /* How to dispose of the results */
5362282792aSdrh   int iContinue,          /* Jump here to continue with next row */
53784ac9d02Sdanielk1977   int iBreak,             /* Jump here to break out of the inner loop */
53884ac9d02Sdanielk1977   char *aff               /* affinity string if eDest is SRT_Union */
5392282792aSdrh ){
5402282792aSdrh   Vdbe *v = pParse->pVdbe;
541d847eaadSdrh   int i;
542ea48eb2eSdrh   int hasDistinct;        /* True if the DISTINCT keyword is present */
543d847eaadSdrh   int regResult;              /* Start of memory holding result set */
544d847eaadSdrh   int eDest = pDest->eDest;   /* How to dispose of results */
545d847eaadSdrh   int iParm = pDest->iParm;   /* First argument to disposal method */
546d847eaadSdrh   int nResultCol;             /* Number of result columns */
54738640e15Sdrh 
548d2b3e23bSdrh   if( v==0 ) return;
54938640e15Sdrh   assert( pEList!=0 );
5502282792aSdrh 
551df199a25Sdrh   /* If there was a LIMIT clause on the SELECT statement, then do the check
552df199a25Sdrh   ** to see if this row should be output.
553df199a25Sdrh   */
554eda639e1Sdrh   hasDistinct = distinct>=0 && pEList->nExpr>0;
555ea48eb2eSdrh   if( pOrderBy==0 && !hasDistinct ){
556b7654111Sdrh     codeOffset(v, p, iContinue);
557df199a25Sdrh   }
558df199a25Sdrh 
559967e8b73Sdrh   /* Pull the requested columns.
5602282792aSdrh   */
56138640e15Sdrh   if( nColumn>0 ){
562d847eaadSdrh     nResultCol = nColumn;
563a2a49dc9Sdrh   }else{
564d847eaadSdrh     nResultCol = pEList->nExpr;
565a2a49dc9Sdrh   }
5661ece7325Sdrh   if( pDest->iMem==0 ){
5671ece7325Sdrh     pDest->iMem = sqlite3GetTempRange(pParse, nResultCol);
568ad27e761Sdrh     pDest->nMem = nResultCol;
569ad27e761Sdrh   }else if( pDest->nMem!=nResultCol ){
570995ae279Sdrh     /* This happens when two SELECTs of a compound SELECT have differing
571995ae279Sdrh     ** numbers of result columns.  The error message will be generated by
572995ae279Sdrh     ** a higher-level routine. */
573ad27e761Sdrh     return;
5741013c932Sdrh   }
5751ece7325Sdrh   regResult = pDest->iMem;
576a2a49dc9Sdrh   if( nColumn>0 ){
577967e8b73Sdrh     for(i=0; i<nColumn; i++){
578d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
57982c3d636Sdrh     }
5809ed1dfa8Sdanielk1977   }else if( eDest!=SRT_Exists ){
5819ed1dfa8Sdanielk1977     /* If the destination is an EXISTS(...) expression, the actual
5829ed1dfa8Sdanielk1977     ** values returned by the SELECT are not required.
5839ed1dfa8Sdanielk1977     */
584d847eaadSdrh     for(i=0; i<nResultCol; i++){
585d847eaadSdrh       sqlite3ExprCode(pParse, pEList->a[i].pExpr, regResult+i);
58682c3d636Sdrh     }
587a2a49dc9Sdrh   }
588d847eaadSdrh   nColumn = nResultCol;
5892282792aSdrh 
590daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
591daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
592daffd0e5Sdrh   ** part of the result.
5932282792aSdrh   */
594ea48eb2eSdrh   if( hasDistinct ){
595f8875400Sdrh     assert( pEList!=0 );
596f8875400Sdrh     assert( pEList->nExpr==nColumn );
597d847eaadSdrh     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
598ea48eb2eSdrh     if( pOrderBy==0 ){
599b7654111Sdrh       codeOffset(v, p, iContinue);
600ea48eb2eSdrh     }
6012282792aSdrh   }
60282c3d636Sdrh 
6036c8c8ce0Sdanielk1977   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
604d2b3e23bSdrh     return;
605e305f43fSdrh   }
606e305f43fSdrh 
607c926afbcSdrh   switch( eDest ){
60882c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
60982c3d636Sdrh     ** table iParm.
6102282792aSdrh     */
61113449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
612c926afbcSdrh     case SRT_Union: {
6139cbf3425Sdrh       int r1;
6149cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
615d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
61613449892Sdrh       if( aff ){
61766a5167bSdrh         sqlite3VdbeChangeP4(v, -1, aff, P4_STATIC);
61813449892Sdrh       }
6199cbf3425Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
6209cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
621c926afbcSdrh       break;
622c926afbcSdrh     }
62382c3d636Sdrh 
62482c3d636Sdrh     /* Construct a record from the query result, but instead of
62582c3d636Sdrh     ** saving that record, use it as a key to delete elements from
62682c3d636Sdrh     ** the temporary table iParm.
62782c3d636Sdrh     */
628c926afbcSdrh     case SRT_Except: {
629e14006d0Sdrh       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
630c926afbcSdrh       break;
631c926afbcSdrh     }
6325338a5f7Sdanielk1977 #endif
6335338a5f7Sdanielk1977 
6345338a5f7Sdanielk1977     /* Store the result as data using a unique key.
6355338a5f7Sdanielk1977     */
6365338a5f7Sdanielk1977     case SRT_Table:
637b9bb7c18Sdrh     case SRT_EphemTab: {
638b7654111Sdrh       int r1 = sqlite3GetTempReg(pParse);
639d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
6405338a5f7Sdanielk1977       if( pOrderBy ){
641b7654111Sdrh         pushOntoSorter(pParse, pOrderBy, p, r1);
6425338a5f7Sdanielk1977       }else{
643b7654111Sdrh         int r2 = sqlite3GetTempReg(pParse);
644b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
645b7654111Sdrh         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
646b7654111Sdrh         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
647b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r2);
6485338a5f7Sdanielk1977       }
649b7654111Sdrh       sqlite3ReleaseTempReg(pParse, r1);
6505338a5f7Sdanielk1977       break;
6515338a5f7Sdanielk1977     }
6522282792aSdrh 
65393758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
6542282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
6552282792aSdrh     ** then there should be a single item on the stack.  Write this
6562282792aSdrh     ** item into the set table with bogus data.
6572282792aSdrh     */
658c926afbcSdrh     case SRT_Set: {
65952b36cabSdrh       int addr2;
660e014a838Sdanielk1977 
661967e8b73Sdrh       assert( nColumn==1 );
662d847eaadSdrh       addr2 = sqlite3VdbeAddOp1(v, OP_IsNull, regResult);
6636c8c8ce0Sdanielk1977       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
664c926afbcSdrh       if( pOrderBy ){
665de941c60Sdrh         /* At first glance you would think we could optimize out the
666de941c60Sdrh         ** ORDER BY in this case since the order of entries in the set
667de941c60Sdrh         ** does not matter.  But there might be a LIMIT clause, in which
668de941c60Sdrh         ** case the order does matter */
669d847eaadSdrh         pushOntoSorter(pParse, pOrderBy, p, regResult);
670c926afbcSdrh       }else{
671b7654111Sdrh         int r1 = sqlite3GetTempReg(pParse);
672d847eaadSdrh         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
673b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
674b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r1);
675c926afbcSdrh       }
676d654be80Sdrh       sqlite3VdbeJumpHere(v, addr2);
677c926afbcSdrh       break;
678c926afbcSdrh     }
67982c3d636Sdrh 
680504b6989Sdrh     /* If any row exist in the result set, record that fact and abort.
681ec7429aeSdrh     */
682ec7429aeSdrh     case SRT_Exists: {
6834c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
684ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
685ec7429aeSdrh       break;
686ec7429aeSdrh     }
687ec7429aeSdrh 
6882282792aSdrh     /* If this is a scalar select that is part of an expression, then
6892282792aSdrh     ** store the results in the appropriate memory cell and break out
6902282792aSdrh     ** of the scan loop.
6912282792aSdrh     */
692c926afbcSdrh     case SRT_Mem: {
693967e8b73Sdrh       assert( nColumn==1 );
694c926afbcSdrh       if( pOrderBy ){
695d847eaadSdrh         pushOntoSorter(pParse, pOrderBy, p, regResult);
696c926afbcSdrh       }else{
697d847eaadSdrh         sqlite3VdbeAddOp2(v, OP_Move, regResult, iParm);
698ec7429aeSdrh         /* The LIMIT clause will jump out of the loop for us */
699c926afbcSdrh       }
700c926afbcSdrh       break;
701c926afbcSdrh     }
70293758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
7032282792aSdrh 
704c182d163Sdrh     /* Send the data to the callback function or to a subroutine.  In the
705c182d163Sdrh     ** case of a subroutine, the subroutine itself is responsible for
706c182d163Sdrh     ** popping the data from the stack.
707f46f905aSdrh     */
708c182d163Sdrh     case SRT_Subroutine:
7099d2985c7Sdrh     case SRT_Callback: {
710f46f905aSdrh       if( pOrderBy ){
711b7654111Sdrh         int r1 = sqlite3GetTempReg(pParse);
712d847eaadSdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
713b7654111Sdrh         pushOntoSorter(pParse, pOrderBy, p, r1);
714b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r1);
715c182d163Sdrh       }else if( eDest==SRT_Subroutine ){
71666a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Gosub, 0, iParm);
717c182d163Sdrh       }else{
718d847eaadSdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
719ac82fcf5Sdrh       }
720142e30dfSdrh       break;
721142e30dfSdrh     }
722142e30dfSdrh 
7236a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER)
724d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
725d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
726d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
727d7489c39Sdrh     ** about the actual results of the select.
728d7489c39Sdrh     */
729c926afbcSdrh     default: {
730f46f905aSdrh       assert( eDest==SRT_Discard );
731c926afbcSdrh       break;
732c926afbcSdrh     }
73393758c8dSdanielk1977 #endif
734c926afbcSdrh   }
735ec7429aeSdrh 
736ec7429aeSdrh   /* Jump to the end of the loop if the LIMIT is reached.
737ec7429aeSdrh   */
738ec7429aeSdrh   if( p->iLimit>=0 && pOrderBy==0 ){
7398558cde1Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
7403c84ddffSdrh     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
741ec7429aeSdrh   }
74282c3d636Sdrh }
74382c3d636Sdrh 
74482c3d636Sdrh /*
745dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records
746dece1a84Sdrh ** the collating sequence for each expression in that expression list.
747dece1a84Sdrh **
7480342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
7490342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to
7500342b1f5Sdrh ** implement that clause.  If the ExprList is the result set of a SELECT
7510342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual
7520342b1f5Sdrh ** index to implement a DISTINCT test.
7530342b1f5Sdrh **
754dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
755dece1a84Sdrh ** function is responsible for seeing that this structure is eventually
75666a5167bSdrh ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
75766a5167bSdrh ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
758dece1a84Sdrh */
759dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
760dece1a84Sdrh   sqlite3 *db = pParse->db;
761dece1a84Sdrh   int nExpr;
762dece1a84Sdrh   KeyInfo *pInfo;
763dece1a84Sdrh   struct ExprList_item *pItem;
764dece1a84Sdrh   int i;
765dece1a84Sdrh 
766dece1a84Sdrh   nExpr = pList->nExpr;
76717435752Sdrh   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
768dece1a84Sdrh   if( pInfo ){
7692646da7eSdrh     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
770dece1a84Sdrh     pInfo->nField = nExpr;
77114db2665Sdanielk1977     pInfo->enc = ENC(db);
772dece1a84Sdrh     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
773dece1a84Sdrh       CollSeq *pColl;
774dece1a84Sdrh       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
775dece1a84Sdrh       if( !pColl ){
776dece1a84Sdrh         pColl = db->pDfltColl;
777dece1a84Sdrh       }
778dece1a84Sdrh       pInfo->aColl[i] = pColl;
779dece1a84Sdrh       pInfo->aSortOrder[i] = pItem->sortOrder;
780dece1a84Sdrh     }
781dece1a84Sdrh   }
782dece1a84Sdrh   return pInfo;
783dece1a84Sdrh }
784dece1a84Sdrh 
785dece1a84Sdrh 
786dece1a84Sdrh /*
787d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
788d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
789d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
790d8bc7086Sdrh ** routine generates the code needed to do that.
791d8bc7086Sdrh */
792c926afbcSdrh static void generateSortTail(
793cdd536f0Sdrh   Parse *pParse,    /* Parsing context */
794c926afbcSdrh   Select *p,        /* The SELECT statement */
795c926afbcSdrh   Vdbe *v,          /* Generate code into this VDBE */
796c926afbcSdrh   int nColumn,      /* Number of columns of data */
7976c8c8ce0Sdanielk1977   SelectDest *pDest /* Write the sorted results here */
798c926afbcSdrh ){
7990342b1f5Sdrh   int brk = sqlite3VdbeMakeLabel(v);
8000342b1f5Sdrh   int cont = sqlite3VdbeMakeLabel(v);
801d8bc7086Sdrh   int addr;
8020342b1f5Sdrh   int iTab;
80361fc595fSdrh   int pseudoTab = 0;
8040342b1f5Sdrh   ExprList *pOrderBy = p->pOrderBy;
805ffbc3088Sdrh 
8066c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
8076c8c8ce0Sdanielk1977   int iParm = pDest->iParm;
8086c8c8ce0Sdanielk1977 
8092d401ab8Sdrh   int regRow;
8102d401ab8Sdrh   int regRowid;
8112d401ab8Sdrh 
8129d2985c7Sdrh   iTab = pOrderBy->iECursor;
813cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
814cdd536f0Sdrh     pseudoTab = pParse->nTab++;
815cd3e8f7cSdanielk1977     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nColumn);
8169882d999Sdanielk1977     sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, eDest==SRT_Callback);
817cdd536f0Sdrh   }
81866a5167bSdrh   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, brk);
819b7654111Sdrh   codeOffset(v, p, cont);
8202d401ab8Sdrh   regRow = sqlite3GetTempReg(pParse);
8212d401ab8Sdrh   regRowid = sqlite3GetTempReg(pParse);
8222d401ab8Sdrh   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
823c926afbcSdrh   switch( eDest ){
824c926afbcSdrh     case SRT_Table:
825b9bb7c18Sdrh     case SRT_EphemTab: {
8262d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
8272d401ab8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
8282d401ab8Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
829c926afbcSdrh       break;
830c926afbcSdrh     }
83193758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
832c926afbcSdrh     case SRT_Set: {
8332d401ab8Sdrh       int j1;
834c926afbcSdrh       assert( nColumn==1 );
8352d401ab8Sdrh       j1 = sqlite3VdbeAddOp1(v, OP_IsNull, regRow);
836a7a8e14bSdanielk1977       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
837a7a8e14bSdanielk1977       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
8386a288a33Sdrh       sqlite3VdbeJumpHere(v, j1);
839c926afbcSdrh       break;
840c926afbcSdrh     }
841c926afbcSdrh     case SRT_Mem: {
842c926afbcSdrh       assert( nColumn==1 );
8432d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_Move, regRow, iParm);
844ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
845c926afbcSdrh       break;
846c926afbcSdrh     }
84793758c8dSdanielk1977 #endif
848ce665cf6Sdrh     case SRT_Callback:
849ac82fcf5Sdrh     case SRT_Subroutine: {
850ac82fcf5Sdrh       int i;
8512d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid);
8522d401ab8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid);
853ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
8549882d999Sdanielk1977         assert( regRow!=pDest->iMem+i );
8551013c932Sdrh         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
856ac82fcf5Sdrh       }
857ce665cf6Sdrh       if( eDest==SRT_Callback ){
8581013c932Sdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
859ce665cf6Sdrh       }else{
86066a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Gosub, 0, iParm);
861ce665cf6Sdrh       }
862ac82fcf5Sdrh       break;
863ac82fcf5Sdrh     }
864c926afbcSdrh     default: {
865f46f905aSdrh       /* Do nothing */
866c926afbcSdrh       break;
867c926afbcSdrh     }
868c926afbcSdrh   }
8692d401ab8Sdrh   sqlite3ReleaseTempReg(pParse, regRow);
8702d401ab8Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
871ec7429aeSdrh 
872ec7429aeSdrh   /* Jump to the end of the loop when the LIMIT is reached
873ec7429aeSdrh   */
874ec7429aeSdrh   if( p->iLimit>=0 ){
8758558cde1Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
8763c84ddffSdrh     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, brk);
877ec7429aeSdrh   }
878ec7429aeSdrh 
879ec7429aeSdrh   /* The bottom of the loop
880ec7429aeSdrh   */
8810342b1f5Sdrh   sqlite3VdbeResolveLabel(v, cont);
88266a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
8830342b1f5Sdrh   sqlite3VdbeResolveLabel(v, brk);
884cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
88566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
886cdd536f0Sdrh   }
887cdd536f0Sdrh 
888d8bc7086Sdrh }
889d8bc7086Sdrh 
890d8bc7086Sdrh /*
891517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
892517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
893e78e8284Sdrh **
894955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the
895955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The
896955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
897955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The
898955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is
899955de52cSdanielk1977 ** considered a column by this function.
900e78e8284Sdrh **
901955de52cSdanielk1977 **   SELECT col FROM tbl;
902955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl;
903955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl);
904955de52cSdanielk1977 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
905955de52cSdanielk1977 **
906955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL.
907fcb78a49Sdrh */
908955de52cSdanielk1977 static const char *columnType(
909955de52cSdanielk1977   NameContext *pNC,
910955de52cSdanielk1977   Expr *pExpr,
911955de52cSdanielk1977   const char **pzOriginDb,
912955de52cSdanielk1977   const char **pzOriginTab,
913955de52cSdanielk1977   const char **pzOriginCol
914955de52cSdanielk1977 ){
915955de52cSdanielk1977   char const *zType = 0;
916955de52cSdanielk1977   char const *zOriginDb = 0;
917955de52cSdanielk1977   char const *zOriginTab = 0;
918955de52cSdanielk1977   char const *zOriginCol = 0;
919517eb646Sdanielk1977   int j;
920b3bce662Sdanielk1977   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
9215338a5f7Sdanielk1977 
92200e279d9Sdanielk1977   switch( pExpr->op ){
92330bcf5dbSdrh     case TK_AGG_COLUMN:
92400e279d9Sdanielk1977     case TK_COLUMN: {
925955de52cSdanielk1977       /* The expression is a column. Locate the table the column is being
926955de52cSdanielk1977       ** extracted from in NameContext.pSrcList. This table may be real
927955de52cSdanielk1977       ** database table or a subquery.
928955de52cSdanielk1977       */
929955de52cSdanielk1977       Table *pTab = 0;            /* Table structure column is extracted from */
930955de52cSdanielk1977       Select *pS = 0;             /* Select the column is extracted from */
931955de52cSdanielk1977       int iCol = pExpr->iColumn;  /* Index of column in pTab */
932b3bce662Sdanielk1977       while( pNC && !pTab ){
933b3bce662Sdanielk1977         SrcList *pTabList = pNC->pSrcList;
934b3bce662Sdanielk1977         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
935b3bce662Sdanielk1977         if( j<pTabList->nSrc ){
9366a3ea0e6Sdrh           pTab = pTabList->a[j].pTab;
937955de52cSdanielk1977           pS = pTabList->a[j].pSelect;
938b3bce662Sdanielk1977         }else{
939b3bce662Sdanielk1977           pNC = pNC->pNext;
940b3bce662Sdanielk1977         }
941b3bce662Sdanielk1977       }
942955de52cSdanielk1977 
9437e62779aSdrh       if( pTab==0 ){
9447e62779aSdrh         /* FIX ME:
9457e62779aSdrh         ** This can occurs if you have something like "SELECT new.x;" inside
9467e62779aSdrh         ** a trigger.  In other words, if you reference the special "new"
9477e62779aSdrh         ** table in the result set of a select.  We do not have a good way
9487e62779aSdrh         ** to find the actual table type, so call it "TEXT".  This is really
9497e62779aSdrh         ** something of a bug, but I do not know how to fix it.
9507e62779aSdrh         **
9517e62779aSdrh         ** This code does not produce the correct answer - it just prevents
9527e62779aSdrh         ** a segfault.  See ticket #1229.
9537e62779aSdrh         */
9547e62779aSdrh         zType = "TEXT";
9557e62779aSdrh         break;
9567e62779aSdrh       }
957955de52cSdanielk1977 
958b3bce662Sdanielk1977       assert( pTab );
959955de52cSdanielk1977       if( pS ){
960955de52cSdanielk1977         /* The "table" is actually a sub-select or a view in the FROM clause
961955de52cSdanielk1977         ** of the SELECT statement. Return the declaration type and origin
962955de52cSdanielk1977         ** data for the result-set column of the sub-select.
963955de52cSdanielk1977         */
964955de52cSdanielk1977         if( iCol>=0 && iCol<pS->pEList->nExpr ){
965955de52cSdanielk1977           /* If iCol is less than zero, then the expression requests the
966955de52cSdanielk1977           ** rowid of the sub-select or view. This expression is legal (see
967955de52cSdanielk1977           ** test case misc2.2.2) - it always evaluates to NULL.
968955de52cSdanielk1977           */
969955de52cSdanielk1977           NameContext sNC;
970955de52cSdanielk1977           Expr *p = pS->pEList->a[iCol].pExpr;
971955de52cSdanielk1977           sNC.pSrcList = pS->pSrc;
972955de52cSdanielk1977           sNC.pNext = 0;
973955de52cSdanielk1977           sNC.pParse = pNC->pParse;
974955de52cSdanielk1977           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
975955de52cSdanielk1977         }
9764b2688abSdanielk1977       }else if( pTab->pSchema ){
977955de52cSdanielk1977         /* A real table */
978955de52cSdanielk1977         assert( !pS );
979fcb78a49Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
980fcb78a49Sdrh         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
981fcb78a49Sdrh         if( iCol<0 ){
982fcb78a49Sdrh           zType = "INTEGER";
983955de52cSdanielk1977           zOriginCol = "rowid";
984fcb78a49Sdrh         }else{
985fcb78a49Sdrh           zType = pTab->aCol[iCol].zType;
986955de52cSdanielk1977           zOriginCol = pTab->aCol[iCol].zName;
987955de52cSdanielk1977         }
988955de52cSdanielk1977         zOriginTab = pTab->zName;
989955de52cSdanielk1977         if( pNC->pParse ){
990955de52cSdanielk1977           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
991955de52cSdanielk1977           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
992955de52cSdanielk1977         }
993fcb78a49Sdrh       }
99400e279d9Sdanielk1977       break;
995736c22b8Sdrh     }
99693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
99700e279d9Sdanielk1977     case TK_SELECT: {
998955de52cSdanielk1977       /* The expression is a sub-select. Return the declaration type and
999955de52cSdanielk1977       ** origin info for the single column in the result set of the SELECT
1000955de52cSdanielk1977       ** statement.
1001955de52cSdanielk1977       */
1002b3bce662Sdanielk1977       NameContext sNC;
100300e279d9Sdanielk1977       Select *pS = pExpr->pSelect;
1004955de52cSdanielk1977       Expr *p = pS->pEList->a[0].pExpr;
1005955de52cSdanielk1977       sNC.pSrcList = pS->pSrc;
1006b3bce662Sdanielk1977       sNC.pNext = pNC;
1007955de52cSdanielk1977       sNC.pParse = pNC->pParse;
1008955de52cSdanielk1977       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
100900e279d9Sdanielk1977       break;
1010fcb78a49Sdrh     }
101193758c8dSdanielk1977 #endif
101200e279d9Sdanielk1977   }
101300e279d9Sdanielk1977 
1014955de52cSdanielk1977   if( pzOriginDb ){
1015955de52cSdanielk1977     assert( pzOriginTab && pzOriginCol );
1016955de52cSdanielk1977     *pzOriginDb = zOriginDb;
1017955de52cSdanielk1977     *pzOriginTab = zOriginTab;
1018955de52cSdanielk1977     *pzOriginCol = zOriginCol;
1019955de52cSdanielk1977   }
1020517eb646Sdanielk1977   return zType;
1021517eb646Sdanielk1977 }
1022517eb646Sdanielk1977 
1023517eb646Sdanielk1977 /*
1024517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
1025517eb646Sdanielk1977 ** in the result set.
1026517eb646Sdanielk1977 */
1027517eb646Sdanielk1977 static void generateColumnTypes(
1028517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
1029517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
1030517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
1031517eb646Sdanielk1977 ){
10323f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE
1033517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
1034517eb646Sdanielk1977   int i;
1035b3bce662Sdanielk1977   NameContext sNC;
1036b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
1037955de52cSdanielk1977   sNC.pParse = pParse;
1038517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
1039517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
10403f913576Sdrh     const char *zType;
10413f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1042955de52cSdanielk1977     const char *zOrigDb = 0;
1043955de52cSdanielk1977     const char *zOrigTab = 0;
1044955de52cSdanielk1977     const char *zOrigCol = 0;
10453f913576Sdrh     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
1046955de52cSdanielk1977 
104785b623f2Sdrh     /* The vdbe must make its own copy of the column-type and other
10484b1ae99dSdanielk1977     ** column specific strings, in case the schema is reset before this
10494b1ae99dSdanielk1977     ** virtual machine is deleted.
1050fbcd585fSdanielk1977     */
105166a5167bSdrh     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P4_TRANSIENT);
105266a5167bSdrh     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P4_TRANSIENT);
105366a5167bSdrh     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P4_TRANSIENT);
10543f913576Sdrh #else
10553f913576Sdrh     zType = columnType(&sNC, p, 0, 0, 0);
10563f913576Sdrh #endif
10573f913576Sdrh     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P4_TRANSIENT);
1058fcb78a49Sdrh   }
10593f913576Sdrh #endif /* SQLITE_OMIT_DECLTYPE */
1060fcb78a49Sdrh }
1061fcb78a49Sdrh 
1062fcb78a49Sdrh /*
1063fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
1064fcb78a49Sdrh ** in the result set.  This information is used to provide the
1065fcabd464Sdrh ** azCol[] values in the callback.
106682c3d636Sdrh */
1067832508b7Sdrh static void generateColumnNames(
1068832508b7Sdrh   Parse *pParse,      /* Parser context */
1069ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
1070832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
1071832508b7Sdrh ){
1072d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
10736a3ea0e6Sdrh   int i, j;
10749bb575fdSdrh   sqlite3 *db = pParse->db;
1075fcabd464Sdrh   int fullNames, shortNames;
1076fcabd464Sdrh 
1077fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN
10783cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
10793cf86063Sdanielk1977   if( pParse->explain ){
108061de0d1bSdanielk1977     return;
10813cf86063Sdanielk1977   }
10825338a5f7Sdanielk1977 #endif
10833cf86063Sdanielk1977 
1084d6502758Sdrh   assert( v!=0 );
108517435752Sdrh   if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
1086d8bc7086Sdrh   pParse->colNamesSet = 1;
1087fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
1088fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
108922322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
109082c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
109182c3d636Sdrh     Expr *p;
10925a38705eSdrh     p = pEList->a[i].pExpr;
10935a38705eSdrh     if( p==0 ) continue;
109482c3d636Sdrh     if( pEList->a[i].zName ){
109582c3d636Sdrh       char *zName = pEList->a[i].zName;
1096955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
109782c3d636Sdrh       continue;
109882c3d636Sdrh     }
1099fa173a76Sdrh     if( p->op==TK_COLUMN && pTabList ){
11006a3ea0e6Sdrh       Table *pTab;
110197665873Sdrh       char *zCol;
11028aff1015Sdrh       int iCol = p->iColumn;
11036a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
11046a3ea0e6Sdrh       assert( j<pTabList->nSrc );
11056a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
11068aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
110797665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1108b1363206Sdrh       if( iCol<0 ){
110947a6db2bSdrh         zCol = "rowid";
1110b1363206Sdrh       }else{
1111b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
1112b1363206Sdrh       }
1113fcabd464Sdrh       if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
1114955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
1115fcabd464Sdrh       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
111682c3d636Sdrh         char *zName = 0;
111782c3d636Sdrh         char *zTab;
111882c3d636Sdrh 
11196a3ea0e6Sdrh         zTab = pTabList->a[j].zAlias;
1120fcabd464Sdrh         if( fullNames || zTab==0 ) zTab = pTab->zName;
1121f93339deSdrh         sqlite3SetString(&zName, zTab, ".", zCol, (char*)0);
112266a5167bSdrh         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P4_DYNAMIC);
112382c3d636Sdrh       }else{
1124955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
112582c3d636Sdrh       }
11266977fea8Sdrh     }else if( p->span.z && p->span.z[0] ){
1127955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
11283cf86063Sdanielk1977       /* sqlite3VdbeCompressSpace(v, addr); */
11291bee3d7bSdrh     }else{
11301bee3d7bSdrh       char zName[30];
11311bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
11325bb3eb9bSdrh       sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1);
1133955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0);
113482c3d636Sdrh     }
113582c3d636Sdrh   }
113676d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
11375080aaa7Sdrh }
113882c3d636Sdrh 
113993758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
114082c3d636Sdrh /*
1141d8bc7086Sdrh ** Name of the connection operator, used for error messages.
1142d8bc7086Sdrh */
1143d8bc7086Sdrh static const char *selectOpName(int id){
1144d8bc7086Sdrh   char *z;
1145d8bc7086Sdrh   switch( id ){
1146d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
1147d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
1148d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
1149d8bc7086Sdrh     default:           z = "UNION";       break;
1150d8bc7086Sdrh   }
1151d8bc7086Sdrh   return z;
1152d8bc7086Sdrh }
115393758c8dSdanielk1977 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1154d8bc7086Sdrh 
1155d8bc7086Sdrh /*
1156315555caSdrh ** Forward declaration
1157315555caSdrh */
11589b3187e1Sdrh static int prepSelectStmt(Parse*, Select*);
1159315555caSdrh 
1160315555caSdrh /*
116122f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
116222f70c32Sdrh ** the result set of that SELECT.
116322f70c32Sdrh */
11644adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
116522f70c32Sdrh   Table *pTab;
1166b733d037Sdrh   int i, j;
116722f70c32Sdrh   ExprList *pEList;
1168290c1948Sdrh   Column *aCol, *pCol;
116917435752Sdrh   sqlite3 *db = pParse->db;
117022f70c32Sdrh 
117192378253Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
11729b3187e1Sdrh   if( prepSelectStmt(pParse, pSelect) ){
117322f70c32Sdrh     return 0;
117422f70c32Sdrh   }
1175142bdf40Sdanielk1977   if( sqlite3SelectResolve(pParse, pSelect, 0) ){
1176142bdf40Sdanielk1977     return 0;
1177142bdf40Sdanielk1977   }
117817435752Sdrh   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
117922f70c32Sdrh   if( pTab==0 ){
118022f70c32Sdrh     return 0;
118122f70c32Sdrh   }
1182ed8a3bb1Sdrh   pTab->nRef = 1;
118317435752Sdrh   pTab->zName = zTabName ? sqlite3DbStrDup(db, zTabName) : 0;
118422f70c32Sdrh   pEList = pSelect->pEList;
118522f70c32Sdrh   pTab->nCol = pEList->nExpr;
1186417be79cSdrh   assert( pTab->nCol>0 );
118717435752Sdrh   pTab->aCol = aCol = sqlite3DbMallocZero(db, sizeof(pTab->aCol[0])*pTab->nCol);
1188290c1948Sdrh   for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
118979d5f63fSdrh     Expr *p, *pR;
1190517eb646Sdanielk1977     char *zType;
119191bb0eedSdrh     char *zName;
11922564ef97Sdrh     int nName;
1193b3bf556eSdanielk1977     CollSeq *pColl;
119479d5f63fSdrh     int cnt;
1195b3bce662Sdanielk1977     NameContext sNC;
119679d5f63fSdrh 
119779d5f63fSdrh     /* Get an appropriate name for the column
119879d5f63fSdrh     */
119979d5f63fSdrh     p = pEList->a[i].pExpr;
1200290c1948Sdrh     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
120191bb0eedSdrh     if( (zName = pEList->a[i].zName)!=0 ){
120279d5f63fSdrh       /* If the column contains an "AS <name>" phrase, use <name> as the name */
120317435752Sdrh       zName = sqlite3DbStrDup(db, zName);
1204517eb646Sdanielk1977     }else if( p->op==TK_DOT
1205b733d037Sdrh               && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
120679d5f63fSdrh       /* For columns of the from A.B use B as the name */
120717435752Sdrh       zName = sqlite3MPrintf(db, "%T", &pR->token);
1208b733d037Sdrh     }else if( p->span.z && p->span.z[0] ){
120979d5f63fSdrh       /* Use the original text of the column expression as its name */
121017435752Sdrh       zName = sqlite3MPrintf(db, "%T", &p->span);
121122f70c32Sdrh     }else{
121279d5f63fSdrh       /* If all else fails, make up a name */
121317435752Sdrh       zName = sqlite3MPrintf(db, "column%d", i+1);
121422f70c32Sdrh     }
12157751940dSdanielk1977     if( !zName || db->mallocFailed ){
12167751940dSdanielk1977       db->mallocFailed = 1;
121717435752Sdrh       sqlite3_free(zName);
1218a04a34ffSdanielk1977       sqlite3DeleteTable(pTab);
1219dd5b2fa5Sdrh       return 0;
1220dd5b2fa5Sdrh     }
12217751940dSdanielk1977     sqlite3Dequote(zName);
122279d5f63fSdrh 
122379d5f63fSdrh     /* Make sure the column name is unique.  If the name is not unique,
122479d5f63fSdrh     ** append a integer to the name so that it becomes unique.
122579d5f63fSdrh     */
12262564ef97Sdrh     nName = strlen(zName);
122779d5f63fSdrh     for(j=cnt=0; j<i; j++){
122879d5f63fSdrh       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
12292564ef97Sdrh         zName[nName] = 0;
12301e536953Sdanielk1977         zName = sqlite3MPrintf(db, "%z:%d", zName, ++cnt);
123179d5f63fSdrh         j = -1;
1232dd5b2fa5Sdrh         if( zName==0 ) break;
123379d5f63fSdrh       }
123479d5f63fSdrh     }
123591bb0eedSdrh     pCol->zName = zName;
1236e014a838Sdanielk1977 
123779d5f63fSdrh     /* Get the typename, type affinity, and collating sequence for the
123879d5f63fSdrh     ** column.
123979d5f63fSdrh     */
1240c43e8be8Sdrh     memset(&sNC, 0, sizeof(sNC));
1241b3bce662Sdanielk1977     sNC.pSrcList = pSelect->pSrc;
124217435752Sdrh     zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
1243290c1948Sdrh     pCol->zType = zType;
1244c60e9b82Sdanielk1977     pCol->affinity = sqlite3ExprAffinity(p);
1245b3bf556eSdanielk1977     pColl = sqlite3ExprCollSeq(pParse, p);
1246b3bf556eSdanielk1977     if( pColl ){
124717435752Sdrh       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
12480202b29eSdanielk1977     }
124922f70c32Sdrh   }
125022f70c32Sdrh   pTab->iPKey = -1;
125122f70c32Sdrh   return pTab;
125222f70c32Sdrh }
125322f70c32Sdrh 
125422f70c32Sdrh /*
12559b3187e1Sdrh ** Prepare a SELECT statement for processing by doing the following
12569b3187e1Sdrh ** things:
1257d8bc7086Sdrh **
12589b3187e1Sdrh **    (1)  Make sure VDBE cursor numbers have been assigned to every
12599b3187e1Sdrh **         element of the FROM clause.
12609b3187e1Sdrh **
12619b3187e1Sdrh **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
12629b3187e1Sdrh **         defines FROM clause.  When views appear in the FROM clause,
126363eb5f29Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
126463eb5f29Sdrh **         that implements the view.  A copy is made of the view's SELECT
126563eb5f29Sdrh **         statement so that we can freely modify or delete that statement
126663eb5f29Sdrh **         without worrying about messing up the presistent representation
126763eb5f29Sdrh **         of the view.
1268d8bc7086Sdrh **
12699b3187e1Sdrh **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
1270ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
1271ad2d8307Sdrh **
12729b3187e1Sdrh **    (4)  Scan the list of columns in the result set (pEList) looking
127354473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
127454473229Sdrh **         If found, expand each "*" to be every column in every table
127554473229Sdrh **         and TABLE.* to be every column in TABLE.
1276d8bc7086Sdrh **
1277d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
1278d8bc7086Sdrh ** in pParse and return non-zero.
1279d8bc7086Sdrh */
12809b3187e1Sdrh static int prepSelectStmt(Parse *pParse, Select *p){
128154473229Sdrh   int i, j, k, rc;
1282ad3cab52Sdrh   SrcList *pTabList;
1283daffd0e5Sdrh   ExprList *pEList;
1284290c1948Sdrh   struct SrcList_item *pFrom;
128517435752Sdrh   sqlite3 *db = pParse->db;
1286daffd0e5Sdrh 
128717435752Sdrh   if( p==0 || p->pSrc==0 || db->mallocFailed ){
12886f7adc8aSdrh     return 1;
12896f7adc8aSdrh   }
1290daffd0e5Sdrh   pTabList = p->pSrc;
1291daffd0e5Sdrh   pEList = p->pEList;
1292d8bc7086Sdrh 
12939b3187e1Sdrh   /* Make sure cursor numbers have been assigned to all entries in
12949b3187e1Sdrh   ** the FROM clause of the SELECT statement.
12959b3187e1Sdrh   */
12969b3187e1Sdrh   sqlite3SrcListAssignCursors(pParse, p->pSrc);
12979b3187e1Sdrh 
12989b3187e1Sdrh   /* Look up every table named in the FROM clause of the select.  If
12999b3187e1Sdrh   ** an entry of the FROM clause is a subquery instead of a table or view,
13009b3187e1Sdrh   ** then create a transient table structure to describe the subquery.
1301d8bc7086Sdrh   */
1302290c1948Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1303f0113000Sdanielk1977     Table *pTab;
13049b3187e1Sdrh     if( pFrom->pTab!=0 ){
13059b3187e1Sdrh       /* This statement has already been prepared.  There is no need
13069b3187e1Sdrh       ** to go further. */
13079b3187e1Sdrh       assert( i==0 );
1308d8bc7086Sdrh       return 0;
1309d8bc7086Sdrh     }
1310290c1948Sdrh     if( pFrom->zName==0 ){
131193758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
131222f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
1313290c1948Sdrh       assert( pFrom->pSelect!=0 );
1314290c1948Sdrh       if( pFrom->zAlias==0 ){
131591bb0eedSdrh         pFrom->zAlias =
13161e536953Sdanielk1977           sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pFrom->pSelect);
1317ad2d8307Sdrh       }
1318ed8a3bb1Sdrh       assert( pFrom->pTab==0 );
1319290c1948Sdrh       pFrom->pTab = pTab =
1320290c1948Sdrh         sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
132122f70c32Sdrh       if( pTab==0 ){
1322daffd0e5Sdrh         return 1;
1323daffd0e5Sdrh       }
1324b9bb7c18Sdrh       /* The isEphem flag indicates that the Table structure has been
13255cf590c1Sdrh       ** dynamically allocated and may be freed at any time.  In other words,
13265cf590c1Sdrh       ** pTab is not pointing to a persistent table structure that defines
13275cf590c1Sdrh       ** part of the schema. */
1328b9bb7c18Sdrh       pTab->isEphem = 1;
132993758c8dSdanielk1977 #endif
133022f70c32Sdrh     }else{
1331a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
1332ed8a3bb1Sdrh       assert( pFrom->pTab==0 );
1333290c1948Sdrh       pFrom->pTab = pTab =
1334ca424114Sdrh         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
1335a76b5dfcSdrh       if( pTab==0 ){
1336d8bc7086Sdrh         return 1;
1337d8bc7086Sdrh       }
1338ed8a3bb1Sdrh       pTab->nRef++;
133993626f48Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
134093626f48Sdanielk1977       if( pTab->pSelect || IsVirtual(pTab) ){
134163eb5f29Sdrh         /* We reach here if the named table is a really a view */
13424adee20fSdanielk1977         if( sqlite3ViewGetColumnNames(pParse, pTab) ){
1343417be79cSdrh           return 1;
1344417be79cSdrh         }
1345290c1948Sdrh         /* If pFrom->pSelect!=0 it means we are dealing with a
134663eb5f29Sdrh         ** view within a view.  The SELECT structure has already been
134763eb5f29Sdrh         ** copied by the outer view so we can skip the copy step here
134863eb5f29Sdrh         ** in the inner view.
134963eb5f29Sdrh         */
1350290c1948Sdrh         if( pFrom->pSelect==0 ){
135117435752Sdrh           pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
1352a76b5dfcSdrh         }
1353d8bc7086Sdrh       }
135493758c8dSdanielk1977 #endif
135522f70c32Sdrh     }
135663eb5f29Sdrh   }
1357d8bc7086Sdrh 
1358ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
1359ad2d8307Sdrh   */
1360ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
1361ad2d8307Sdrh 
13627c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
136354473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
136454473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
13657c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
13667c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
13677c917d19Sdrh   ** each one to the list of all columns in all tables.
136854473229Sdrh   **
136954473229Sdrh   ** The first loop just checks to see if there are any "*" operators
137054473229Sdrh   ** that need expanding.
1371d8bc7086Sdrh   */
13727c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
137354473229Sdrh     Expr *pE = pEList->a[k].pExpr;
137454473229Sdrh     if( pE->op==TK_ALL ) break;
137554473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
137654473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
13777c917d19Sdrh   }
137854473229Sdrh   rc = 0;
13797c917d19Sdrh   if( k<pEList->nExpr ){
138054473229Sdrh     /*
138154473229Sdrh     ** If we get here it means the result set contains one or more "*"
138254473229Sdrh     ** operators that need to be expanded.  Loop through each expression
138354473229Sdrh     ** in the result set and expand them one by one.
138454473229Sdrh     */
13857c917d19Sdrh     struct ExprList_item *a = pEList->a;
13867c917d19Sdrh     ExprList *pNew = 0;
1387d70dc52dSdrh     int flags = pParse->db->flags;
1388d70dc52dSdrh     int longNames = (flags & SQLITE_FullColNames)!=0 &&
1389d70dc52dSdrh                       (flags & SQLITE_ShortColNames)==0;
1390d70dc52dSdrh 
13917c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
139254473229Sdrh       Expr *pE = a[k].pExpr;
139354473229Sdrh       if( pE->op!=TK_ALL &&
139454473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
139554473229Sdrh         /* This particular expression does not need to be expanded.
139654473229Sdrh         */
139717435752Sdrh         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
1398261919ccSdanielk1977         if( pNew ){
13997c917d19Sdrh           pNew->a[pNew->nExpr-1].zName = a[k].zName;
1400261919ccSdanielk1977         }else{
1401261919ccSdanielk1977           rc = 1;
1402261919ccSdanielk1977         }
14037c917d19Sdrh         a[k].pExpr = 0;
14047c917d19Sdrh         a[k].zName = 0;
14057c917d19Sdrh       }else{
140654473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
140754473229Sdrh         ** expanded. */
140854473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
1409cf55b7aeSdrh         char *zTName;            /* text of name of TABLE */
141054473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
141117435752Sdrh           zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
141254473229Sdrh         }else{
1413cf55b7aeSdrh           zTName = 0;
141454473229Sdrh         }
1415290c1948Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1416290c1948Sdrh           Table *pTab = pFrom->pTab;
1417290c1948Sdrh           char *zTabName = pFrom->zAlias;
141854473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
141954473229Sdrh             zTabName = pTab->zName;
142054473229Sdrh           }
1421cf55b7aeSdrh           if( zTName && (zTabName==0 || zTabName[0]==0 ||
1422cf55b7aeSdrh                  sqlite3StrICmp(zTName, zTabName)!=0) ){
142354473229Sdrh             continue;
142454473229Sdrh           }
142554473229Sdrh           tableSeen = 1;
1426d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
1427f0113000Sdanielk1977             Expr *pExpr, *pRight;
1428ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
1429ad2d8307Sdrh 
1430034ca14fSdanielk1977             /* If a column is marked as 'hidden' (currently only possible
1431034ca14fSdanielk1977             ** for virtual tables), do not include it in the expanded
1432034ca14fSdanielk1977             ** result-set list.
1433034ca14fSdanielk1977             */
1434034ca14fSdanielk1977             if( IsHiddenColumn(&pTab->aCol[j]) ){
1435034ca14fSdanielk1977               assert(IsVirtual(pTab));
1436034ca14fSdanielk1977               continue;
1437034ca14fSdanielk1977             }
1438034ca14fSdanielk1977 
143991bb0eedSdrh             if( i>0 ){
144091bb0eedSdrh               struct SrcList_item *pLeft = &pTabList->a[i-1];
144161dfc31dSdrh               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
144291bb0eedSdrh                         columnIndex(pLeft->pTab, zName)>=0 ){
1443ad2d8307Sdrh                 /* In a NATURAL join, omit the join columns from the
1444ad2d8307Sdrh                 ** table on the right */
1445ad2d8307Sdrh                 continue;
1446ad2d8307Sdrh               }
144761dfc31dSdrh               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
1448ad2d8307Sdrh                 /* In a join with a USING clause, omit columns in the
1449ad2d8307Sdrh                 ** using clause from the table on the right. */
1450ad2d8307Sdrh                 continue;
1451ad2d8307Sdrh               }
145291bb0eedSdrh             }
1453a1644fd8Sdanielk1977             pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
145422f70c32Sdrh             if( pRight==0 ) break;
14551e536953Sdanielk1977             setQuotedToken(pParse, &pRight->token, zName);
1456d70dc52dSdrh             if( zTabName && (longNames || pTabList->nSrc>1) ){
1457a1644fd8Sdanielk1977               Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
1458a1644fd8Sdanielk1977               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
145922f70c32Sdrh               if( pExpr==0 ) break;
14601e536953Sdanielk1977               setQuotedToken(pParse, &pLeft->token, zTabName);
14611e536953Sdanielk1977               setToken(&pExpr->span,
14621e536953Sdanielk1977                   sqlite3MPrintf(db, "%s.%s", zTabName, zName));
14636977fea8Sdrh               pExpr->span.dyn = 1;
14646977fea8Sdrh               pExpr->token.z = 0;
14656977fea8Sdrh               pExpr->token.n = 0;
14666977fea8Sdrh               pExpr->token.dyn = 0;
146722f70c32Sdrh             }else{
146822f70c32Sdrh               pExpr = pRight;
14696977fea8Sdrh               pExpr->span = pExpr->token;
1470f3b863edSdanielk1977               pExpr->span.dyn = 0;
147122f70c32Sdrh             }
1472d70dc52dSdrh             if( longNames ){
147317435752Sdrh               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
1474d70dc52dSdrh             }else{
147517435752Sdrh               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
1476d8bc7086Sdrh             }
1477d8bc7086Sdrh           }
1478d70dc52dSdrh         }
147954473229Sdrh         if( !tableSeen ){
1480cf55b7aeSdrh           if( zTName ){
1481cf55b7aeSdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
1482f5db2d3eSdrh           }else{
14834adee20fSdanielk1977             sqlite3ErrorMsg(pParse, "no tables specified");
1484f5db2d3eSdrh           }
148554473229Sdrh           rc = 1;
148654473229Sdrh         }
148717435752Sdrh         sqlite3_free(zTName);
14887c917d19Sdrh       }
14897c917d19Sdrh     }
14904adee20fSdanielk1977     sqlite3ExprListDelete(pEList);
14917c917d19Sdrh     p->pEList = pNew;
1492d8bc7086Sdrh   }
1493bb4957f8Sdrh #if SQLITE_MAX_COLUMN
1494bb4957f8Sdrh   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1495e5c941b8Sdrh     sqlite3ErrorMsg(pParse, "too many columns in result set");
1496e5c941b8Sdrh     rc = SQLITE_ERROR;
1497e5c941b8Sdrh   }
1498bb4957f8Sdrh #endif
149917435752Sdrh   if( db->mallocFailed ){
1500f3b863edSdanielk1977     rc = SQLITE_NOMEM;
1501f3b863edSdanielk1977   }
150254473229Sdrh   return rc;
1503d8bc7086Sdrh }
1504d8bc7086Sdrh 
1505ff78bd2fSdrh /*
15069a99334dSdrh ** pE is a pointer to an expression which is a single term in
15079a99334dSdrh ** ORDER BY or GROUP BY clause.
1508d8bc7086Sdrh **
15099a99334dSdrh ** If pE evaluates to an integer constant i, then return i.
15109a99334dSdrh ** This is an indication to the caller that it should sort
15119a99334dSdrh ** by the i-th column of the result set.
15129a99334dSdrh **
15139a99334dSdrh ** If pE is a well-formed expression and the SELECT statement
15149a99334dSdrh ** is not compound, then return 0.  This indicates to the
15159a99334dSdrh ** caller that it should sort by the value of the ORDER BY
15169a99334dSdrh ** expression.
15179a99334dSdrh **
15189a99334dSdrh ** If the SELECT is compound, then attempt to match pE against
15199a99334dSdrh ** result set columns in the left-most SELECT statement.  Return
15209a99334dSdrh ** the index i of the matching column, as an indication to the
15219a99334dSdrh ** caller that it should sort by the i-th column.  If there is
15229a99334dSdrh ** no match, return -1 and leave an error message in pParse.
1523d8bc7086Sdrh */
15249a99334dSdrh static int matchOrderByTermToExprList(
15259a99334dSdrh   Parse *pParse,     /* Parsing context for error messages */
15269a99334dSdrh   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
15279a99334dSdrh   Expr *pE,          /* The specific ORDER BY term */
15289a99334dSdrh   int idx,           /* When ORDER BY term is this */
15299a99334dSdrh   int isCompound,    /* True if this is a compound SELECT */
15309a99334dSdrh   u8 *pHasAgg        /* True if expression contains aggregate functions */
1531d8bc7086Sdrh ){
15329a99334dSdrh   int i;             /* Loop counter */
15339a99334dSdrh   ExprList *pEList;  /* The columns of the result set */
15349a99334dSdrh   NameContext nc;    /* Name context for resolving pE */
15359a99334dSdrh 
15369a99334dSdrh 
15379a99334dSdrh   /* If the term is an integer constant, return the value of that
15389a99334dSdrh   ** constant */
15399a99334dSdrh   pEList = pSelect->pEList;
15409a99334dSdrh   if( sqlite3ExprIsInteger(pE, &i) ){
15419a99334dSdrh     if( i<=0 ){
15429a99334dSdrh       /* If i is too small, make it too big.  That way the calling
15439a99334dSdrh       ** function still sees a value that is out of range, but does
15449a99334dSdrh       ** not confuse the column number with 0 or -1 result code.
15459a99334dSdrh       */
15469a99334dSdrh       i = pEList->nExpr+1;
15479a99334dSdrh     }
15489a99334dSdrh     return i;
15499a99334dSdrh   }
15509a99334dSdrh 
15519a99334dSdrh   /* If the term is a simple identifier that try to match that identifier
15529a99334dSdrh   ** against a column name in the result set.
15539a99334dSdrh   */
15549a99334dSdrh   if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){
155517435752Sdrh     sqlite3 *db = pParse->db;
15569a99334dSdrh     char *zCol = sqlite3NameFromToken(db, &pE->token);
1557ef0bea92Sdrh     if( zCol==0 ){
15589a99334dSdrh       return -1;
15599a99334dSdrh     }
15609a99334dSdrh     for(i=0; i<pEList->nExpr; i++){
15619a99334dSdrh       char *zAs = pEList->a[i].zName;
15629a99334dSdrh       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
15639a99334dSdrh         sqlite3_free(zCol);
15649a99334dSdrh         return i+1;
15659a99334dSdrh       }
15669a99334dSdrh     }
15679a99334dSdrh     sqlite3_free(zCol);
15684c774314Sdrh   }
156970517ab9Sdanielk1977 
15709a99334dSdrh   /* Resolve all names in the ORDER BY term expression
15719a99334dSdrh   */
157270517ab9Sdanielk1977   memset(&nc, 0, sizeof(nc));
157370517ab9Sdanielk1977   nc.pParse = pParse;
15749a99334dSdrh   nc.pSrcList = pSelect->pSrc;
157570517ab9Sdanielk1977   nc.pEList = pEList;
157670517ab9Sdanielk1977   nc.allowAgg = 1;
15774c774314Sdrh   nc.nErr = 0;
15789a99334dSdrh   if( sqlite3ExprResolveNames(&nc, pE) ){
15791e281291Sdrh     if( isCompound ){
15801e281291Sdrh       sqlite3ErrorClear(pParse);
15811e281291Sdrh       return 0;
15821e281291Sdrh     }else{
15839a99334dSdrh       return -1;
15849a99334dSdrh     }
15851e281291Sdrh   }
15869a99334dSdrh   if( nc.hasAgg && pHasAgg ){
15879a99334dSdrh     *pHasAgg = 1;
15889a99334dSdrh   }
15899a99334dSdrh 
15909a99334dSdrh   /* For a compound SELECT, we need to try to match the ORDER BY
15919a99334dSdrh   ** expression against an expression in the result set
15929a99334dSdrh   */
15939a99334dSdrh   if( isCompound ){
15949a99334dSdrh     for(i=0; i<pEList->nExpr; i++){
15959a99334dSdrh       if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
15969a99334dSdrh         return i+1;
15979a99334dSdrh       }
15989a99334dSdrh     }
15994c774314Sdrh   }
16001e281291Sdrh   return 0;
160170517ab9Sdanielk1977 }
160270517ab9Sdanielk1977 
16039a99334dSdrh 
16049a99334dSdrh /*
16059a99334dSdrh ** Analyze and ORDER BY or GROUP BY clause in a simple SELECT statement.
16069a99334dSdrh ** Return the number of errors seen.
16079a99334dSdrh **
16089a99334dSdrh ** Every term of the ORDER BY or GROUP BY clause needs to be an
16099a99334dSdrh ** expression.  If any expression is an integer constant, then
16109a99334dSdrh ** that expression is replaced by the corresponding
16119a99334dSdrh ** expression from the result set.
16129a99334dSdrh */
16139a99334dSdrh static int processOrderGroupBy(
16149a99334dSdrh   Parse *pParse,        /* Parsing context.  Leave error messages here */
16159a99334dSdrh   Select *pSelect,      /* The SELECT statement containing the clause */
16169a99334dSdrh   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
16179a99334dSdrh   int isOrder,          /* 1 for ORDER BY.  0 for GROUP BY */
16189a99334dSdrh   u8 *pHasAgg           /* Set to TRUE if any term contains an aggregate */
16199a99334dSdrh ){
16209a99334dSdrh   int i;
16219a99334dSdrh   sqlite3 *db = pParse->db;
16229a99334dSdrh   ExprList *pEList;
16239a99334dSdrh 
162415cdbebeSdanielk1977   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
1625bb4957f8Sdrh #if SQLITE_MAX_COLUMN
1626bb4957f8Sdrh   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
16279a99334dSdrh     const char *zType = isOrder ? "ORDER" : "GROUP";
16289a99334dSdrh     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
16299a99334dSdrh     return 1;
16309a99334dSdrh   }
1631bb4957f8Sdrh #endif
16329a99334dSdrh   pEList = pSelect->pEList;
16339a99334dSdrh   if( pEList==0 ){
16349a99334dSdrh     return 0;
16359a99334dSdrh   }
16369a99334dSdrh   for(i=0; i<pOrderBy->nExpr; i++){
16379a99334dSdrh     int iCol;
16389a99334dSdrh     Expr *pE = pOrderBy->a[i].pExpr;
16399a99334dSdrh     iCol = matchOrderByTermToExprList(pParse, pSelect, pE, i+1, 0, pHasAgg);
164070517ab9Sdanielk1977     if( iCol<0 ){
16419a99334dSdrh       return 1;
16429a99334dSdrh     }
16439a99334dSdrh     if( iCol>pEList->nExpr ){
16449a99334dSdrh       const char *zType = isOrder ? "ORDER" : "GROUP";
164570517ab9Sdanielk1977       sqlite3ErrorMsg(pParse,
16469a99334dSdrh          "%r %s BY term out of range - should be "
16479a99334dSdrh          "between 1 and %d", i+1, zType, pEList->nExpr);
16489a99334dSdrh       return 1;
16499a99334dSdrh     }
16509a99334dSdrh     if( iCol>0 ){
16519a99334dSdrh       CollSeq *pColl = pE->pColl;
16529a99334dSdrh       int flags = pE->flags & EP_ExpCollate;
16539a99334dSdrh       sqlite3ExprDelete(pE);
16549a99334dSdrh       pE = sqlite3ExprDup(db, pEList->a[iCol-1].pExpr);
16559a99334dSdrh       pOrderBy->a[i].pExpr = pE;
165615cdbebeSdanielk1977       if( pE && pColl && flags ){
16579a99334dSdrh         pE->pColl = pColl;
16589a99334dSdrh         pE->flags |= flags;
16599a99334dSdrh       }
16609a99334dSdrh     }
16619a99334dSdrh   }
16629a99334dSdrh   return 0;
16639a99334dSdrh }
16649a99334dSdrh 
16659a99334dSdrh /*
16669a99334dSdrh ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement.  Return
16679a99334dSdrh ** the number of errors seen.
16689a99334dSdrh **
16699a99334dSdrh ** The processing depends on whether the SELECT is simple or compound.
16709a99334dSdrh ** For a simple SELECT statement, evry term of the ORDER BY or GROUP BY
16719a99334dSdrh ** clause needs to be an expression.  If any expression is an integer
16729a99334dSdrh ** constant, then that expression is replaced by the corresponding
16739a99334dSdrh ** expression from the result set.
16749a99334dSdrh **
16759a99334dSdrh ** For compound SELECT statements, every expression needs to be of
16769a99334dSdrh ** type TK_COLUMN with a iTable value as given in the 4th parameter.
16779a99334dSdrh ** If any expression is an integer, that becomes the column number.
16789a99334dSdrh ** Otherwise, match the expression against result set columns from
16799a99334dSdrh ** the left-most SELECT.
16809a99334dSdrh */
16819a99334dSdrh static int processCompoundOrderBy(
16829a99334dSdrh   Parse *pParse,        /* Parsing context.  Leave error messages here */
16839a99334dSdrh   Select *pSelect,      /* The SELECT statement containing the ORDER BY */
16849a99334dSdrh   int iTable            /* Output table for compound SELECT statements */
16859a99334dSdrh ){
16869a99334dSdrh   int i;
16879a99334dSdrh   ExprList *pOrderBy;
16889a99334dSdrh   ExprList *pEList;
16891e281291Sdrh   sqlite3 *db;
16901e281291Sdrh   int moreToDo = 1;
16919a99334dSdrh 
16929a99334dSdrh   pOrderBy = pSelect->pOrderBy;
16939a99334dSdrh   if( pOrderBy==0 ) return 0;
1694bb4957f8Sdrh   db = pParse->db;
1695bb4957f8Sdrh #if SQLITE_MAX_COLUMN
1696bb4957f8Sdrh   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
16979a99334dSdrh     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
16989a99334dSdrh     return 1;
16999a99334dSdrh   }
1700bb4957f8Sdrh #endif
17011e281291Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
17021e281291Sdrh     pOrderBy->a[i].done = 0;
17031e281291Sdrh   }
17049a99334dSdrh   while( pSelect->pPrior ){
17059a99334dSdrh     pSelect = pSelect->pPrior;
17069a99334dSdrh   }
17071e281291Sdrh   while( pSelect && moreToDo ){
17081e281291Sdrh     moreToDo = 0;
17099a99334dSdrh     for(i=0; i<pOrderBy->nExpr; i++){
1710ac559264Sdanielk1977       int iCol = -1;
17118f0ecaaeSdrh       Expr *pE, *pDup;
17121e281291Sdrh       if( pOrderBy->a[i].done ) continue;
17131e281291Sdrh       pE = pOrderBy->a[i].pExpr;
17148f0ecaaeSdrh       pDup = sqlite3ExprDup(db, pE);
1715ac559264Sdanielk1977       if( !db->mallocFailed ){
1716ac559264Sdanielk1977         assert(pDup);
17171e281291Sdrh         iCol = matchOrderByTermToExprList(pParse, pSelect, pDup, i+1, 1, 0);
1718ac559264Sdanielk1977       }
17191e281291Sdrh       sqlite3ExprDelete(pDup);
17209a99334dSdrh       if( iCol<0 ){
17219a99334dSdrh         return 1;
17229a99334dSdrh       }
17231e281291Sdrh       pEList = pSelect->pEList;
17241e281291Sdrh       if( pEList==0 ){
17251e281291Sdrh         return 1;
17261e281291Sdrh       }
17279a99334dSdrh       if( iCol>pEList->nExpr ){
17289a99334dSdrh         sqlite3ErrorMsg(pParse,
17299a99334dSdrh            "%r ORDER BY term out of range - should be "
17309a99334dSdrh            "between 1 and %d", i+1, pEList->nExpr);
17319a99334dSdrh         return 1;
17329a99334dSdrh       }
17331e281291Sdrh       if( iCol>0 ){
1734967e8b73Sdrh         pE->op = TK_COLUMN;
1735d8bc7086Sdrh         pE->iTable = iTable;
1736a58fdfb1Sdanielk1977         pE->iAgg = -1;
17379a99334dSdrh         pE->iColumn = iCol-1;
17389a99334dSdrh         pE->pTab = 0;
17391e281291Sdrh         pOrderBy->a[i].done = 1;
17401e281291Sdrh       }else{
17411e281291Sdrh         moreToDo = 1;
17421e281291Sdrh       }
17431e281291Sdrh     }
17441e281291Sdrh     pSelect = pSelect->pNext;
17451e281291Sdrh   }
17461e281291Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
17471e281291Sdrh     if( pOrderBy->a[i].done==0 ){
17481e281291Sdrh       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
17491e281291Sdrh             "column in the result set", i+1);
17501e281291Sdrh       return 1;
17511e281291Sdrh     }
175270517ab9Sdanielk1977   }
17539a99334dSdrh   return 0;
1754d8bc7086Sdrh }
1755d8bc7086Sdrh 
1756d8bc7086Sdrh /*
1757d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1758d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1759d8bc7086Sdrh */
17604adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1761d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1762d8bc7086Sdrh   if( v==0 ){
17634adee20fSdanielk1977     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1764949f9cd5Sdrh #ifndef SQLITE_OMIT_TRACE
1765949f9cd5Sdrh     if( v ){
1766949f9cd5Sdrh       sqlite3VdbeAddOp0(v, OP_Trace);
1767949f9cd5Sdrh     }
1768949f9cd5Sdrh #endif
1769d8bc7086Sdrh   }
1770d8bc7086Sdrh   return v;
1771d8bc7086Sdrh }
1772d8bc7086Sdrh 
177315007a99Sdrh 
1774d8bc7086Sdrh /*
17757b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
1776ec7429aeSdrh ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
17777b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
1778a2dc3b1aSdanielk1977 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1779a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute
1780a2dc3b1aSdanielk1977 ** the limit and offset.  If there is no limit and/or offset, then
1781a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative.
17827b58daeaSdrh **
1783d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if
1784ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset.  iLimit and
17857b58daeaSdrh ** iOffset should have been preset to appropriate default values
17867b58daeaSdrh ** (usually but not always -1) prior to calling this routine.
1787ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
17887b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
17897b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
17907b58daeaSdrh ** SELECT statements.
17917b58daeaSdrh */
1792ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
179302afc861Sdrh   Vdbe *v = 0;
179402afc861Sdrh   int iLimit = 0;
179515007a99Sdrh   int iOffset;
1796b7654111Sdrh   int addr1;
179715007a99Sdrh 
17987b58daeaSdrh   /*
17997b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
18007b58daeaSdrh   ** contraversy about what the correct behavior should be.
18017b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
18027b58daeaSdrh   ** no rows.
18037b58daeaSdrh   */
1804a2dc3b1aSdanielk1977   if( p->pLimit ){
18050a07c107Sdrh     p->iLimit = iLimit = ++pParse->nMem;
180615007a99Sdrh     v = sqlite3GetVdbe(pParse);
18077b58daeaSdrh     if( v==0 ) return;
1808b7654111Sdrh     sqlite3ExprCode(pParse, p->pLimit, iLimit);
1809b7654111Sdrh     sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
1810d4e70ebdSdrh     VdbeComment((v, "LIMIT counter"));
18113c84ddffSdrh     sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
18127b58daeaSdrh   }
1813a2dc3b1aSdanielk1977   if( p->pOffset ){
18140a07c107Sdrh     p->iOffset = iOffset = ++pParse->nMem;
1815b7654111Sdrh     if( p->pLimit ){
1816b7654111Sdrh       pParse->nMem++;   /* Allocate an extra register for limit+offset */
1817b7654111Sdrh     }
181815007a99Sdrh     v = sqlite3GetVdbe(pParse);
18197b58daeaSdrh     if( v==0 ) return;
1820b7654111Sdrh     sqlite3ExprCode(pParse, p->pOffset, iOffset);
1821b7654111Sdrh     sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
1822d4e70ebdSdrh     VdbeComment((v, "OFFSET counter"));
18233c84ddffSdrh     addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
1824b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
182515007a99Sdrh     sqlite3VdbeJumpHere(v, addr1);
1826d59ba6ceSdrh     if( p->pLimit ){
1827b7654111Sdrh       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
1828d4e70ebdSdrh       VdbeComment((v, "LIMIT+OFFSET"));
1829b7654111Sdrh       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
1830b7654111Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
1831b7654111Sdrh       sqlite3VdbeJumpHere(v, addr1);
1832b7654111Sdrh     }
1833d59ba6ceSdrh   }
18347b58daeaSdrh }
18357b58daeaSdrh 
18367b58daeaSdrh /*
18370342b1f5Sdrh ** Allocate a virtual index to use for sorting.
1838d3d39e93Sdrh */
18394db38a70Sdrh static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
18400342b1f5Sdrh   if( pOrderBy ){
1841dc1bdc4fSdanielk1977     int addr;
18429d2985c7Sdrh     assert( pOrderBy->iECursor==0 );
18439d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
184466a5167bSdrh     addr = sqlite3VdbeAddOp2(pParse->pVdbe, OP_OpenEphemeral,
18459d2985c7Sdrh                             pOrderBy->iECursor, pOrderBy->nExpr+1);
1846b9bb7c18Sdrh     assert( p->addrOpenEphm[2] == -1 );
1847b9bb7c18Sdrh     p->addrOpenEphm[2] = addr;
1848736c22b8Sdrh   }
1849dc1bdc4fSdanielk1977 }
1850dc1bdc4fSdanielk1977 
1851b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1852fbc4ee7bSdrh /*
1853fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
1854fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
1855fbc4ee7bSdrh ** the column has no default collating sequence.
1856fbc4ee7bSdrh **
1857fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
1858fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
1859fbc4ee7bSdrh */
1860dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1861fbc4ee7bSdrh   CollSeq *pRet;
1862dc1bdc4fSdanielk1977   if( p->pPrior ){
1863dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1864fbc4ee7bSdrh   }else{
1865fbc4ee7bSdrh     pRet = 0;
1866dc1bdc4fSdanielk1977   }
1867fbc4ee7bSdrh   if( pRet==0 ){
1868dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1869dc1bdc4fSdanielk1977   }
1870dc1bdc4fSdanielk1977   return pRet;
1871d3d39e93Sdrh }
1872b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1873d3d39e93Sdrh 
1874b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1875d3d39e93Sdrh /*
187682c3d636Sdrh ** This routine is called to process a query that is really the union
187782c3d636Sdrh ** or intersection of two or more separate queries.
1878c926afbcSdrh **
1879e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1880e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1881e78e8284Sdrh ** in which case this routine will be called recursively.
1882e78e8284Sdrh **
1883e78e8284Sdrh ** The results of the total query are to be written into a destination
1884e78e8284Sdrh ** of type eDest with parameter iParm.
1885e78e8284Sdrh **
1886e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1887e78e8284Sdrh **
1888e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1889e78e8284Sdrh **
1890e78e8284Sdrh ** This statement is parsed up as follows:
1891e78e8284Sdrh **
1892e78e8284Sdrh **     SELECT c FROM t3
1893e78e8284Sdrh **      |
1894e78e8284Sdrh **      `----->  SELECT b FROM t2
1895e78e8284Sdrh **                |
18964b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1897e78e8284Sdrh **
1898e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1899e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1900e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1901e78e8284Sdrh **
1902e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1903e78e8284Sdrh ** individual selects always group from left to right.
190482c3d636Sdrh */
190584ac9d02Sdanielk1977 static int multiSelect(
1906fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
1907fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
19086c8c8ce0Sdanielk1977   SelectDest *pDest,    /* What to do with query results */
190984ac9d02Sdanielk1977   char *aff             /* If eDest is SRT_Union, the affinity string */
191084ac9d02Sdanielk1977 ){
191184ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
191210e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
191310e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
19148cdbf836Sdrh   int nCol;             /* Number of columns in the result set */
19150342b1f5Sdrh   ExprList *pOrderBy;   /* The ORDER BY clause on p */
19160342b1f5Sdrh   int aSetP2[2];        /* Set P2 value of these op to number of columns */
19170342b1f5Sdrh   int nSetP2 = 0;       /* Number of slots in aSetP2[] used */
19181013c932Sdrh   SelectDest dest;      /* Alternative data destination */
191982c3d636Sdrh 
19201013c932Sdrh   dest = *pDest;
19216c8c8ce0Sdanielk1977 
19227b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1923fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
192482c3d636Sdrh   */
192584ac9d02Sdanielk1977   if( p==0 || p->pPrior==0 ){
192684ac9d02Sdanielk1977     rc = 1;
192784ac9d02Sdanielk1977     goto multi_select_end;
192884ac9d02Sdanielk1977   }
1929d8bc7086Sdrh   pPrior = p->pPrior;
19300342b1f5Sdrh   assert( pPrior->pRightmost!=pPrior );
19310342b1f5Sdrh   assert( pPrior->pRightmost==p->pRightmost );
1932d8bc7086Sdrh   if( pPrior->pOrderBy ){
19334adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1934da93d238Sdrh       selectOpName(p->op));
193584ac9d02Sdanielk1977     rc = 1;
193684ac9d02Sdanielk1977     goto multi_select_end;
193782c3d636Sdrh   }
1938a2dc3b1aSdanielk1977   if( pPrior->pLimit ){
19394adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
19407b58daeaSdrh       selectOpName(p->op));
194184ac9d02Sdanielk1977     rc = 1;
194284ac9d02Sdanielk1977     goto multi_select_end;
19437b58daeaSdrh   }
194482c3d636Sdrh 
1945d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
1946d8bc7086Sdrh   */
19474adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
194884ac9d02Sdanielk1977   if( v==0 ){
194984ac9d02Sdanielk1977     rc = 1;
195084ac9d02Sdanielk1977     goto multi_select_end;
195184ac9d02Sdanielk1977   }
1952d8bc7086Sdrh 
19531cc3d75fSdrh   /* Create the destination temporary table if necessary
19541cc3d75fSdrh   */
19556c8c8ce0Sdanielk1977   if( dest.eDest==SRT_EphemTab ){
1956b4964b72Sdanielk1977     assert( p->pEList );
19570342b1f5Sdrh     assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
195866a5167bSdrh     aSetP2[nSetP2++] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, 0);
19596c8c8ce0Sdanielk1977     dest.eDest = SRT_Table;
19601cc3d75fSdrh   }
19611cc3d75fSdrh 
1962f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1963d8bc7086Sdrh   */
19640342b1f5Sdrh   pOrderBy = p->pOrderBy;
196582c3d636Sdrh   switch( p->op ){
1966f46f905aSdrh     case TK_ALL: {
19670342b1f5Sdrh       if( pOrderBy==0 ){
1968ec7429aeSdrh         int addr = 0;
1969a2dc3b1aSdanielk1977         assert( !pPrior->pLimit );
1970a2dc3b1aSdanielk1977         pPrior->pLimit = p->pLimit;
1971a2dc3b1aSdanielk1977         pPrior->pOffset = p->pOffset;
19726c8c8ce0Sdanielk1977         rc = sqlite3Select(pParse, pPrior, &dest, 0, 0, 0, aff);
1973ad68cb6bSdanielk1977         p->pLimit = 0;
1974ad68cb6bSdanielk1977         p->pOffset = 0;
197584ac9d02Sdanielk1977         if( rc ){
197684ac9d02Sdanielk1977           goto multi_select_end;
197784ac9d02Sdanielk1977         }
1978f46f905aSdrh         p->pPrior = 0;
19797b58daeaSdrh         p->iLimit = pPrior->iLimit;
19807b58daeaSdrh         p->iOffset = pPrior->iOffset;
1981ec7429aeSdrh         if( p->iLimit>=0 ){
19823c84ddffSdrh           addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
1983d4e70ebdSdrh           VdbeComment((v, "Jump ahead if LIMIT reached"));
1984ec7429aeSdrh         }
19856c8c8ce0Sdanielk1977         rc = sqlite3Select(pParse, p, &dest, 0, 0, 0, aff);
1986f46f905aSdrh         p->pPrior = pPrior;
198784ac9d02Sdanielk1977         if( rc ){
198884ac9d02Sdanielk1977           goto multi_select_end;
198984ac9d02Sdanielk1977         }
1990ec7429aeSdrh         if( addr ){
1991ec7429aeSdrh           sqlite3VdbeJumpHere(v, addr);
1992ec7429aeSdrh         }
1993f46f905aSdrh         break;
1994f46f905aSdrh       }
1995f46f905aSdrh       /* For UNION ALL ... ORDER BY fall through to the next case */
1996f46f905aSdrh     }
199782c3d636Sdrh     case TK_EXCEPT:
199882c3d636Sdrh     case TK_UNION: {
1999d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
2000742f947bSdanielk1977       int op = 0;      /* One of the SRT_ operations to apply to self */
2001d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
2002a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
2003dc1bdc4fSdanielk1977       int addr;
20046c8c8ce0Sdanielk1977       SelectDest uniondest;
200582c3d636Sdrh 
2006d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
20076c8c8ce0Sdanielk1977       if( dest.eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
2008d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
2009c926afbcSdrh         ** right.
2010d8bc7086Sdrh         */
20116c8c8ce0Sdanielk1977         unionTab = dest.iParm;
201282c3d636Sdrh       }else{
2013d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
2014d8bc7086Sdrh         ** intermediate results.
2015d8bc7086Sdrh         */
201682c3d636Sdrh         unionTab = pParse->nTab++;
20179a99334dSdrh         if( processCompoundOrderBy(pParse, p, unionTab) ){
201884ac9d02Sdanielk1977           rc = 1;
201984ac9d02Sdanielk1977           goto multi_select_end;
2020d8bc7086Sdrh         }
202166a5167bSdrh         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
20220342b1f5Sdrh         if( priorOp==SRT_Table ){
20230342b1f5Sdrh           assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
20240342b1f5Sdrh           aSetP2[nSetP2++] = addr;
20250342b1f5Sdrh         }else{
2026b9bb7c18Sdrh           assert( p->addrOpenEphm[0] == -1 );
2027b9bb7c18Sdrh           p->addrOpenEphm[0] = addr;
2028b9bb7c18Sdrh           p->pRightmost->usesEphm = 1;
2029dc1bdc4fSdanielk1977         }
20300342b1f5Sdrh         createSortingIndex(pParse, p, pOrderBy);
203184ac9d02Sdanielk1977         assert( p->pEList );
2032d8bc7086Sdrh       }
2033d8bc7086Sdrh 
2034d8bc7086Sdrh       /* Code the SELECT statements to our left
2035d8bc7086Sdrh       */
2036b3bce662Sdanielk1977       assert( !pPrior->pOrderBy );
20371013c932Sdrh       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
20386c8c8ce0Sdanielk1977       rc = sqlite3Select(pParse, pPrior, &uniondest, 0, 0, 0, aff);
203984ac9d02Sdanielk1977       if( rc ){
204084ac9d02Sdanielk1977         goto multi_select_end;
204184ac9d02Sdanielk1977       }
2042d8bc7086Sdrh 
2043d8bc7086Sdrh       /* Code the current SELECT statement
2044d8bc7086Sdrh       */
2045d8bc7086Sdrh       switch( p->op ){
2046d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
2047d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
2048d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
2049d8bc7086Sdrh       }
205082c3d636Sdrh       p->pPrior = 0;
2051c926afbcSdrh       p->pOrderBy = 0;
20524b14b4d7Sdrh       p->disallowOrderBy = pOrderBy!=0;
2053a2dc3b1aSdanielk1977       pLimit = p->pLimit;
2054a2dc3b1aSdanielk1977       p->pLimit = 0;
2055a2dc3b1aSdanielk1977       pOffset = p->pOffset;
2056a2dc3b1aSdanielk1977       p->pOffset = 0;
20576c8c8ce0Sdanielk1977       uniondest.eDest = op;
20586c8c8ce0Sdanielk1977       rc = sqlite3Select(pParse, p, &uniondest, 0, 0, 0, aff);
20595bd1bf2eSdrh       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
20605bd1bf2eSdrh       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
20615bd1bf2eSdrh       sqlite3ExprListDelete(p->pOrderBy);
206282c3d636Sdrh       p->pPrior = pPrior;
2063c926afbcSdrh       p->pOrderBy = pOrderBy;
2064a2dc3b1aSdanielk1977       sqlite3ExprDelete(p->pLimit);
2065a2dc3b1aSdanielk1977       p->pLimit = pLimit;
2066a2dc3b1aSdanielk1977       p->pOffset = pOffset;
2067be5fd490Sdrh       p->iLimit = -1;
2068be5fd490Sdrh       p->iOffset = -1;
206984ac9d02Sdanielk1977       if( rc ){
207084ac9d02Sdanielk1977         goto multi_select_end;
207184ac9d02Sdanielk1977       }
207284ac9d02Sdanielk1977 
2073d8bc7086Sdrh 
2074d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
2075d8bc7086Sdrh       ** it is that we currently need.
2076d8bc7086Sdrh       */
20776c8c8ce0Sdanielk1977       if( dest.eDest!=priorOp || unionTab!=dest.iParm ){
20786b56344dSdrh         int iCont, iBreak, iStart;
207982c3d636Sdrh         assert( p->pEList );
20806c8c8ce0Sdanielk1977         if( dest.eDest==SRT_Callback ){
208192378253Sdrh           Select *pFirst = p;
208292378253Sdrh           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
208392378253Sdrh           generateColumnNames(pParse, 0, pFirst->pEList);
208441202ccaSdrh         }
20854adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
20864adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
2087ec7429aeSdrh         computeLimitRegisters(pParse, p, iBreak);
208866a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
20894adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
2090d2b3e23bSdrh         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
20916c8c8ce0Sdanielk1977                         pOrderBy, -1, &dest, iCont, iBreak, 0);
20924adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
209366a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
20944adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
209566a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
209682c3d636Sdrh       }
209782c3d636Sdrh       break;
209882c3d636Sdrh     }
209982c3d636Sdrh     case TK_INTERSECT: {
210082c3d636Sdrh       int tab1, tab2;
21016b56344dSdrh       int iCont, iBreak, iStart;
2102a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset;
2103dc1bdc4fSdanielk1977       int addr;
21041013c932Sdrh       SelectDest intersectdest;
21059cbf3425Sdrh       int r1;
210682c3d636Sdrh 
2107d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
21086206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
2109d8bc7086Sdrh       ** by allocating the tables we will need.
2110d8bc7086Sdrh       */
211182c3d636Sdrh       tab1 = pParse->nTab++;
211282c3d636Sdrh       tab2 = pParse->nTab++;
21139a99334dSdrh       if( processCompoundOrderBy(pParse, p, tab1) ){
211484ac9d02Sdanielk1977         rc = 1;
211584ac9d02Sdanielk1977         goto multi_select_end;
2116d8bc7086Sdrh       }
21170342b1f5Sdrh       createSortingIndex(pParse, p, pOrderBy);
2118dc1bdc4fSdanielk1977 
211966a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
2120b9bb7c18Sdrh       assert( p->addrOpenEphm[0] == -1 );
2121b9bb7c18Sdrh       p->addrOpenEphm[0] = addr;
2122b9bb7c18Sdrh       p->pRightmost->usesEphm = 1;
212384ac9d02Sdanielk1977       assert( p->pEList );
2124d8bc7086Sdrh 
2125d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
2126d8bc7086Sdrh       */
21271013c932Sdrh       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
21286c8c8ce0Sdanielk1977       rc = sqlite3Select(pParse, pPrior, &intersectdest, 0, 0, 0, aff);
212984ac9d02Sdanielk1977       if( rc ){
213084ac9d02Sdanielk1977         goto multi_select_end;
213184ac9d02Sdanielk1977       }
2132d8bc7086Sdrh 
2133d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
2134d8bc7086Sdrh       */
213566a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
2136b9bb7c18Sdrh       assert( p->addrOpenEphm[1] == -1 );
2137b9bb7c18Sdrh       p->addrOpenEphm[1] = addr;
213882c3d636Sdrh       p->pPrior = 0;
2139a2dc3b1aSdanielk1977       pLimit = p->pLimit;
2140a2dc3b1aSdanielk1977       p->pLimit = 0;
2141a2dc3b1aSdanielk1977       pOffset = p->pOffset;
2142a2dc3b1aSdanielk1977       p->pOffset = 0;
21436c8c8ce0Sdanielk1977       intersectdest.iParm = tab2;
21446c8c8ce0Sdanielk1977       rc = sqlite3Select(pParse, p, &intersectdest, 0, 0, 0, aff);
214582c3d636Sdrh       p->pPrior = pPrior;
2146a2dc3b1aSdanielk1977       sqlite3ExprDelete(p->pLimit);
2147a2dc3b1aSdanielk1977       p->pLimit = pLimit;
2148a2dc3b1aSdanielk1977       p->pOffset = pOffset;
214984ac9d02Sdanielk1977       if( rc ){
215084ac9d02Sdanielk1977         goto multi_select_end;
215184ac9d02Sdanielk1977       }
2152d8bc7086Sdrh 
2153d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
2154d8bc7086Sdrh       ** tables.
2155d8bc7086Sdrh       */
215682c3d636Sdrh       assert( p->pEList );
21576c8c8ce0Sdanielk1977       if( dest.eDest==SRT_Callback ){
215892378253Sdrh         Select *pFirst = p;
215992378253Sdrh         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
216092378253Sdrh         generateColumnNames(pParse, 0, pFirst->pEList);
216141202ccaSdrh       }
21624adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
21634adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
2164ec7429aeSdrh       computeLimitRegisters(pParse, p, iBreak);
216566a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
21669cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
21679cbf3425Sdrh       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
21689cbf3425Sdrh       sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1);
21699cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
2170d2b3e23bSdrh       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
21716c8c8ce0Sdanielk1977                       pOrderBy, -1, &dest, iCont, iBreak, 0);
21724adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
217366a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
21744adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
217566a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
217666a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
217782c3d636Sdrh       break;
217882c3d636Sdrh     }
217982c3d636Sdrh   }
21808cdbf836Sdrh 
21818cdbf836Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
21828cdbf836Sdrh   ** in their result sets.
21838cdbf836Sdrh   */
218482c3d636Sdrh   assert( p->pEList && pPrior->pEList );
218582c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
21864adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
2187da93d238Sdrh       " do not have the same number of result columns", selectOpName(p->op));
218884ac9d02Sdanielk1977     rc = 1;
218984ac9d02Sdanielk1977     goto multi_select_end;
21902282792aSdrh   }
219184ac9d02Sdanielk1977 
21928cdbf836Sdrh   /* Set the number of columns in temporary tables
21938cdbf836Sdrh   */
21948cdbf836Sdrh   nCol = p->pEList->nExpr;
21950342b1f5Sdrh   while( nSetP2 ){
21960342b1f5Sdrh     sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
21978cdbf836Sdrh   }
21988cdbf836Sdrh 
2199fbc4ee7bSdrh   /* Compute collating sequences used by either the ORDER BY clause or
2200fbc4ee7bSdrh   ** by any temporary tables needed to implement the compound select.
2201fbc4ee7bSdrh   ** Attach the KeyInfo structure to all temporary tables.  Invoke the
2202fbc4ee7bSdrh   ** ORDER BY processing if there is an ORDER BY clause.
22038cdbf836Sdrh   **
22048cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
22058cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
22068cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
22078cdbf836Sdrh   ** no temp tables are required.
2208fbc4ee7bSdrh   */
2209b9bb7c18Sdrh   if( pOrderBy || p->usesEphm ){
2210fbc4ee7bSdrh     int i;                        /* Loop counter */
2211fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
22120342b1f5Sdrh     Select *pLoop;                /* For looping through SELECT statements */
22131e31e0b2Sdrh     int nKeyCol;                  /* Number of entries in pKeyInfo->aCol[] */
2214f68d7d17Sdrh     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
2215f68d7d17Sdrh     CollSeq **aCopy;              /* A copy of pKeyInfo->aColl[] */
2216fbc4ee7bSdrh 
22170342b1f5Sdrh     assert( p->pRightmost==p );
22181e31e0b2Sdrh     nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0);
221917435752Sdrh     pKeyInfo = sqlite3DbMallocZero(pParse->db,
222017435752Sdrh                        sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1));
2221dc1bdc4fSdanielk1977     if( !pKeyInfo ){
2222dc1bdc4fSdanielk1977       rc = SQLITE_NOMEM;
2223dc1bdc4fSdanielk1977       goto multi_select_end;
2224dc1bdc4fSdanielk1977     }
2225dc1bdc4fSdanielk1977 
222614db2665Sdanielk1977     pKeyInfo->enc = ENC(pParse->db);
2227dc1bdc4fSdanielk1977     pKeyInfo->nField = nCol;
2228dc1bdc4fSdanielk1977 
22290342b1f5Sdrh     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
22300342b1f5Sdrh       *apColl = multiSelectCollSeq(pParse, p, i);
22310342b1f5Sdrh       if( 0==*apColl ){
22320342b1f5Sdrh         *apColl = pParse->db->pDfltColl;
2233dc1bdc4fSdanielk1977       }
2234dc1bdc4fSdanielk1977     }
2235dc1bdc4fSdanielk1977 
22360342b1f5Sdrh     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
22370342b1f5Sdrh       for(i=0; i<2; i++){
2238b9bb7c18Sdrh         int addr = pLoop->addrOpenEphm[i];
22390342b1f5Sdrh         if( addr<0 ){
22400342b1f5Sdrh           /* If [0] is unused then [1] is also unused.  So we can
22410342b1f5Sdrh           ** always safely abort as soon as the first unused slot is found */
2242b9bb7c18Sdrh           assert( pLoop->addrOpenEphm[1]<0 );
22430342b1f5Sdrh           break;
22440342b1f5Sdrh         }
22450342b1f5Sdrh         sqlite3VdbeChangeP2(v, addr, nCol);
224666a5167bSdrh         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
22470ee5a1e7Sdrh         pLoop->addrOpenEphm[i] = -1;
22480342b1f5Sdrh       }
2249dc1bdc4fSdanielk1977     }
2250dc1bdc4fSdanielk1977 
22510342b1f5Sdrh     if( pOrderBy ){
22520342b1f5Sdrh       struct ExprList_item *pOTerm = pOrderBy->a;
22534efc083fSdrh       int nOrderByExpr = pOrderBy->nExpr;
22540342b1f5Sdrh       int addr;
22554db38a70Sdrh       u8 *pSortOrder;
22560342b1f5Sdrh 
2257f68d7d17Sdrh       /* Reuse the same pKeyInfo for the ORDER BY as was used above for
2258f68d7d17Sdrh       ** the compound select statements.  Except we have to change out the
2259f68d7d17Sdrh       ** pKeyInfo->aColl[] values.  Some of the aColl[] values will be
2260f68d7d17Sdrh       ** reused when constructing the pKeyInfo for the ORDER BY, so make
2261f68d7d17Sdrh       ** a copy.  Sufficient space to hold both the nCol entries for
2262f68d7d17Sdrh       ** the compound select and the nOrderbyExpr entries for the ORDER BY
2263f68d7d17Sdrh       ** was allocated above.  But we need to move the compound select
2264f68d7d17Sdrh       ** entries out of the way before constructing the ORDER BY entries.
2265f68d7d17Sdrh       ** Move the compound select entries into aCopy[] where they can be
2266f68d7d17Sdrh       ** accessed and reused when constructing the ORDER BY entries.
2267f68d7d17Sdrh       ** Because nCol might be greater than or less than nOrderByExpr
2268f68d7d17Sdrh       ** we have to use memmove() when doing the copy.
2269f68d7d17Sdrh       */
22701e31e0b2Sdrh       aCopy = &pKeyInfo->aColl[nOrderByExpr];
22714efc083fSdrh       pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
2272f68d7d17Sdrh       memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
2273f68d7d17Sdrh 
22740342b1f5Sdrh       apColl = pKeyInfo->aColl;
22754efc083fSdrh       for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
22760342b1f5Sdrh         Expr *pExpr = pOTerm->pExpr;
22778b4c40d8Sdrh         if( (pExpr->flags & EP_ExpCollate) ){
22788b4c40d8Sdrh           assert( pExpr->pColl!=0 );
22798b4c40d8Sdrh           *apColl = pExpr->pColl;
228084ac9d02Sdanielk1977         }else{
22810342b1f5Sdrh           *apColl = aCopy[pExpr->iColumn];
228284ac9d02Sdanielk1977         }
22834db38a70Sdrh         *pSortOrder = pOTerm->sortOrder;
228484ac9d02Sdanielk1977       }
22850342b1f5Sdrh       assert( p->pRightmost==p );
2286b9bb7c18Sdrh       assert( p->addrOpenEphm[2]>=0 );
2287b9bb7c18Sdrh       addr = p->addrOpenEphm[2];
2288a670b226Sdanielk1977       sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2);
22894efc083fSdrh       pKeyInfo->nField = nOrderByExpr;
229066a5167bSdrh       sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
22914db38a70Sdrh       pKeyInfo = 0;
22926c8c8ce0Sdanielk1977       generateSortTail(pParse, p, v, p->pEList->nExpr, &dest);
2293dc1bdc4fSdanielk1977     }
2294dc1bdc4fSdanielk1977 
229517435752Sdrh     sqlite3_free(pKeyInfo);
2296dc1bdc4fSdanielk1977   }
2297dc1bdc4fSdanielk1977 
2298dc1bdc4fSdanielk1977 multi_select_end:
22991013c932Sdrh   pDest->iMem = dest.iMem;
2300ad27e761Sdrh   pDest->nMem = dest.nMem;
230184ac9d02Sdanielk1977   return rc;
23022282792aSdrh }
2303b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
23042282792aSdrh 
2305b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
230617435752Sdrh /* Forward Declarations */
230717435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*);
230817435752Sdrh static void substSelect(sqlite3*, Select *, int, ExprList *);
230917435752Sdrh 
23102282792aSdrh /*
2311832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
23126a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
231384e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
23146a3ea0e6Sdrh ** unchanged.)
2315832508b7Sdrh **
2316832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
2317832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
2318832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
2319832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
2320832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
2321832508b7Sdrh ** of the subquery rather the result set of the subquery.
2322832508b7Sdrh */
232317435752Sdrh static void substExpr(
232417435752Sdrh   sqlite3 *db,        /* Report malloc errors to this connection */
232517435752Sdrh   Expr *pExpr,        /* Expr in which substitution occurs */
232617435752Sdrh   int iTable,         /* Table to be substituted */
232717435752Sdrh   ExprList *pEList    /* Substitute expressions */
232817435752Sdrh ){
2329832508b7Sdrh   if( pExpr==0 ) return;
233050350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
233150350a15Sdrh     if( pExpr->iColumn<0 ){
233250350a15Sdrh       pExpr->op = TK_NULL;
233350350a15Sdrh     }else{
2334832508b7Sdrh       Expr *pNew;
233584e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
2336832508b7Sdrh       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
2337832508b7Sdrh       pNew = pEList->a[pExpr->iColumn].pExpr;
2338832508b7Sdrh       assert( pNew!=0 );
2339832508b7Sdrh       pExpr->op = pNew->op;
2340d94a6698Sdrh       assert( pExpr->pLeft==0 );
234117435752Sdrh       pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
2342d94a6698Sdrh       assert( pExpr->pRight==0 );
234317435752Sdrh       pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
2344d94a6698Sdrh       assert( pExpr->pList==0 );
234517435752Sdrh       pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
2346832508b7Sdrh       pExpr->iTable = pNew->iTable;
2347fbbe005aSdanielk1977       pExpr->pTab = pNew->pTab;
2348832508b7Sdrh       pExpr->iColumn = pNew->iColumn;
2349832508b7Sdrh       pExpr->iAgg = pNew->iAgg;
235017435752Sdrh       sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
235117435752Sdrh       sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
235217435752Sdrh       pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
2353a1cb183dSdanielk1977       pExpr->flags = pNew->flags;
235450350a15Sdrh     }
2355832508b7Sdrh   }else{
235617435752Sdrh     substExpr(db, pExpr->pLeft, iTable, pEList);
235717435752Sdrh     substExpr(db, pExpr->pRight, iTable, pEList);
235817435752Sdrh     substSelect(db, pExpr->pSelect, iTable, pEList);
235917435752Sdrh     substExprList(db, pExpr->pList, iTable, pEList);
2360832508b7Sdrh   }
2361832508b7Sdrh }
236217435752Sdrh static void substExprList(
236317435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
236417435752Sdrh   ExprList *pList,     /* List to scan and in which to make substitutes */
236517435752Sdrh   int iTable,          /* Table to be substituted */
236617435752Sdrh   ExprList *pEList     /* Substitute values */
236717435752Sdrh ){
2368832508b7Sdrh   int i;
2369832508b7Sdrh   if( pList==0 ) return;
2370832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
237117435752Sdrh     substExpr(db, pList->a[i].pExpr, iTable, pEList);
2372832508b7Sdrh   }
2373832508b7Sdrh }
237417435752Sdrh static void substSelect(
237517435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
237617435752Sdrh   Select *p,           /* SELECT statement in which to make substitutions */
237717435752Sdrh   int iTable,          /* Table to be replaced */
237817435752Sdrh   ExprList *pEList     /* Substitute values */
237917435752Sdrh ){
2380b3bce662Sdanielk1977   if( !p ) return;
238117435752Sdrh   substExprList(db, p->pEList, iTable, pEList);
238217435752Sdrh   substExprList(db, p->pGroupBy, iTable, pEList);
238317435752Sdrh   substExprList(db, p->pOrderBy, iTable, pEList);
238417435752Sdrh   substExpr(db, p->pHaving, iTable, pEList);
238517435752Sdrh   substExpr(db, p->pWhere, iTable, pEList);
238617435752Sdrh   substSelect(db, p->pPrior, iTable, pEList);
2387b3bce662Sdanielk1977 }
2388b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_VIEW) */
2389832508b7Sdrh 
2390b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
2391832508b7Sdrh /*
23921350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
23931350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
23941350b030Sdrh ** occurs.
23951350b030Sdrh **
23961350b030Sdrh ** To understand the concept of flattening, consider the following
23971350b030Sdrh ** query:
23981350b030Sdrh **
23991350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
24001350b030Sdrh **
24011350b030Sdrh ** The default way of implementing this query is to execute the
24021350b030Sdrh ** subquery first and store the results in a temporary table, then
24031350b030Sdrh ** run the outer query on that temporary table.  This requires two
24041350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
24051350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
2406832508b7Sdrh ** optimized.
24071350b030Sdrh **
2408832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
24091350b030Sdrh ** a single flat select, like this:
24101350b030Sdrh **
24111350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
24121350b030Sdrh **
24131350b030Sdrh ** The code generated for this simpification gives the same result
2414832508b7Sdrh ** but only has to scan the data once.  And because indices might
2415832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
2416832508b7Sdrh ** avoided.
24171350b030Sdrh **
2418832508b7Sdrh ** Flattening is only attempted if all of the following are true:
24191350b030Sdrh **
2420832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
24211350b030Sdrh **
2422832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
2423832508b7Sdrh **
24248af4d3acSdrh **   (3)  The subquery is not the right operand of a left outer join, or
24258af4d3acSdrh **        the subquery is not itself a join.  (Ticket #306)
2426832508b7Sdrh **
2427832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
2428832508b7Sdrh **
2429832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
2430832508b7Sdrh **        aggregates.
2431832508b7Sdrh **
2432832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
2433832508b7Sdrh **        DISTINCT.
2434832508b7Sdrh **
243508192d5fSdrh **   (7)  The subquery has a FROM clause.
243608192d5fSdrh **
2437df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
2438df199a25Sdrh **
2439df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
2440df199a25Sdrh **        aggregates.
2441df199a25Sdrh **
2442df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
2443df199a25Sdrh **        use LIMIT.
2444df199a25Sdrh **
2445174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
2446174b6195Sdrh **
24473fc673e6Sdrh **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
24483fc673e6Sdrh **        subquery has no WHERE clause.  (added by ticket #350)
24493fc673e6Sdrh **
2450ac83963aSdrh **  (13)  The subquery and outer query do not both use LIMIT
2451ac83963aSdrh **
2452ac83963aSdrh **  (14)  The subquery does not use OFFSET
2453ac83963aSdrh **
2454ad91c6cdSdrh **  (15)  The outer query is not part of a compound select or the
2455ad91c6cdSdrh **        subquery does not have both an ORDER BY and a LIMIT clause.
2456ad91c6cdSdrh **        (See ticket #2339)
2457ad91c6cdSdrh **
2458c52e355dSdrh **  (16)  The outer query is not an aggregate or the subquery does
2459c52e355dSdrh **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
2460c52e355dSdrh **        until we introduced the group_concat() function.
2461c52e355dSdrh **
2462832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
2463832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
2464832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
2465832508b7Sdrh **
2466665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
2467832508b7Sdrh ** If flattening is attempted this routine returns 1.
2468832508b7Sdrh **
2469832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
2470832508b7Sdrh ** the subquery before this routine runs.
24711350b030Sdrh */
24728c74a8caSdrh static int flattenSubquery(
247317435752Sdrh   sqlite3 *db,         /* Database connection */
24748c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
24758c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
24768c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
24778c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
24788c74a8caSdrh ){
24790bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
2480ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
2481ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
24820bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
24836a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
248491bb0eedSdrh   int i;              /* Loop counter */
248591bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
248691bb0eedSdrh   struct SrcList_item *pSubitem;   /* The subquery */
24871350b030Sdrh 
2488832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
2489832508b7Sdrh   */
2490832508b7Sdrh   if( p==0 ) return 0;
2491832508b7Sdrh   pSrc = p->pSrc;
2492ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
249391bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
249491bb0eedSdrh   pSub = pSubitem->pSelect;
2495832508b7Sdrh   assert( pSub!=0 );
2496ac83963aSdrh   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
2497ac83963aSdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
2498832508b7Sdrh   pSubSrc = pSub->pSrc;
2499832508b7Sdrh   assert( pSubSrc );
2500ac83963aSdrh   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
2501ac83963aSdrh   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
2502ac83963aSdrh   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
2503ac83963aSdrh   ** became arbitrary expressions, we were forced to add restrictions (13)
2504ac83963aSdrh   ** and (14). */
2505ac83963aSdrh   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
2506ac83963aSdrh   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
2507ad91c6cdSdrh   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
2508ad91c6cdSdrh     return 0;                                            /* Restriction (15) */
2509ad91c6cdSdrh   }
2510ac83963aSdrh   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
2511ac83963aSdrh   if( (pSub->isDistinct || pSub->pLimit)
2512ac83963aSdrh          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
2513df199a25Sdrh      return 0;
2514df199a25Sdrh   }
2515ac83963aSdrh   if( p->isDistinct && subqueryIsAgg ) return 0;         /* Restriction (6)  */
2516ac83963aSdrh   if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){
2517ac83963aSdrh      return 0;                                           /* Restriction (11) */
2518ac83963aSdrh   }
2519c52e355dSdrh   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
2520832508b7Sdrh 
25218af4d3acSdrh   /* Restriction 3:  If the subquery is a join, make sure the subquery is
25228af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
25238af4d3acSdrh   ** is not allowed:
25248af4d3acSdrh   **
25258af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
25268af4d3acSdrh   **
25278af4d3acSdrh   ** If we flatten the above, we would get
25288af4d3acSdrh   **
25298af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
25308af4d3acSdrh   **
25318af4d3acSdrh   ** which is not at all the same thing.
25328af4d3acSdrh   */
253361dfc31dSdrh   if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){
25348af4d3acSdrh     return 0;
25358af4d3acSdrh   }
25368af4d3acSdrh 
25373fc673e6Sdrh   /* Restriction 12:  If the subquery is the right operand of a left outer
25383fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
25393fc673e6Sdrh   ** An examples of why this is not allowed:
25403fc673e6Sdrh   **
25413fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
25423fc673e6Sdrh   **
25433fc673e6Sdrh   ** If we flatten the above, we would get
25443fc673e6Sdrh   **
25453fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
25463fc673e6Sdrh   **
25473fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
25483fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
25493fc673e6Sdrh   */
255061dfc31dSdrh   if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){
25513fc673e6Sdrh     return 0;
25523fc673e6Sdrh   }
25533fc673e6Sdrh 
25540bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
255563eb5f29Sdrh   ** iFrom-th entry of the FROM clause in the outer query.
2556832508b7Sdrh   */
2557c31c2eb8Sdrh 
2558c31c2eb8Sdrh   /* Move all of the FROM elements of the subquery into the
2559c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
2560c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
2561c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
2562c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
2563c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
2564c31c2eb8Sdrh   ** elements we are now copying in.
2565c31c2eb8Sdrh   */
256691bb0eedSdrh   iParent = pSubitem->iCursor;
2567c31c2eb8Sdrh   {
2568c31c2eb8Sdrh     int nSubSrc = pSubSrc->nSrc;
256991bb0eedSdrh     int jointype = pSubitem->jointype;
2570c31c2eb8Sdrh 
2571a04a34ffSdanielk1977     sqlite3DeleteTable(pSubitem->pTab);
257217435752Sdrh     sqlite3_free(pSubitem->zDatabase);
257317435752Sdrh     sqlite3_free(pSubitem->zName);
257417435752Sdrh     sqlite3_free(pSubitem->zAlias);
2575cfa063b3Sdrh     pSubitem->pTab = 0;
2576cfa063b3Sdrh     pSubitem->zDatabase = 0;
2577cfa063b3Sdrh     pSubitem->zName = 0;
2578cfa063b3Sdrh     pSubitem->zAlias = 0;
2579c31c2eb8Sdrh     if( nSubSrc>1 ){
2580c31c2eb8Sdrh       int extra = nSubSrc - 1;
2581c31c2eb8Sdrh       for(i=1; i<nSubSrc; i++){
258217435752Sdrh         pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0);
2583cfa063b3Sdrh         if( pSrc==0 ){
2584cfa063b3Sdrh           p->pSrc = 0;
2585cfa063b3Sdrh           return 1;
2586cfa063b3Sdrh         }
2587c31c2eb8Sdrh       }
2588c31c2eb8Sdrh       p->pSrc = pSrc;
2589c31c2eb8Sdrh       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2590c31c2eb8Sdrh         pSrc->a[i] = pSrc->a[i-extra];
2591c31c2eb8Sdrh       }
2592c31c2eb8Sdrh     }
2593c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
2594c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
2595c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2596c31c2eb8Sdrh     }
259761dfc31dSdrh     pSrc->a[iFrom].jointype = jointype;
2598c31c2eb8Sdrh   }
2599c31c2eb8Sdrh 
2600c31c2eb8Sdrh   /* Now begin substituting subquery result set expressions for
2601c31c2eb8Sdrh   ** references to the iParent in the outer query.
2602c31c2eb8Sdrh   **
2603c31c2eb8Sdrh   ** Example:
2604c31c2eb8Sdrh   **
2605c31c2eb8Sdrh   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2606c31c2eb8Sdrh   **   \                     \_____________ subquery __________/          /
2607c31c2eb8Sdrh   **    \_____________________ outer query ______________________________/
2608c31c2eb8Sdrh   **
2609c31c2eb8Sdrh   ** We look at every expression in the outer query and every place we see
2610c31c2eb8Sdrh   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2611c31c2eb8Sdrh   */
2612832508b7Sdrh   pList = p->pEList;
2613832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
26146977fea8Sdrh     Expr *pExpr;
26156977fea8Sdrh     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
261617435752Sdrh       pList->a[i].zName =
261717435752Sdrh              sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
2618832508b7Sdrh     }
2619832508b7Sdrh   }
26201e536953Sdanielk1977   substExprList(db, p->pEList, iParent, pSub->pEList);
26211b2e0329Sdrh   if( isAgg ){
26221e536953Sdanielk1977     substExprList(db, p->pGroupBy, iParent, pSub->pEList);
26231e536953Sdanielk1977     substExpr(db, p->pHaving, iParent, pSub->pEList);
26241b2e0329Sdrh   }
2625174b6195Sdrh   if( pSub->pOrderBy ){
2626174b6195Sdrh     assert( p->pOrderBy==0 );
2627174b6195Sdrh     p->pOrderBy = pSub->pOrderBy;
2628174b6195Sdrh     pSub->pOrderBy = 0;
2629174b6195Sdrh   }else if( p->pOrderBy ){
26301e536953Sdanielk1977     substExprList(db, p->pOrderBy, iParent, pSub->pEList);
2631174b6195Sdrh   }
2632832508b7Sdrh   if( pSub->pWhere ){
263317435752Sdrh     pWhere = sqlite3ExprDup(db, pSub->pWhere);
2634832508b7Sdrh   }else{
2635832508b7Sdrh     pWhere = 0;
2636832508b7Sdrh   }
2637832508b7Sdrh   if( subqueryIsAgg ){
2638832508b7Sdrh     assert( p->pHaving==0 );
26391b2e0329Sdrh     p->pHaving = p->pWhere;
26401b2e0329Sdrh     p->pWhere = pWhere;
26411e536953Sdanielk1977     substExpr(db, p->pHaving, iParent, pSub->pEList);
264217435752Sdrh     p->pHaving = sqlite3ExprAnd(db, p->pHaving,
264317435752Sdrh                                 sqlite3ExprDup(db, pSub->pHaving));
26441b2e0329Sdrh     assert( p->pGroupBy==0 );
264517435752Sdrh     p->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
2646832508b7Sdrh   }else{
26471e536953Sdanielk1977     substExpr(db, p->pWhere, iParent, pSub->pEList);
264817435752Sdrh     p->pWhere = sqlite3ExprAnd(db, p->pWhere, pWhere);
2649832508b7Sdrh   }
2650c31c2eb8Sdrh 
2651c31c2eb8Sdrh   /* The flattened query is distinct if either the inner or the
2652c31c2eb8Sdrh   ** outer query is distinct.
2653c31c2eb8Sdrh   */
2654832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
26558c74a8caSdrh 
2656a58fdfb1Sdanielk1977   /*
2657a58fdfb1Sdanielk1977   ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2658ac83963aSdrh   **
2659ac83963aSdrh   ** One is tempted to try to add a and b to combine the limits.  But this
2660ac83963aSdrh   ** does not work if either limit is negative.
2661a58fdfb1Sdanielk1977   */
2662a2dc3b1aSdanielk1977   if( pSub->pLimit ){
2663a2dc3b1aSdanielk1977     p->pLimit = pSub->pLimit;
2664a2dc3b1aSdanielk1977     pSub->pLimit = 0;
2665df199a25Sdrh   }
26668c74a8caSdrh 
2667c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
2668c31c2eb8Sdrh   ** success.
2669c31c2eb8Sdrh   */
26704adee20fSdanielk1977   sqlite3SelectDelete(pSub);
2671832508b7Sdrh   return 1;
26721350b030Sdrh }
2673b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */
26741350b030Sdrh 
26751350b030Sdrh /*
2676a9d1ccb9Sdanielk1977 ** Analyze the SELECT statement passed as an argument to see if it
2677a9d1ccb9Sdanielk1977 ** is a min() or max() query. Return ORDERBY_MIN or ORDERBY_MAX if
2678a9d1ccb9Sdanielk1977 ** it is, or 0 otherwise. At present, a query is considered to be
2679a9d1ccb9Sdanielk1977 ** a min()/max() query if:
2680a9d1ccb9Sdanielk1977 **
2681738bdcfbSdanielk1977 **   1. There is a single object in the FROM clause.
2682738bdcfbSdanielk1977 **
2683738bdcfbSdanielk1977 **   2. There is a single expression in the result set, and it is
2684738bdcfbSdanielk1977 **      either min(x) or max(x), where x is a column reference.
2685a9d1ccb9Sdanielk1977 */
2686a9d1ccb9Sdanielk1977 static int minMaxQuery(Parse *pParse, Select *p){
2687a9d1ccb9Sdanielk1977   Expr *pExpr;
2688a9d1ccb9Sdanielk1977   ExprList *pEList = p->pEList;
2689a9d1ccb9Sdanielk1977 
2690a9d1ccb9Sdanielk1977   if( pEList->nExpr!=1 ) return ORDERBY_NORMAL;
2691a9d1ccb9Sdanielk1977   pExpr = pEList->a[0].pExpr;
2692a9d1ccb9Sdanielk1977   pEList = pExpr->pList;
2693a9d1ccb9Sdanielk1977   if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0;
2694a9d1ccb9Sdanielk1977   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return ORDERBY_NORMAL;
2695a9d1ccb9Sdanielk1977   if( pExpr->token.n!=3 ) return ORDERBY_NORMAL;
2696a9d1ccb9Sdanielk1977   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
2697a9d1ccb9Sdanielk1977     return ORDERBY_MIN;
2698a9d1ccb9Sdanielk1977   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
2699a9d1ccb9Sdanielk1977     return ORDERBY_MAX;
2700a9d1ccb9Sdanielk1977   }
2701a9d1ccb9Sdanielk1977   return ORDERBY_NORMAL;
2702a9d1ccb9Sdanielk1977 }
2703a9d1ccb9Sdanielk1977 
2704a9d1ccb9Sdanielk1977 /*
2705b3bce662Sdanielk1977 ** This routine resolves any names used in the result set of the
2706b3bce662Sdanielk1977 ** supplied SELECT statement. If the SELECT statement being resolved
2707b3bce662Sdanielk1977 ** is a sub-select, then pOuterNC is a pointer to the NameContext
2708b3bce662Sdanielk1977 ** of the parent SELECT.
2709b3bce662Sdanielk1977 */
2710b3bce662Sdanielk1977 int sqlite3SelectResolve(
2711b3bce662Sdanielk1977   Parse *pParse,         /* The parser context */
2712b3bce662Sdanielk1977   Select *p,             /* The SELECT statement being coded. */
2713b3bce662Sdanielk1977   NameContext *pOuterNC  /* The outer name context. May be NULL. */
2714b3bce662Sdanielk1977 ){
2715b3bce662Sdanielk1977   ExprList *pEList;          /* Result set. */
2716b3bce662Sdanielk1977   int i;                     /* For-loop variable used in multiple places */
2717b3bce662Sdanielk1977   NameContext sNC;           /* Local name-context */
271813449892Sdrh   ExprList *pGroupBy;        /* The group by clause */
2719b3bce662Sdanielk1977 
2720b3bce662Sdanielk1977   /* If this routine has run before, return immediately. */
2721b3bce662Sdanielk1977   if( p->isResolved ){
2722b3bce662Sdanielk1977     assert( !pOuterNC );
2723b3bce662Sdanielk1977     return SQLITE_OK;
2724b3bce662Sdanielk1977   }
2725b3bce662Sdanielk1977   p->isResolved = 1;
2726b3bce662Sdanielk1977 
2727b3bce662Sdanielk1977   /* If there have already been errors, do nothing. */
2728b3bce662Sdanielk1977   if( pParse->nErr>0 ){
2729b3bce662Sdanielk1977     return SQLITE_ERROR;
2730b3bce662Sdanielk1977   }
2731b3bce662Sdanielk1977 
2732b3bce662Sdanielk1977   /* Prepare the select statement. This call will allocate all cursors
2733b3bce662Sdanielk1977   ** required to handle the tables and subqueries in the FROM clause.
2734b3bce662Sdanielk1977   */
2735b3bce662Sdanielk1977   if( prepSelectStmt(pParse, p) ){
2736b3bce662Sdanielk1977     return SQLITE_ERROR;
2737b3bce662Sdanielk1977   }
2738b3bce662Sdanielk1977 
2739a2dc3b1aSdanielk1977   /* Resolve the expressions in the LIMIT and OFFSET clauses. These
2740a2dc3b1aSdanielk1977   ** are not allowed to refer to any names, so pass an empty NameContext.
2741a2dc3b1aSdanielk1977   */
2742ffe07b2dSdrh   memset(&sNC, 0, sizeof(sNC));
2743b3bce662Sdanielk1977   sNC.pParse = pParse;
2744a2dc3b1aSdanielk1977   if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2745a2dc3b1aSdanielk1977       sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2746a2dc3b1aSdanielk1977     return SQLITE_ERROR;
2747a2dc3b1aSdanielk1977   }
2748a2dc3b1aSdanielk1977 
2749a2dc3b1aSdanielk1977   /* Set up the local name-context to pass to ExprResolveNames() to
2750a2dc3b1aSdanielk1977   ** resolve the expression-list.
2751a2dc3b1aSdanielk1977   */
2752a2dc3b1aSdanielk1977   sNC.allowAgg = 1;
2753a2dc3b1aSdanielk1977   sNC.pSrcList = p->pSrc;
2754a2dc3b1aSdanielk1977   sNC.pNext = pOuterNC;
2755b3bce662Sdanielk1977 
2756b3bce662Sdanielk1977   /* Resolve names in the result set. */
2757b3bce662Sdanielk1977   pEList = p->pEList;
2758b3bce662Sdanielk1977   if( !pEList ) return SQLITE_ERROR;
2759b3bce662Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
2760b3bce662Sdanielk1977     Expr *pX = pEList->a[i].pExpr;
2761b3bce662Sdanielk1977     if( sqlite3ExprResolveNames(&sNC, pX) ){
2762b3bce662Sdanielk1977       return SQLITE_ERROR;
2763b3bce662Sdanielk1977     }
2764b3bce662Sdanielk1977   }
2765b3bce662Sdanielk1977 
2766b3bce662Sdanielk1977   /* If there are no aggregate functions in the result-set, and no GROUP BY
2767b3bce662Sdanielk1977   ** expression, do not allow aggregates in any of the other expressions.
2768b3bce662Sdanielk1977   */
2769b3bce662Sdanielk1977   assert( !p->isAgg );
277013449892Sdrh   pGroupBy = p->pGroupBy;
277113449892Sdrh   if( pGroupBy || sNC.hasAgg ){
2772b3bce662Sdanielk1977     p->isAgg = 1;
2773b3bce662Sdanielk1977   }else{
2774b3bce662Sdanielk1977     sNC.allowAgg = 0;
2775b3bce662Sdanielk1977   }
2776b3bce662Sdanielk1977 
2777b3bce662Sdanielk1977   /* If a HAVING clause is present, then there must be a GROUP BY clause.
2778b3bce662Sdanielk1977   */
277913449892Sdrh   if( p->pHaving && !pGroupBy ){
2780b3bce662Sdanielk1977     sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2781b3bce662Sdanielk1977     return SQLITE_ERROR;
2782b3bce662Sdanielk1977   }
2783b3bce662Sdanielk1977 
2784b3bce662Sdanielk1977   /* Add the expression list to the name-context before parsing the
2785b3bce662Sdanielk1977   ** other expressions in the SELECT statement. This is so that
2786b3bce662Sdanielk1977   ** expressions in the WHERE clause (etc.) can refer to expressions by
2787b3bce662Sdanielk1977   ** aliases in the result set.
2788b3bce662Sdanielk1977   **
2789b3bce662Sdanielk1977   ** Minor point: If this is the case, then the expression will be
2790b3bce662Sdanielk1977   ** re-evaluated for each reference to it.
2791b3bce662Sdanielk1977   */
2792b3bce662Sdanielk1977   sNC.pEList = p->pEList;
2793b3bce662Sdanielk1977   if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2794994c80afSdrh      sqlite3ExprResolveNames(&sNC, p->pHaving) ){
2795b3bce662Sdanielk1977     return SQLITE_ERROR;
2796b3bce662Sdanielk1977   }
27979a99334dSdrh   if( p->pPrior==0 ){
279801874bfcSdanielk1977     if( processOrderGroupBy(pParse, p, p->pOrderBy, 1, &sNC.hasAgg) ){
2799994c80afSdrh       return SQLITE_ERROR;
2800994c80afSdrh     }
28019a99334dSdrh   }
28029a99334dSdrh   if( processOrderGroupBy(pParse, p, pGroupBy, 0, &sNC.hasAgg) ){
28034c774314Sdrh     return SQLITE_ERROR;
2804994c80afSdrh   }
2805b3bce662Sdanielk1977 
28061e536953Sdanielk1977   if( pParse->db->mallocFailed ){
28079afe689eSdanielk1977     return SQLITE_NOMEM;
28089afe689eSdanielk1977   }
28099afe689eSdanielk1977 
281013449892Sdrh   /* Make sure the GROUP BY clause does not contain aggregate functions.
281113449892Sdrh   */
281213449892Sdrh   if( pGroupBy ){
281313449892Sdrh     struct ExprList_item *pItem;
281413449892Sdrh 
281513449892Sdrh     for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
281613449892Sdrh       if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
281713449892Sdrh         sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
281813449892Sdrh             "the GROUP BY clause");
281913449892Sdrh         return SQLITE_ERROR;
282013449892Sdrh       }
282113449892Sdrh     }
282213449892Sdrh   }
282313449892Sdrh 
2824f6bbe022Sdrh   /* If this is one SELECT of a compound, be sure to resolve names
2825f6bbe022Sdrh   ** in the other SELECTs.
2826f6bbe022Sdrh   */
2827f6bbe022Sdrh   if( p->pPrior ){
2828f6bbe022Sdrh     return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC);
2829f6bbe022Sdrh   }else{
2830b3bce662Sdanielk1977     return SQLITE_OK;
2831b3bce662Sdanielk1977   }
2832f6bbe022Sdrh }
2833b3bce662Sdanielk1977 
2834b3bce662Sdanielk1977 /*
283513449892Sdrh ** Reset the aggregate accumulator.
283613449892Sdrh **
283713449892Sdrh ** The aggregate accumulator is a set of memory cells that hold
283813449892Sdrh ** intermediate results while calculating an aggregate.  This
283913449892Sdrh ** routine simply stores NULLs in all of those memory cells.
2840b3bce662Sdanielk1977 */
284113449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
284213449892Sdrh   Vdbe *v = pParse->pVdbe;
284313449892Sdrh   int i;
2844c99130fdSdrh   struct AggInfo_func *pFunc;
284513449892Sdrh   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
284613449892Sdrh     return;
284713449892Sdrh   }
284813449892Sdrh   for(i=0; i<pAggInfo->nColumn; i++){
28494c583128Sdrh     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
285013449892Sdrh   }
2851c99130fdSdrh   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
28524c583128Sdrh     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
2853c99130fdSdrh     if( pFunc->iDistinct>=0 ){
2854c99130fdSdrh       Expr *pE = pFunc->pExpr;
2855c99130fdSdrh       if( pE->pList==0 || pE->pList->nExpr!=1 ){
2856c99130fdSdrh         sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
2857c99130fdSdrh            "by an expression");
2858c99130fdSdrh         pFunc->iDistinct = -1;
2859c99130fdSdrh       }else{
2860c99130fdSdrh         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
286166a5167bSdrh         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
286266a5167bSdrh                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
2863c99130fdSdrh       }
2864c99130fdSdrh     }
286513449892Sdrh   }
2866b3bce662Sdanielk1977 }
2867b3bce662Sdanielk1977 
2868b3bce662Sdanielk1977 /*
286913449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function
287013449892Sdrh ** in the AggInfo structure.
2871b3bce662Sdanielk1977 */
287213449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
287313449892Sdrh   Vdbe *v = pParse->pVdbe;
287413449892Sdrh   int i;
287513449892Sdrh   struct AggInfo_func *pF;
287613449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
2877a10a34b8Sdrh     ExprList *pList = pF->pExpr->pList;
287866a5167bSdrh     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
287966a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
2880b3bce662Sdanielk1977   }
288113449892Sdrh }
288213449892Sdrh 
288313449892Sdrh /*
288413449892Sdrh ** Update the accumulator memory cells for an aggregate based on
288513449892Sdrh ** the current cursor position.
288613449892Sdrh */
288713449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
288813449892Sdrh   Vdbe *v = pParse->pVdbe;
288913449892Sdrh   int i;
289013449892Sdrh   struct AggInfo_func *pF;
289113449892Sdrh   struct AggInfo_col *pC;
289213449892Sdrh 
289313449892Sdrh   pAggInfo->directMode = 1;
289413449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
289513449892Sdrh     int nArg;
2896c99130fdSdrh     int addrNext = 0;
289798757157Sdrh     int regAgg;
289813449892Sdrh     ExprList *pList = pF->pExpr->pList;
289913449892Sdrh     if( pList ){
290013449892Sdrh       nArg = pList->nExpr;
2901892d3179Sdrh       regAgg = sqlite3GetTempRange(pParse, nArg);
2902892d3179Sdrh       sqlite3ExprCodeExprList(pParse, pList, regAgg);
290313449892Sdrh     }else{
290413449892Sdrh       nArg = 0;
290598757157Sdrh       regAgg = 0;
290613449892Sdrh     }
2907c99130fdSdrh     if( pF->iDistinct>=0 ){
2908c99130fdSdrh       addrNext = sqlite3VdbeMakeLabel(v);
2909c99130fdSdrh       assert( nArg==1 );
29102dcef11bSdrh       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
2911c99130fdSdrh     }
291213449892Sdrh     if( pF->pFunc->needCollSeq ){
291313449892Sdrh       CollSeq *pColl = 0;
291413449892Sdrh       struct ExprList_item *pItem;
291513449892Sdrh       int j;
291643617e9aSdrh       assert( pList!=0 );  /* pList!=0 if pF->pFunc->needCollSeq is true */
291743617e9aSdrh       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
291813449892Sdrh         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
291913449892Sdrh       }
292013449892Sdrh       if( !pColl ){
292113449892Sdrh         pColl = pParse->db->pDfltColl;
292213449892Sdrh       }
292366a5167bSdrh       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
292413449892Sdrh     }
292598757157Sdrh     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
292666a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
292798757157Sdrh     sqlite3VdbeChangeP5(v, nArg);
2928892d3179Sdrh     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
2929c99130fdSdrh     if( addrNext ){
2930c99130fdSdrh       sqlite3VdbeResolveLabel(v, addrNext);
2931c99130fdSdrh     }
293213449892Sdrh   }
293313449892Sdrh   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
2934389a1adbSdrh     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
293513449892Sdrh   }
293613449892Sdrh   pAggInfo->directMode = 0;
293713449892Sdrh }
293813449892Sdrh 
29398f2c54e6Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
29408f2c54e6Sdanielk1977 /*
29418f2c54e6Sdanielk1977 ** This function is used when a SELECT statement is used to create a
29428f2c54e6Sdanielk1977 ** temporary table for iterating through when running an INSTEAD OF
29438f2c54e6Sdanielk1977 ** UPDATE or INSTEAD OF DELETE trigger.
29448f2c54e6Sdanielk1977 **
29458f2c54e6Sdanielk1977 ** If possible, the SELECT statement is modified so that NULL values
29468f2c54e6Sdanielk1977 ** are stored in the temporary table for all columns for which the
29478f2c54e6Sdanielk1977 ** corresponding bit in argument mask is not set. If mask takes the
29488f2c54e6Sdanielk1977 ** special value 0xffffffff, then all columns are populated.
29498f2c54e6Sdanielk1977 */
2950d2b3e23bSdrh void sqlite3SelectMask(Parse *pParse, Select *p, u32 mask){
2951cdf3020cSdanielk1977   if( p && !p->pPrior && !p->isDistinct && mask!=0xffffffff ){
29528f2c54e6Sdanielk1977     ExprList *pEList;
29538f2c54e6Sdanielk1977     int i;
2954d2b3e23bSdrh     sqlite3SelectResolve(pParse, p, 0);
29558f2c54e6Sdanielk1977     pEList = p->pEList;
2956cdf3020cSdanielk1977     for(i=0; pEList && i<pEList->nExpr && i<32; i++){
29578f2c54e6Sdanielk1977       if( !(mask&((u32)1<<i)) ){
29588f2c54e6Sdanielk1977         sqlite3ExprDelete(pEList->a[i].pExpr);
29598f2c54e6Sdanielk1977         pEList->a[i].pExpr = sqlite3Expr(pParse->db, TK_NULL, 0, 0, 0);
29608f2c54e6Sdanielk1977       }
29618f2c54e6Sdanielk1977     }
29628f2c54e6Sdanielk1977   }
29638f2c54e6Sdanielk1977 }
29648f2c54e6Sdanielk1977 #endif
2965b3bce662Sdanielk1977 
2966b3bce662Sdanielk1977 /*
29679bb61fe7Sdrh ** Generate code for the given SELECT statement.
29689bb61fe7Sdrh **
2969fef5208cSdrh ** The results are distributed in various ways depending on the
29706c8c8ce0Sdanielk1977 ** contents of the SelectDest structure pointed to by argument pDest
29716c8c8ce0Sdanielk1977 ** as follows:
2972fef5208cSdrh **
29736c8c8ce0Sdanielk1977 **     pDest->eDest    Result
2974fef5208cSdrh **     ------------    -------------------------------------------
2975fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
2976fef5208cSdrh **
29776c8c8ce0Sdanielk1977 **     SRT_Mem         Store first result in memory cell pDest->iParm
2978fef5208cSdrh **
29796c8c8ce0Sdanielk1977 **     SRT_Set         Store non-null results as keys of table pDest->iParm.
29806c8c8ce0Sdanielk1977 **                     Apply the affinity pDest->affinity before storing them.
2981fef5208cSdrh **
29826c8c8ce0Sdanielk1977 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
298382c3d636Sdrh **
29846c8c8ce0Sdanielk1977 **     SRT_Except      Remove results from the temporary table pDest->iParm.
2985c4a3c779Sdrh **
29866c8c8ce0Sdanielk1977 **     SRT_Table       Store results in temporary table pDest->iParm
29879bb61fe7Sdrh **
29886c8c8ce0Sdanielk1977 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
29896c8c8ce0Sdanielk1977 **                     the result there. The cursor is left open after
29906c8c8ce0Sdanielk1977 **                     returning.
29916c8c8ce0Sdanielk1977 **
29926c8c8ce0Sdanielk1977 **     SRT_Subroutine  For each row returned, push the results onto the
29936c8c8ce0Sdanielk1977 **                     vdbe stack and call the subroutine (via OP_Gosub)
29946c8c8ce0Sdanielk1977 **                     at address pDest->iParm.
29956c8c8ce0Sdanielk1977 **
29966c8c8ce0Sdanielk1977 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
29976c8c8ce0Sdanielk1977 **                     set is not empty.
29986c8c8ce0Sdanielk1977 **
29996c8c8ce0Sdanielk1977 **     SRT_Discard     Throw the results away.
30006c8c8ce0Sdanielk1977 **
30016c8c8ce0Sdanielk1977 ** See the selectInnerLoop() function for a canonical listing of the
30026c8c8ce0Sdanielk1977 ** allowed values of eDest and their meanings.
3003e78e8284Sdrh **
30049bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
30059bb61fe7Sdrh ** encountered, then an appropriate error message is left in
30069bb61fe7Sdrh ** pParse->zErrMsg.
30079bb61fe7Sdrh **
30089bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
30099bb61fe7Sdrh ** calling function needs to do that.
30101b2e0329Sdrh **
30111b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
30121b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
30131b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
30141b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
30151b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
30161b2e0329Sdrh ** can be changed.
3017e78e8284Sdrh **
3018e78e8284Sdrh ** Example 1:   The meaning of the pParent parameter.
3019e78e8284Sdrh **
3020e78e8284Sdrh **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
3021e78e8284Sdrh **    \                      \_______ subquery _______/        /
3022e78e8284Sdrh **     \                                                      /
3023e78e8284Sdrh **      \____________________ outer query ___________________/
3024e78e8284Sdrh **
3025e78e8284Sdrh ** This routine is called for the outer query first.   For that call,
3026e78e8284Sdrh ** pParent will be NULL.  During the processing of the outer query, this
3027e78e8284Sdrh ** routine is called recursively to handle the subquery.  For the recursive
3028e78e8284Sdrh ** call, pParent will point to the outer query.  Because the subquery is
3029e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will
3030e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.)
30319bb61fe7Sdrh */
30324adee20fSdanielk1977 int sqlite3Select(
3033cce7d176Sdrh   Parse *pParse,         /* The parser context */
30349bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
30356c8c8ce0Sdanielk1977   SelectDest *pDest,     /* What to do with the query results */
3036832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
3037832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
303884ac9d02Sdanielk1977   int *pParentAgg,       /* True if pParent uses aggregate functions */
3039b3bce662Sdanielk1977   char *aff              /* If eDest is SRT_Union, the affinity string */
3040cce7d176Sdrh ){
304113449892Sdrh   int i, j;              /* Loop counters */
304213449892Sdrh   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
304313449892Sdrh   Vdbe *v;               /* The virtual machine under construction */
3044b3bce662Sdanielk1977   int isAgg;             /* True for select lists like "count(*)" */
3045a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
3046ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
30479bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
30489bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
30492282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
30502282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
305119a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
305219a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
30531d83f052Sdrh   int rc = 1;            /* Value to return from this function */
3054b9bb7c18Sdrh   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
305513449892Sdrh   AggInfo sAggInfo;      /* Information used by aggregate queries */
3056ec7429aeSdrh   int iEnd;              /* Address of the end of the query */
305717435752Sdrh   sqlite3 *db;           /* The database connection */
30589bb61fe7Sdrh 
305917435752Sdrh   db = pParse->db;
306017435752Sdrh   if( p==0 || db->mallocFailed || pParse->nErr ){
30616f7adc8aSdrh     return 1;
30626f7adc8aSdrh   }
30634adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
306413449892Sdrh   memset(&sAggInfo, 0, sizeof(sAggInfo));
3065daffd0e5Sdrh 
30669a99334dSdrh   pOrderBy = p->pOrderBy;
30676c8c8ce0Sdanielk1977   if( IgnorableOrderby(pDest) ){
30689a99334dSdrh     p->pOrderBy = 0;
30699ed1dfa8Sdanielk1977 
30709ed1dfa8Sdanielk1977     /* In these cases the DISTINCT operator makes no difference to the
30719ed1dfa8Sdanielk1977     ** results, so remove it if it were specified.
30729ed1dfa8Sdanielk1977     */
30739ed1dfa8Sdanielk1977     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
30749ed1dfa8Sdanielk1977            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
30759ed1dfa8Sdanielk1977     p->isDistinct = 0;
30769a99334dSdrh   }
30779a99334dSdrh   if( sqlite3SelectResolve(pParse, p, 0) ){
30789a99334dSdrh     goto select_end;
30799a99334dSdrh   }
30809a99334dSdrh   p->pOrderBy = pOrderBy;
30819a99334dSdrh 
3082b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
308382c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
308482c3d636Sdrh   */
308582c3d636Sdrh   if( p->pPrior ){
30860342b1f5Sdrh     if( p->pRightmost==0 ){
30871e281291Sdrh       Select *pLoop, *pRight = 0;
30880325d873Sdrh       int cnt = 0;
3089bb4957f8Sdrh       int mxSelect;
30900325d873Sdrh       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
30910342b1f5Sdrh         pLoop->pRightmost = p;
30921e281291Sdrh         pLoop->pNext = pRight;
30931e281291Sdrh         pRight = pLoop;
30940342b1f5Sdrh       }
3095bb4957f8Sdrh       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
3096bb4957f8Sdrh       if( mxSelect && cnt>mxSelect ){
30970325d873Sdrh         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
30980325d873Sdrh         return 1;
30990325d873Sdrh       }
31000342b1f5Sdrh     }
31016c8c8ce0Sdanielk1977     return multiSelect(pParse, p, pDest, aff);
310282c3d636Sdrh   }
3103b7f9164eSdrh #endif
310482c3d636Sdrh 
310582c3d636Sdrh   /* Make local copies of the parameters for this query.
310682c3d636Sdrh   */
31079bb61fe7Sdrh   pTabList = p->pSrc;
31089bb61fe7Sdrh   pWhere = p->pWhere;
31092282792aSdrh   pGroupBy = p->pGroupBy;
31102282792aSdrh   pHaving = p->pHaving;
3111b3bce662Sdanielk1977   isAgg = p->isAgg;
311219a775c2Sdrh   isDistinct = p->isDistinct;
3113b3bce662Sdanielk1977   pEList = p->pEList;
3114b3bce662Sdanielk1977   if( pEList==0 ) goto select_end;
31159bb61fe7Sdrh 
31169bb61fe7Sdrh   /*
31179bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
31189bb61fe7Sdrh   ** errors before this routine starts.
31199bb61fe7Sdrh   */
31201d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
3121cce7d176Sdrh 
31222282792aSdrh   /* If writing to memory or generating a set
31232282792aSdrh   ** only a single column may be output.
312419a775c2Sdrh   */
312593758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
31266c8c8ce0Sdanielk1977   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
31271d83f052Sdrh     goto select_end;
312819a775c2Sdrh   }
312993758c8dSdanielk1977 #endif
313019a775c2Sdrh 
3131c926afbcSdrh   /* ORDER BY is ignored for some destinations.
31322282792aSdrh   */
31336c8c8ce0Sdanielk1977   if( IgnorableOrderby(pDest) ){
3134acd4c695Sdrh     pOrderBy = 0;
31352282792aSdrh   }
31362282792aSdrh 
3137d820cb1bSdrh   /* Begin generating code.
3138d820cb1bSdrh   */
31394adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
3140d820cb1bSdrh   if( v==0 ) goto select_end;
3141d820cb1bSdrh 
3142d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
3143d820cb1bSdrh   */
314451522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3145ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
3146742f947bSdanielk1977     const char *zSavedAuthContext = 0;
3147c31c2eb8Sdrh     int needRestoreContext;
314813449892Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
31491013c932Sdrh     SelectDest dest;
3150c31c2eb8Sdrh 
31511787ccabSdanielk1977     if( pItem->pSelect==0 || pItem->isPopulated ) continue;
315213449892Sdrh     if( pItem->zName!=0 ){
31535cf590c1Sdrh       zSavedAuthContext = pParse->zAuthContext;
315413449892Sdrh       pParse->zAuthContext = pItem->zName;
3155c31c2eb8Sdrh       needRestoreContext = 1;
3156c31c2eb8Sdrh     }else{
3157c31c2eb8Sdrh       needRestoreContext = 0;
31585cf590c1Sdrh     }
3159fc976065Sdanielk1977     /* Increment Parse.nHeight by the height of the largest expression
3160fc976065Sdanielk1977     ** tree refered to by this, the parent select. The child select
3161fc976065Sdanielk1977     ** may contain expression trees of at most
3162fc976065Sdanielk1977     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
3163fc976065Sdanielk1977     ** more conservative than necessary, but much easier than enforcing
3164fc976065Sdanielk1977     ** an exact limit.
3165fc976065Sdanielk1977     */
3166fc976065Sdanielk1977     pParse->nHeight += sqlite3SelectExprHeight(p);
31671013c932Sdrh     sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
31686c8c8ce0Sdanielk1977     sqlite3Select(pParse, pItem->pSelect, &dest, p, i, &isAgg, 0);
3169cfa063b3Sdrh     if( db->mallocFailed ){
3170cfa063b3Sdrh       goto select_end;
3171cfa063b3Sdrh     }
3172fc976065Sdanielk1977     pParse->nHeight -= sqlite3SelectExprHeight(p);
3173c31c2eb8Sdrh     if( needRestoreContext ){
31745cf590c1Sdrh       pParse->zAuthContext = zSavedAuthContext;
31755cf590c1Sdrh     }
3176832508b7Sdrh     pTabList = p->pSrc;
3177832508b7Sdrh     pWhere = p->pWhere;
31786c8c8ce0Sdanielk1977     if( !IgnorableOrderby(pDest) ){
3179832508b7Sdrh       pOrderBy = p->pOrderBy;
3180acd4c695Sdrh     }
3181832508b7Sdrh     pGroupBy = p->pGroupBy;
3182832508b7Sdrh     pHaving = p->pHaving;
3183832508b7Sdrh     isDistinct = p->isDistinct;
31841b2e0329Sdrh   }
318551522cd3Sdrh #endif
31861b2e0329Sdrh 
31871b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
31881b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
31891b2e0329Sdrh   */
3190b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
31911b2e0329Sdrh   if( pParent && pParentAgg &&
319217435752Sdrh       flattenSubquery(db, pParent, parentTab, *pParentAgg, isAgg) ){
31931b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
3194b3bce662Sdanielk1977     goto select_end;
31951b2e0329Sdrh   }
3196b7f9164eSdrh #endif
3197832508b7Sdrh 
31980318d441Sdanielk1977   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
31990318d441Sdanielk1977   ** GROUP BY may use an index, DISTINCT never does.
32003c4809a2Sdanielk1977   */
32013c4809a2Sdanielk1977   if( p->isDistinct && !p->isAgg && !p->pGroupBy ){
32023c4809a2Sdanielk1977     p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
32033c4809a2Sdanielk1977     pGroupBy = p->pGroupBy;
32043c4809a2Sdanielk1977     p->isDistinct = 0;
32053c4809a2Sdanielk1977     isDistinct = 0;
32063c4809a2Sdanielk1977   }
32073c4809a2Sdanielk1977 
32088b4c40d8Sdrh   /* If there is an ORDER BY clause, then this sorting
32098b4c40d8Sdrh   ** index might end up being unused if the data can be
32109d2985c7Sdrh   ** extracted in pre-sorted order.  If that is the case, then the
3211b9bb7c18Sdrh   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
32129d2985c7Sdrh   ** we figure out that the sorting index is not needed.  The addrSortIndex
32139d2985c7Sdrh   ** variable is used to facilitate that change.
32147cedc8d4Sdanielk1977   */
32157cedc8d4Sdanielk1977   if( pOrderBy ){
32160342b1f5Sdrh     KeyInfo *pKeyInfo;
32170342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
32189d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
3219b9bb7c18Sdrh     p->addrOpenEphm[2] = addrSortIndex =
322066a5167bSdrh       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
322166a5167bSdrh                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
322266a5167bSdrh                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
32239d2985c7Sdrh   }else{
32249d2985c7Sdrh     addrSortIndex = -1;
32257cedc8d4Sdanielk1977   }
32267cedc8d4Sdanielk1977 
32272d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
32282d0794e3Sdrh   */
32296c8c8ce0Sdanielk1977   if( pDest->eDest==SRT_EphemTab ){
323066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
32312d0794e3Sdrh   }
32322d0794e3Sdrh 
3233f42bacc2Sdrh   /* Set the limiter.
3234f42bacc2Sdrh   */
3235f42bacc2Sdrh   iEnd = sqlite3VdbeMakeLabel(v);
3236f42bacc2Sdrh   computeLimitRegisters(pParse, p, iEnd);
3237f42bacc2Sdrh 
3238dece1a84Sdrh   /* Open a virtual index to use for the distinct set.
3239cce7d176Sdrh   */
324019a775c2Sdrh   if( isDistinct ){
32410342b1f5Sdrh     KeyInfo *pKeyInfo;
32423c4809a2Sdanielk1977     assert( isAgg || pGroupBy );
3243832508b7Sdrh     distinct = pParse->nTab++;
32440342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
324566a5167bSdrh     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
324666a5167bSdrh                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
3247832508b7Sdrh   }else{
3248832508b7Sdrh     distinct = -1;
3249efb7251dSdrh   }
3250832508b7Sdrh 
325113449892Sdrh   /* Aggregate and non-aggregate queries are handled differently */
325213449892Sdrh   if( !isAgg && pGroupBy==0 ){
325313449892Sdrh     /* This case is for non-aggregate queries
325413449892Sdrh     ** Begin the database scan
3255832508b7Sdrh     */
3256a9d1ccb9Sdanielk1977     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
32571d83f052Sdrh     if( pWInfo==0 ) goto select_end;
3258cce7d176Sdrh 
3259b9bb7c18Sdrh     /* If sorting index that was created by a prior OP_OpenEphemeral
3260b9bb7c18Sdrh     ** instruction ended up not being needed, then change the OP_OpenEphemeral
32619d2985c7Sdrh     ** into an OP_Noop.
32629d2985c7Sdrh     */
32639d2985c7Sdrh     if( addrSortIndex>=0 && pOrderBy==0 ){
3264f8875400Sdrh       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
3265b9bb7c18Sdrh       p->addrOpenEphm[2] = -1;
32669d2985c7Sdrh     }
32679d2985c7Sdrh 
326813449892Sdrh     /* Use the standard inner loop
3269cce7d176Sdrh     */
32703c4809a2Sdanielk1977     assert(!isDistinct);
3271d2b3e23bSdrh     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
3272d2b3e23bSdrh                     pWInfo->iContinue, pWInfo->iBreak, aff);
32732282792aSdrh 
3274cce7d176Sdrh     /* End the database scan loop.
3275cce7d176Sdrh     */
32764adee20fSdanielk1977     sqlite3WhereEnd(pWInfo);
327713449892Sdrh   }else{
327813449892Sdrh     /* This is the processing for aggregate queries */
327913449892Sdrh     NameContext sNC;    /* Name context for processing aggregate information */
328013449892Sdrh     int iAMem;          /* First Mem address for storing current GROUP BY */
328113449892Sdrh     int iBMem;          /* First Mem address for previous GROUP BY */
328213449892Sdrh     int iUseFlag;       /* Mem address holding flag indicating that at least
328313449892Sdrh                         ** one row of the input to the aggregator has been
328413449892Sdrh                         ** processed */
328513449892Sdrh     int iAbortFlag;     /* Mem address which causes query abort if positive */
328613449892Sdrh     int groupBySort;    /* Rows come from source in GROUP BY order */
3287cce7d176Sdrh 
328813449892Sdrh 
328913449892Sdrh     /* The following variables hold addresses or labels for parts of the
329013449892Sdrh     ** virtual machine program we are putting together */
329113449892Sdrh     int addrOutputRow;      /* Start of subroutine that outputs a result row */
329213449892Sdrh     int addrSetAbort;       /* Set the abort flag and return */
329313449892Sdrh     int addrInitializeLoop; /* Start of code that initializes the input loop */
329413449892Sdrh     int addrTopOfLoop;      /* Top of the input loop */
329513449892Sdrh     int addrGroupByChange;  /* Code that runs when any GROUP BY term changes */
329613449892Sdrh     int addrProcessRow;     /* Code to process a single input row */
329713449892Sdrh     int addrEnd;            /* End of all processing */
3298b9bb7c18Sdrh     int addrSortingIdx;     /* The OP_OpenEphemeral for the sorting index */
3299e313382eSdrh     int addrReset;          /* Subroutine for resetting the accumulator */
330013449892Sdrh 
330113449892Sdrh     addrEnd = sqlite3VdbeMakeLabel(v);
330213449892Sdrh 
330313449892Sdrh     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
330413449892Sdrh     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
330513449892Sdrh     ** SELECT statement.
33062282792aSdrh     */
330713449892Sdrh     memset(&sNC, 0, sizeof(sNC));
330813449892Sdrh     sNC.pParse = pParse;
330913449892Sdrh     sNC.pSrcList = pTabList;
331013449892Sdrh     sNC.pAggInfo = &sAggInfo;
331113449892Sdrh     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
33129d2985c7Sdrh     sAggInfo.pGroupBy = pGroupBy;
3313d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pEList);
3314d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
3315d2b3e23bSdrh     if( pHaving ){
3316d2b3e23bSdrh       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
331713449892Sdrh     }
331813449892Sdrh     sAggInfo.nAccumulator = sAggInfo.nColumn;
331913449892Sdrh     for(i=0; i<sAggInfo.nFunc; i++){
3320d2b3e23bSdrh       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList);
332113449892Sdrh     }
332217435752Sdrh     if( db->mallocFailed ) goto select_end;
332313449892Sdrh 
332413449892Sdrh     /* Processing for aggregates with GROUP BY is very different and
33253c4809a2Sdanielk1977     ** much more complex than aggregates without a GROUP BY.
332613449892Sdrh     */
332713449892Sdrh     if( pGroupBy ){
332813449892Sdrh       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
332913449892Sdrh 
333013449892Sdrh       /* Create labels that we will be needing
333113449892Sdrh       */
333213449892Sdrh 
333313449892Sdrh       addrInitializeLoop = sqlite3VdbeMakeLabel(v);
333413449892Sdrh       addrGroupByChange = sqlite3VdbeMakeLabel(v);
333513449892Sdrh       addrProcessRow = sqlite3VdbeMakeLabel(v);
333613449892Sdrh 
333713449892Sdrh       /* If there is a GROUP BY clause we might need a sorting index to
333813449892Sdrh       ** implement it.  Allocate that sorting index now.  If it turns out
3339b9bb7c18Sdrh       ** that we do not need it after all, the OpenEphemeral instruction
334013449892Sdrh       ** will be converted into a Noop.
334113449892Sdrh       */
334213449892Sdrh       sAggInfo.sortingIdx = pParse->nTab++;
334313449892Sdrh       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
3344cd3e8f7cSdanielk1977       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
3345cd3e8f7cSdanielk1977           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
3346cd3e8f7cSdanielk1977           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
334713449892Sdrh 
334813449892Sdrh       /* Initialize memory locations used by GROUP BY aggregate processing
334913449892Sdrh       */
33500a07c107Sdrh       iUseFlag = ++pParse->nMem;
33510a07c107Sdrh       iAbortFlag = ++pParse->nMem;
33520a07c107Sdrh       iAMem = pParse->nMem + 1;
335313449892Sdrh       pParse->nMem += pGroupBy->nExpr;
33540a07c107Sdrh       iBMem = pParse->nMem + 1;
335513449892Sdrh       pParse->nMem += pGroupBy->nExpr;
33564c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
3357d4e70ebdSdrh       VdbeComment((v, "clear abort flag"));
33584c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
3359d4e70ebdSdrh       VdbeComment((v, "indicate accumulator empty"));
336066a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrInitializeLoop);
336113449892Sdrh 
336213449892Sdrh       /* Generate a subroutine that outputs a single row of the result
336313449892Sdrh       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
336413449892Sdrh       ** is less than or equal to zero, the subroutine is a no-op.  If
336513449892Sdrh       ** the processing calls for the query to abort, this subroutine
336613449892Sdrh       ** increments the iAbortFlag memory location before returning in
336713449892Sdrh       ** order to signal the caller to abort.
336813449892Sdrh       */
336913449892Sdrh       addrSetAbort = sqlite3VdbeCurrentAddr(v);
33704c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
3371d4e70ebdSdrh       VdbeComment((v, "set abort flag"));
337266a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
337313449892Sdrh       addrOutputRow = sqlite3VdbeCurrentAddr(v);
33743c84ddffSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
3375d4e70ebdSdrh       VdbeComment((v, "Groupby result generator entry point"));
337666a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
337713449892Sdrh       finalizeAggFunctions(pParse, &sAggInfo);
337813449892Sdrh       if( pHaving ){
337935573356Sdrh         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
338013449892Sdrh       }
3381d2b3e23bSdrh       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
33826c8c8ce0Sdanielk1977                       distinct, pDest,
338313449892Sdrh                       addrOutputRow+1, addrSetAbort, aff);
338466a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
3385d4e70ebdSdrh       VdbeComment((v, "end groupby result generator"));
338613449892Sdrh 
3387e313382eSdrh       /* Generate a subroutine that will reset the group-by accumulator
3388e313382eSdrh       */
3389e313382eSdrh       addrReset = sqlite3VdbeCurrentAddr(v);
3390e313382eSdrh       resetAccumulator(pParse, &sAggInfo);
339166a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
3392e313382eSdrh 
339313449892Sdrh       /* Begin a loop that will extract all source rows in GROUP BY order.
339413449892Sdrh       ** This might involve two separate loops with an OP_Sort in between, or
339513449892Sdrh       ** it might be a single loop that uses an index to extract information
339613449892Sdrh       ** in the right order to begin with.
339713449892Sdrh       */
339813449892Sdrh       sqlite3VdbeResolveLabel(v, addrInitializeLoop);
339966a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset);
3400a9d1ccb9Sdanielk1977       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
34015360ad34Sdrh       if( pWInfo==0 ) goto select_end;
340213449892Sdrh       if( pGroupBy==0 ){
340313449892Sdrh         /* The optimizer is able to deliver rows in group by order so
3404b9bb7c18Sdrh         ** we do not have to sort.  The OP_OpenEphemeral table will be
340513449892Sdrh         ** cancelled later because we still need to use the pKeyInfo
340613449892Sdrh         */
340713449892Sdrh         pGroupBy = p->pGroupBy;
340813449892Sdrh         groupBySort = 0;
340913449892Sdrh       }else{
341013449892Sdrh         /* Rows are coming out in undetermined order.  We have to push
341113449892Sdrh         ** each row into a sorting index, terminate the first loop,
341213449892Sdrh         ** then loop over the sorting index in order to get the output
341313449892Sdrh         ** in sorted order
341413449892Sdrh         */
3415892d3179Sdrh         int regBase;
3416892d3179Sdrh         int regRecord;
3417892d3179Sdrh         int nCol;
3418892d3179Sdrh         int nGroupBy;
3419892d3179Sdrh 
342013449892Sdrh         groupBySort = 1;
3421892d3179Sdrh         nGroupBy = pGroupBy->nExpr;
3422892d3179Sdrh         nCol = nGroupBy + 1;
3423892d3179Sdrh         j = nGroupBy+1;
342413449892Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
3425892d3179Sdrh           if( sAggInfo.aCol[i].iSorterColumn>=j ){
3426892d3179Sdrh             nCol++;
342713449892Sdrh             j++;
342813449892Sdrh           }
3429892d3179Sdrh         }
3430892d3179Sdrh         regBase = sqlite3GetTempRange(pParse, nCol);
3431892d3179Sdrh         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase);
3432892d3179Sdrh         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
3433892d3179Sdrh         j = nGroupBy+1;
3434892d3179Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
3435892d3179Sdrh           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
3436892d3179Sdrh           if( pCol->iSorterColumn>=j ){
3437892d3179Sdrh             sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn, pCol->iTable,
3438892d3179Sdrh                                      j + regBase);
3439892d3179Sdrh             j++;
3440892d3179Sdrh           }
3441892d3179Sdrh         }
3442892d3179Sdrh         regRecord = sqlite3GetTempReg(pParse);
34431db639ceSdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
3444892d3179Sdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
3445892d3179Sdrh         sqlite3ReleaseTempReg(pParse, regRecord);
3446892d3179Sdrh         sqlite3ReleaseTempRange(pParse, regBase, nCol);
344713449892Sdrh         sqlite3WhereEnd(pWInfo);
344866a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
3449d4e70ebdSdrh         VdbeComment((v, "GROUP BY sort"));
345013449892Sdrh         sAggInfo.useSortingIdx = 1;
345113449892Sdrh       }
345213449892Sdrh 
345313449892Sdrh       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
345413449892Sdrh       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
345513449892Sdrh       ** Then compare the current GROUP BY terms against the GROUP BY terms
345613449892Sdrh       ** from the previous row currently stored in a0, a1, a2...
345713449892Sdrh       */
345813449892Sdrh       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
345913449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
346013449892Sdrh         if( groupBySort ){
34612dcef11bSdrh           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
346213449892Sdrh         }else{
346313449892Sdrh           sAggInfo.directMode = 1;
34642dcef11bSdrh           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
346513449892Sdrh         }
346613449892Sdrh       }
346713449892Sdrh       for(j=pGroupBy->nExpr-1; j>=0; j--){
346813449892Sdrh         if( j==0 ){
34692dcef11bSdrh           sqlite3VdbeAddOp3(v, OP_Eq, iAMem+j, addrProcessRow, iBMem+j);
347013449892Sdrh         }else{
34712dcef11bSdrh           sqlite3VdbeAddOp3(v, OP_Ne, iAMem+j, addrGroupByChange, iBMem+j);
347213449892Sdrh         }
347366a5167bSdrh         sqlite3VdbeChangeP4(v, -1, (void*)pKeyInfo->aColl[j], P4_COLLSEQ);
347435573356Sdrh         sqlite3VdbeChangeP5(v, SQLITE_NULLEQUAL);
347513449892Sdrh       }
347613449892Sdrh 
347713449892Sdrh       /* Generate code that runs whenever the GROUP BY changes.
347813449892Sdrh       ** Change in the GROUP BY are detected by the previous code
347913449892Sdrh       ** block.  If there were no changes, this block is skipped.
348013449892Sdrh       **
348113449892Sdrh       ** This code copies current group by terms in b0,b1,b2,...
348213449892Sdrh       ** over to a0,a1,a2.  It then calls the output subroutine
348313449892Sdrh       ** and resets the aggregate accumulator registers in preparation
348413449892Sdrh       ** for the next GROUP BY batch.
348513449892Sdrh       */
348613449892Sdrh       sqlite3VdbeResolveLabel(v, addrGroupByChange);
348713449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
3488b1fdb2adSdrh         sqlite3VdbeAddOp2(v, OP_Move, iBMem+j, iAMem+j);
348913449892Sdrh       }
349066a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrOutputRow);
3491d4e70ebdSdrh       VdbeComment((v, "output one row"));
34923c84ddffSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
3493d4e70ebdSdrh       VdbeComment((v, "check abort flag"));
349466a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset);
3495d4e70ebdSdrh       VdbeComment((v, "reset accumulator"));
349613449892Sdrh 
349713449892Sdrh       /* Update the aggregate accumulators based on the content of
349813449892Sdrh       ** the current row
349913449892Sdrh       */
350013449892Sdrh       sqlite3VdbeResolveLabel(v, addrProcessRow);
350113449892Sdrh       updateAccumulator(pParse, &sAggInfo);
35024c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
3503d4e70ebdSdrh       VdbeComment((v, "indicate data in accumulator"));
350413449892Sdrh 
350513449892Sdrh       /* End of the loop
350613449892Sdrh       */
350713449892Sdrh       if( groupBySort ){
350866a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
350913449892Sdrh       }else{
351013449892Sdrh         sqlite3WhereEnd(pWInfo);
3511f8875400Sdrh         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
351213449892Sdrh       }
351313449892Sdrh 
351413449892Sdrh       /* Output the final row of result
351513449892Sdrh       */
351666a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrOutputRow);
3517d4e70ebdSdrh       VdbeComment((v, "output final row"));
351813449892Sdrh 
351913449892Sdrh     } /* endif pGroupBy */
352013449892Sdrh     else {
3521a9d1ccb9Sdanielk1977       ExprList *pMinMax = 0;
3522dba0137eSdanielk1977       ExprList *pDel = 0;
3523a9d1ccb9Sdanielk1977       u8 flag;
3524a9d1ccb9Sdanielk1977 
3525738bdcfbSdanielk1977       /* Check if the query is of one of the following forms:
3526738bdcfbSdanielk1977       **
3527738bdcfbSdanielk1977       **   SELECT min(x) FROM ...
3528738bdcfbSdanielk1977       **   SELECT max(x) FROM ...
3529738bdcfbSdanielk1977       **
3530738bdcfbSdanielk1977       ** If it is, then ask the code in where.c to attempt to sort results
3531738bdcfbSdanielk1977       ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
3532738bdcfbSdanielk1977       ** If where.c is able to produce results sorted in this order, then
3533738bdcfbSdanielk1977       ** add vdbe code to break out of the processing loop after the
3534738bdcfbSdanielk1977       ** first iteration (since the first iteration of the loop is
3535738bdcfbSdanielk1977       ** guaranteed to operate on the row with the minimum or maximum
3536738bdcfbSdanielk1977       ** value of x, the only row required).
3537738bdcfbSdanielk1977       **
3538738bdcfbSdanielk1977       ** A special flag must be passed to sqlite3WhereBegin() to slightly
3539738bdcfbSdanielk1977       ** modify behaviour as follows:
3540738bdcfbSdanielk1977       **
3541738bdcfbSdanielk1977       **   + If the query is a "SELECT min(x)", then the loop coded by
3542738bdcfbSdanielk1977       **     where.c should not iterate over any values with a NULL value
3543738bdcfbSdanielk1977       **     for x.
3544738bdcfbSdanielk1977       **
3545738bdcfbSdanielk1977       **   + The optimizer code in where.c (the thing that decides which
3546738bdcfbSdanielk1977       **     index or indices to use) should place a different priority on
3547738bdcfbSdanielk1977       **     satisfying the 'ORDER BY' clause than it does in other cases.
3548738bdcfbSdanielk1977       **     Refer to code and comments in where.c for details.
3549738bdcfbSdanielk1977       */
3550a9d1ccb9Sdanielk1977       flag = minMaxQuery(pParse, p);
3551a9d1ccb9Sdanielk1977       if( flag ){
35528cc74322Sdrh         pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList);
35530e359b30Sdrh         if( pMinMax && !db->mallocFailed ){
3554a9d1ccb9Sdanielk1977           pMinMax->a[0].sortOrder = ((flag==ORDERBY_MIN)?0:1);
3555a9d1ccb9Sdanielk1977           pMinMax->a[0].pExpr->op = TK_COLUMN;
3556a9d1ccb9Sdanielk1977         }
35571013c932Sdrh       }
3558a9d1ccb9Sdanielk1977 
355913449892Sdrh       /* This case runs if the aggregate has no GROUP BY clause.  The
356013449892Sdrh       ** processing is much simpler since there is only a single row
356113449892Sdrh       ** of output.
356213449892Sdrh       */
356313449892Sdrh       resetAccumulator(pParse, &sAggInfo);
3564a9d1ccb9Sdanielk1977       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
3565dba0137eSdanielk1977       if( pWInfo==0 ){
35661013c932Sdrh         sqlite3ExprListDelete(pDel);
3567dba0137eSdanielk1977         goto select_end;
3568dba0137eSdanielk1977       }
356913449892Sdrh       updateAccumulator(pParse, &sAggInfo);
3570a9d1ccb9Sdanielk1977       if( !pMinMax && flag ){
3571a9d1ccb9Sdanielk1977         sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
3572a9d1ccb9Sdanielk1977         VdbeComment((v, "%s() by index", (flag==ORDERBY_MIN?"min":"max")));
3573a9d1ccb9Sdanielk1977       }
357413449892Sdrh       sqlite3WhereEnd(pWInfo);
357513449892Sdrh       finalizeAggFunctions(pParse, &sAggInfo);
357613449892Sdrh       pOrderBy = 0;
35775774b806Sdrh       if( pHaving ){
357835573356Sdrh         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
35795774b806Sdrh       }
358013449892Sdrh       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
35816c8c8ce0Sdanielk1977                       pDest, addrEnd, addrEnd, aff);
3582a9d1ccb9Sdanielk1977 
3583dba0137eSdanielk1977       sqlite3ExprListDelete(pDel);
358413449892Sdrh     }
358513449892Sdrh     sqlite3VdbeResolveLabel(v, addrEnd);
358613449892Sdrh 
358713449892Sdrh   } /* endif aggregate query */
35882282792aSdrh 
3589cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
3590cce7d176Sdrh   ** and send them to the callback one by one.
3591cce7d176Sdrh   */
3592cce7d176Sdrh   if( pOrderBy ){
35936c8c8ce0Sdanielk1977     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
3594cce7d176Sdrh   }
35956a535340Sdrh 
359693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
3597f620b4e2Sdrh   /* If this was a subquery, we have now converted the subquery into a
35981787ccabSdanielk1977   ** temporary table.  So set the SrcList_item.isPopulated flag to prevent
35991787ccabSdanielk1977   ** this subquery from being evaluated again and to force the use of
36001787ccabSdanielk1977   ** the temporary table.
3601f620b4e2Sdrh   */
3602f620b4e2Sdrh   if( pParent ){
3603f620b4e2Sdrh     assert( pParent->pSrc->nSrc>parentTab );
3604f620b4e2Sdrh     assert( pParent->pSrc->a[parentTab].pSelect==p );
36051787ccabSdanielk1977     pParent->pSrc->a[parentTab].isPopulated = 1;
3606f620b4e2Sdrh   }
360793758c8dSdanielk1977 #endif
3608f620b4e2Sdrh 
3609ec7429aeSdrh   /* Jump here to skip this query
3610ec7429aeSdrh   */
3611ec7429aeSdrh   sqlite3VdbeResolveLabel(v, iEnd);
3612ec7429aeSdrh 
36131d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
36141d83f052Sdrh   ** to indicate no errors.
36151d83f052Sdrh   */
36161d83f052Sdrh   rc = 0;
36171d83f052Sdrh 
36181d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
36191d83f052Sdrh   ** successful coding of the SELECT.
36201d83f052Sdrh   */
36211d83f052Sdrh select_end:
3622955de52cSdanielk1977 
3623955de52cSdanielk1977   /* Identify column names if we will be using them in a callback.  This
3624955de52cSdanielk1977   ** step is skipped if the output is going to some other destination.
3625955de52cSdanielk1977   */
36266c8c8ce0Sdanielk1977   if( rc==SQLITE_OK && pDest->eDest==SRT_Callback ){
3627955de52cSdanielk1977     generateColumnNames(pParse, pTabList, pEList);
3628955de52cSdanielk1977   }
3629955de52cSdanielk1977 
363017435752Sdrh   sqlite3_free(sAggInfo.aCol);
363117435752Sdrh   sqlite3_free(sAggInfo.aFunc);
36321d83f052Sdrh   return rc;
3633cce7d176Sdrh }
3634485f0039Sdrh 
363577a2a5e7Sdrh #if defined(SQLITE_DEBUG)
3636485f0039Sdrh /*
3637485f0039Sdrh *******************************************************************************
3638485f0039Sdrh ** The following code is used for testing and debugging only.  The code
3639485f0039Sdrh ** that follows does not appear in normal builds.
3640485f0039Sdrh **
3641485f0039Sdrh ** These routines are used to print out the content of all or part of a
3642485f0039Sdrh ** parse structures such as Select or Expr.  Such printouts are useful
3643485f0039Sdrh ** for helping to understand what is happening inside the code generator
3644485f0039Sdrh ** during the execution of complex SELECT statements.
3645485f0039Sdrh **
3646485f0039Sdrh ** These routine are not called anywhere from within the normal
3647485f0039Sdrh ** code base.  Then are intended to be called from within the debugger
3648485f0039Sdrh ** or from temporary "printf" statements inserted for debugging.
3649485f0039Sdrh */
36503a00f907Smlcreech static void sqlite3PrintExpr(Expr *p){
3651485f0039Sdrh   if( p->token.z && p->token.n>0 ){
3652485f0039Sdrh     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
3653485f0039Sdrh   }else{
3654485f0039Sdrh     sqlite3DebugPrintf("(%d", p->op);
3655485f0039Sdrh   }
3656485f0039Sdrh   if( p->pLeft ){
3657485f0039Sdrh     sqlite3DebugPrintf(" ");
3658485f0039Sdrh     sqlite3PrintExpr(p->pLeft);
3659485f0039Sdrh   }
3660485f0039Sdrh   if( p->pRight ){
3661485f0039Sdrh     sqlite3DebugPrintf(" ");
3662485f0039Sdrh     sqlite3PrintExpr(p->pRight);
3663485f0039Sdrh   }
3664485f0039Sdrh   sqlite3DebugPrintf(")");
3665485f0039Sdrh }
36663a00f907Smlcreech static void sqlite3PrintExprList(ExprList *pList){
3667485f0039Sdrh   int i;
3668485f0039Sdrh   for(i=0; i<pList->nExpr; i++){
3669485f0039Sdrh     sqlite3PrintExpr(pList->a[i].pExpr);
3670485f0039Sdrh     if( i<pList->nExpr-1 ){
3671485f0039Sdrh       sqlite3DebugPrintf(", ");
3672485f0039Sdrh     }
3673485f0039Sdrh   }
3674485f0039Sdrh }
36753a00f907Smlcreech static void sqlite3PrintSelect(Select *p, int indent){
3676485f0039Sdrh   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
3677485f0039Sdrh   sqlite3PrintExprList(p->pEList);
3678485f0039Sdrh   sqlite3DebugPrintf("\n");
3679485f0039Sdrh   if( p->pSrc ){
3680485f0039Sdrh     char *zPrefix;
3681485f0039Sdrh     int i;
3682485f0039Sdrh     zPrefix = "FROM";
3683485f0039Sdrh     for(i=0; i<p->pSrc->nSrc; i++){
3684485f0039Sdrh       struct SrcList_item *pItem = &p->pSrc->a[i];
3685485f0039Sdrh       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
3686485f0039Sdrh       zPrefix = "";
3687485f0039Sdrh       if( pItem->pSelect ){
3688485f0039Sdrh         sqlite3DebugPrintf("(\n");
3689485f0039Sdrh         sqlite3PrintSelect(pItem->pSelect, indent+10);
3690485f0039Sdrh         sqlite3DebugPrintf("%*s)", indent+8, "");
3691485f0039Sdrh       }else if( pItem->zName ){
3692485f0039Sdrh         sqlite3DebugPrintf("%s", pItem->zName);
3693485f0039Sdrh       }
3694485f0039Sdrh       if( pItem->pTab ){
3695485f0039Sdrh         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
3696485f0039Sdrh       }
3697485f0039Sdrh       if( pItem->zAlias ){
3698485f0039Sdrh         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
3699485f0039Sdrh       }
3700485f0039Sdrh       if( i<p->pSrc->nSrc-1 ){
3701485f0039Sdrh         sqlite3DebugPrintf(",");
3702485f0039Sdrh       }
3703485f0039Sdrh       sqlite3DebugPrintf("\n");
3704485f0039Sdrh     }
3705485f0039Sdrh   }
3706485f0039Sdrh   if( p->pWhere ){
3707485f0039Sdrh     sqlite3DebugPrintf("%*s WHERE ", indent, "");
3708485f0039Sdrh     sqlite3PrintExpr(p->pWhere);
3709485f0039Sdrh     sqlite3DebugPrintf("\n");
3710485f0039Sdrh   }
3711485f0039Sdrh   if( p->pGroupBy ){
3712485f0039Sdrh     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
3713485f0039Sdrh     sqlite3PrintExprList(p->pGroupBy);
3714485f0039Sdrh     sqlite3DebugPrintf("\n");
3715485f0039Sdrh   }
3716485f0039Sdrh   if( p->pHaving ){
3717485f0039Sdrh     sqlite3DebugPrintf("%*s HAVING ", indent, "");
3718485f0039Sdrh     sqlite3PrintExpr(p->pHaving);
3719485f0039Sdrh     sqlite3DebugPrintf("\n");
3720485f0039Sdrh   }
3721485f0039Sdrh   if( p->pOrderBy ){
3722485f0039Sdrh     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
3723485f0039Sdrh     sqlite3PrintExprList(p->pOrderBy);
3724485f0039Sdrh     sqlite3DebugPrintf("\n");
3725485f0039Sdrh   }
3726485f0039Sdrh }
3727485f0039Sdrh /* End of the structure debug printing code
3728485f0039Sdrh *****************************************************************************/
3729485f0039Sdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
3730