xref: /sqlite-3.40.0/src/select.c (revision da250ea5)
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*da250ea5Sdrh ** $Id: select.c,v 1.425 2008/04/01 05:07:15 drh Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19315555caSdrh 
20cce7d176Sdrh /*
21eda639e1Sdrh ** Delete all the content of a Select structure but do not deallocate
22eda639e1Sdrh ** the select structure itself.
23eda639e1Sdrh */
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){
208a686bfcfSdanielk1977 
209a686bfcfSdanielk1977   /* Check if the string contains any " characters. If it does, then
210a686bfcfSdanielk1977   ** this function will malloc space to create a quoted version of
211a686bfcfSdanielk1977   ** the string in. Otherwise, save a call to sqlite3MPrintf() by
212a686bfcfSdanielk1977   ** just copying the pointer to the string.
213a686bfcfSdanielk1977   */
214a686bfcfSdanielk1977   const char *z2 = z;
215a686bfcfSdanielk1977   while( *z2 ){
216a686bfcfSdanielk1977     if( *z2=='"' ) break;
217a686bfcfSdanielk1977     z2++;
218a686bfcfSdanielk1977   }
219a686bfcfSdanielk1977 
220a686bfcfSdanielk1977   if( *z2 ){
221a686bfcfSdanielk1977     /* String contains " characters - copy and quote the string. */
222a686bfcfSdanielk1977     p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z);
223f3b863edSdanielk1977     if( p->z ){
224f3b863edSdanielk1977       p->n = strlen((char *)p->z);
225a686bfcfSdanielk1977       p->dyn = 1;
226a686bfcfSdanielk1977     }
2271e536953Sdanielk1977   }else{
228a686bfcfSdanielk1977     /* String contains no " characters - copy the pointer. */
229a686bfcfSdanielk1977     p->z = (u8*)z;
230a686bfcfSdanielk1977     p->n = (z2 - z);
231a686bfcfSdanielk1977     p->dyn = 0;
232f3b863edSdanielk1977   }
233f3b863edSdanielk1977 }
234f3b863edSdanielk1977 
235f3b863edSdanielk1977 /*
236c182d163Sdrh ** Create an expression node for an identifier with the name of zName
237c182d163Sdrh */
23817435752Sdrh Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
239c182d163Sdrh   Token dummy;
240c182d163Sdrh   setToken(&dummy, zName);
24117435752Sdrh   return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
242c182d163Sdrh }
243c182d163Sdrh 
24491bb0eedSdrh /*
245ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the
246ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2.
247ad2d8307Sdrh */
248ad2d8307Sdrh static void addWhereTerm(
24917435752Sdrh   Parse *pParse,           /* Parsing context */
250ad2d8307Sdrh   const char *zCol,        /* Name of the column */
251ad2d8307Sdrh   const Table *pTab1,      /* First table */
252030530deSdrh   const char *zAlias1,     /* Alias for first table.  May be NULL */
253ad2d8307Sdrh   const Table *pTab2,      /* Second table */
254030530deSdrh   const char *zAlias2,     /* Alias for second table.  May be NULL */
25522d6a53aSdrh   int iRightJoinTable,     /* VDBE cursor for the right table */
256ad27e761Sdrh   Expr **ppExpr,           /* Add the equality term to this expression */
257ad27e761Sdrh   int isOuterJoin          /* True if dealing with an OUTER join */
258ad2d8307Sdrh ){
259ad2d8307Sdrh   Expr *pE1a, *pE1b, *pE1c;
260ad2d8307Sdrh   Expr *pE2a, *pE2b, *pE2c;
261ad2d8307Sdrh   Expr *pE;
262ad2d8307Sdrh 
26317435752Sdrh   pE1a = sqlite3CreateIdExpr(pParse, zCol);
26417435752Sdrh   pE2a = sqlite3CreateIdExpr(pParse, zCol);
265030530deSdrh   if( zAlias1==0 ){
266030530deSdrh     zAlias1 = pTab1->zName;
267030530deSdrh   }
26817435752Sdrh   pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
269030530deSdrh   if( zAlias2==0 ){
270030530deSdrh     zAlias2 = pTab2->zName;
271030530deSdrh   }
27217435752Sdrh   pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
27317435752Sdrh   pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
27417435752Sdrh   pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
2751e536953Sdanielk1977   pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
276ad27e761Sdrh   if( pE && isOuterJoin ){
2771f16230bSdrh     ExprSetProperty(pE, EP_FromJoin);
27822d6a53aSdrh     pE->iRightJoinTable = iRightJoinTable;
279206f3d96Sdrh   }
280f4ce8ed0Sdrh   *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
281ad2d8307Sdrh }
282ad2d8307Sdrh 
283ad2d8307Sdrh /*
2841f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
28522d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the
28622d6a53aSdrh ** expression.
2871cc093c2Sdrh **
288e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
2891cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
2901f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
2911f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
2921f16230bSdrh ** WHERE clause during join processing but we need to remember that they
2931f16230bSdrh ** originated in the ON or USING clause.
29422d6a53aSdrh **
29522d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the
29622d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not
29722d6a53aSdrh ** explicitly mentioned in the expression.  That information is needed
29822d6a53aSdrh ** for cases like this:
29922d6a53aSdrh **
30022d6a53aSdrh **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
30122d6a53aSdrh **
30222d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5
30322d6a53aSdrh ** term until after the t2 loop of the join.  In that way, a
30422d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
30522d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately
30622d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in
30722d6a53aSdrh ** the output, which is incorrect.
3081cc093c2Sdrh */
30922d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){
3101cc093c2Sdrh   while( p ){
3111f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
31222d6a53aSdrh     p->iRightJoinTable = iTable;
31322d6a53aSdrh     setJoinExpr(p->pLeft, iTable);
3141cc093c2Sdrh     p = p->pRight;
3151cc093c2Sdrh   }
3161cc093c2Sdrh }
3171cc093c2Sdrh 
3181cc093c2Sdrh /*
319ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
320ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
321ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
322ad2d8307Sdrh **
32391bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure.
32491bb0eedSdrh ** The left most table is the first entry in Select.pSrc.  The right-most
32591bb0eedSdrh ** table is the last entry.  The join operator is held in the entry to
32691bb0eedSdrh ** the left.  Thus entry 0 contains the join operator for the join between
32791bb0eedSdrh ** entries 0 and 1.  Any ON or USING clauses associated with the join are
32891bb0eedSdrh ** also attached to the left entry.
32991bb0eedSdrh **
330ad2d8307Sdrh ** This routine returns the number of errors encountered.
331ad2d8307Sdrh */
332ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
33391bb0eedSdrh   SrcList *pSrc;                  /* All tables in the FROM clause */
33491bb0eedSdrh   int i, j;                       /* Loop counters */
33591bb0eedSdrh   struct SrcList_item *pLeft;     /* Left table being joined */
33691bb0eedSdrh   struct SrcList_item *pRight;    /* Right table being joined */
337ad2d8307Sdrh 
33891bb0eedSdrh   pSrc = p->pSrc;
33991bb0eedSdrh   pLeft = &pSrc->a[0];
34091bb0eedSdrh   pRight = &pLeft[1];
34191bb0eedSdrh   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
34291bb0eedSdrh     Table *pLeftTab = pLeft->pTab;
34391bb0eedSdrh     Table *pRightTab = pRight->pTab;
344ad27e761Sdrh     int isOuter;
34591bb0eedSdrh 
34691bb0eedSdrh     if( pLeftTab==0 || pRightTab==0 ) continue;
347ad27e761Sdrh     isOuter = (pRight->jointype & JT_OUTER)!=0;
348ad2d8307Sdrh 
349ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
350ad2d8307Sdrh     ** every column that the two tables have in common.
351ad2d8307Sdrh     */
35261dfc31dSdrh     if( pRight->jointype & JT_NATURAL ){
35361dfc31dSdrh       if( pRight->pOn || pRight->pUsing ){
3544adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
355ad2d8307Sdrh            "an ON or USING clause", 0);
356ad2d8307Sdrh         return 1;
357ad2d8307Sdrh       }
35891bb0eedSdrh       for(j=0; j<pLeftTab->nCol; j++){
35991bb0eedSdrh         char *zName = pLeftTab->aCol[j].zName;
36091bb0eedSdrh         if( columnIndex(pRightTab, zName)>=0 ){
3611e536953Sdanielk1977           addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
36222d6a53aSdrh                               pRightTab, pRight->zAlias,
363ad27e761Sdrh                               pRight->iCursor, &p->pWhere, isOuter);
36422d6a53aSdrh 
365ad2d8307Sdrh         }
366ad2d8307Sdrh       }
367ad2d8307Sdrh     }
368ad2d8307Sdrh 
369ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
370ad2d8307Sdrh     */
37161dfc31dSdrh     if( pRight->pOn && pRight->pUsing ){
3724adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
373da93d238Sdrh         "clauses in the same join");
374ad2d8307Sdrh       return 1;
375ad2d8307Sdrh     }
376ad2d8307Sdrh 
377ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
37891bb0eedSdrh     ** an AND operator.
379ad2d8307Sdrh     */
38061dfc31dSdrh     if( pRight->pOn ){
381ad27e761Sdrh       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
38217435752Sdrh       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
38361dfc31dSdrh       pRight->pOn = 0;
384ad2d8307Sdrh     }
385ad2d8307Sdrh 
386ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
387ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
388ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
389ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
390ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
391ad2d8307Sdrh     ** not contained in both tables to be joined.
392ad2d8307Sdrh     */
39361dfc31dSdrh     if( pRight->pUsing ){
39461dfc31dSdrh       IdList *pList = pRight->pUsing;
395ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
39691bb0eedSdrh         char *zName = pList->a[j].zName;
39791bb0eedSdrh         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
3984adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
39991bb0eedSdrh             "not present in both tables", zName);
400ad2d8307Sdrh           return 1;
401ad2d8307Sdrh         }
4021e536953Sdanielk1977         addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
40322d6a53aSdrh                             pRightTab, pRight->zAlias,
404ad27e761Sdrh                             pRight->iCursor, &p->pWhere, isOuter);
405ad2d8307Sdrh       }
406ad2d8307Sdrh     }
407ad2d8307Sdrh   }
408ad2d8307Sdrh   return 0;
409ad2d8307Sdrh }
410ad2d8307Sdrh 
411ad2d8307Sdrh /*
412c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
413c926afbcSdrh ** stack into the sorter.
414c926afbcSdrh */
415d59ba6ceSdrh static void pushOntoSorter(
416d59ba6ceSdrh   Parse *pParse,         /* Parser context */
417d59ba6ceSdrh   ExprList *pOrderBy,    /* The ORDER BY clause */
418b7654111Sdrh   Select *pSelect,       /* The whole SELECT statement */
419b7654111Sdrh   int regData            /* Register holding data to be sorted */
420d59ba6ceSdrh ){
421d59ba6ceSdrh   Vdbe *v = pParse->pVdbe;
422892d3179Sdrh   int nExpr = pOrderBy->nExpr;
423892d3179Sdrh   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
424892d3179Sdrh   int regRecord = sqlite3GetTempReg(pParse);
425892d3179Sdrh   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase);
426892d3179Sdrh   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
427e55cbd72Sdrh   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1);
4281db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
429892d3179Sdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
430892d3179Sdrh   sqlite3ReleaseTempReg(pParse, regRecord);
431892d3179Sdrh   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
432d59ba6ceSdrh   if( pSelect->iLimit>=0 ){
43315007a99Sdrh     int addr1, addr2;
434b7654111Sdrh     int iLimit;
435b7654111Sdrh     if( pSelect->pOffset ){
436b7654111Sdrh       iLimit = pSelect->iOffset+1;
437b7654111Sdrh     }else{
438b7654111Sdrh       iLimit = pSelect->iLimit;
439b7654111Sdrh     }
440b7654111Sdrh     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
441b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
4423c84ddffSdrh     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
443d59ba6ceSdrh     sqlite3VdbeJumpHere(v, addr1);
4443c84ddffSdrh     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
4453c84ddffSdrh     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
44615007a99Sdrh     sqlite3VdbeJumpHere(v, addr2);
447d59ba6ceSdrh     pSelect->iLimit = -1;
448d59ba6ceSdrh   }
449c926afbcSdrh }
450c926afbcSdrh 
451c926afbcSdrh /*
452ec7429aeSdrh ** Add code to implement the OFFSET
453ea48eb2eSdrh */
454ec7429aeSdrh static void codeOffset(
455bab39e13Sdrh   Vdbe *v,          /* Generate code into this VM */
456ea48eb2eSdrh   Select *p,        /* The SELECT statement being coded */
457b7654111Sdrh   int iContinue     /* Jump here to skip the current record */
458ea48eb2eSdrh ){
45913449892Sdrh   if( p->iOffset>=0 && iContinue!=0 ){
46015007a99Sdrh     int addr;
4618558cde1Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
4623c84ddffSdrh     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
46366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
464d4e70ebdSdrh     VdbeComment((v, "skip OFFSET records"));
46515007a99Sdrh     sqlite3VdbeJumpHere(v, addr);
466ea48eb2eSdrh   }
467ea48eb2eSdrh }
468ea48eb2eSdrh 
469ea48eb2eSdrh /*
47098757157Sdrh ** Add code that will check to make sure the N registers starting at iMem
47198757157Sdrh ** form a distinct entry.  iTab is a sorting index that holds previously
472a2a49dc9Sdrh ** seen combinations of the N values.  A new entry is made in iTab
473a2a49dc9Sdrh ** if the current N values are new.
474a2a49dc9Sdrh **
475a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the
476a2a49dc9Sdrh ** stack if the top N elements are not distinct.
477a2a49dc9Sdrh */
478a2a49dc9Sdrh static void codeDistinct(
4792dcef11bSdrh   Parse *pParse,     /* Parsing and code generating context */
480a2a49dc9Sdrh   int iTab,          /* A sorting index used to test for distinctness */
481a2a49dc9Sdrh   int addrRepeat,    /* Jump to here if not distinct */
482477df4b3Sdrh   int N,             /* Number of elements */
483a2a49dc9Sdrh   int iMem           /* First element */
484a2a49dc9Sdrh ){
4852dcef11bSdrh   Vdbe *v;
4862dcef11bSdrh   int r1;
4872dcef11bSdrh 
4882dcef11bSdrh   v = pParse->pVdbe;
4892dcef11bSdrh   r1 = sqlite3GetTempReg(pParse);
4901db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
4912dcef11bSdrh   sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1);
4922dcef11bSdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
4932dcef11bSdrh   sqlite3ReleaseTempReg(pParse, r1);
494a2a49dc9Sdrh }
495a2a49dc9Sdrh 
496a2a49dc9Sdrh /*
497e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression
498e305f43fSdrh ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
499e305f43fSdrh ** column.  We do this in a subroutine because the error occurs in multiple
500e305f43fSdrh ** places.
501e305f43fSdrh */
5026c8c8ce0Sdanielk1977 static int checkForMultiColumnSelectError(
5036c8c8ce0Sdanielk1977   Parse *pParse,       /* Parse context. */
5046c8c8ce0Sdanielk1977   SelectDest *pDest,   /* Destination of SELECT results */
5056c8c8ce0Sdanielk1977   int nExpr            /* Number of result columns returned by SELECT */
5066c8c8ce0Sdanielk1977 ){
5076c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
508e305f43fSdrh   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
509e305f43fSdrh     sqlite3ErrorMsg(pParse, "only a single result allowed for "
510e305f43fSdrh        "a SELECT that is part of an expression");
511e305f43fSdrh     return 1;
512e305f43fSdrh   }else{
513e305f43fSdrh     return 0;
514e305f43fSdrh   }
515e305f43fSdrh }
516c99130fdSdrh 
517c99130fdSdrh /*
5182282792aSdrh ** This routine generates the code for the inside of the inner loop
5192282792aSdrh ** of a SELECT.
52082c3d636Sdrh **
52138640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
52238640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
52338640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
52438640e15Sdrh ** datatypes for each column.
5252282792aSdrh */
526d2b3e23bSdrh static void selectInnerLoop(
5272282792aSdrh   Parse *pParse,          /* The parser context */
528df199a25Sdrh   Select *p,              /* The complete select statement being coded */
5292282792aSdrh   ExprList *pEList,       /* List of values being extracted */
53082c3d636Sdrh   int srcTab,             /* Pull data from this table */
531967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
5322282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
5332282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
5346c8c8ce0Sdanielk1977   SelectDest *pDest,      /* How to dispose of the results */
5352282792aSdrh   int iContinue,          /* Jump here to continue with next row */
53684ac9d02Sdanielk1977   int iBreak,             /* Jump here to break out of the inner loop */
53784ac9d02Sdanielk1977   char *aff               /* affinity string if eDest is SRT_Union */
5382282792aSdrh ){
5392282792aSdrh   Vdbe *v = pParse->pVdbe;
540d847eaadSdrh   int i;
541ea48eb2eSdrh   int hasDistinct;        /* True if the DISTINCT keyword is present */
542d847eaadSdrh   int regResult;              /* Start of memory holding result set */
543d847eaadSdrh   int eDest = pDest->eDest;   /* How to dispose of results */
544d847eaadSdrh   int iParm = pDest->iParm;   /* First argument to disposal method */
545d847eaadSdrh   int nResultCol;             /* Number of result columns */
54638640e15Sdrh 
547d2b3e23bSdrh   if( v==0 ) return;
54838640e15Sdrh   assert( pEList!=0 );
5492282792aSdrh 
550df199a25Sdrh   /* If there was a LIMIT clause on the SELECT statement, then do the check
551df199a25Sdrh   ** to see if this row should be output.
552df199a25Sdrh   */
553eda639e1Sdrh   hasDistinct = distinct>=0 && pEList->nExpr>0;
554ea48eb2eSdrh   if( pOrderBy==0 && !hasDistinct ){
555b7654111Sdrh     codeOffset(v, p, iContinue);
556df199a25Sdrh   }
557df199a25Sdrh 
558967e8b73Sdrh   /* Pull the requested columns.
5592282792aSdrh   */
56038640e15Sdrh   if( nColumn>0 ){
561d847eaadSdrh     nResultCol = nColumn;
562a2a49dc9Sdrh   }else{
563d847eaadSdrh     nResultCol = pEList->nExpr;
564a2a49dc9Sdrh   }
5651ece7325Sdrh   if( pDest->iMem==0 ){
5661ece7325Sdrh     pDest->iMem = sqlite3GetTempRange(pParse, nResultCol);
567ad27e761Sdrh     pDest->nMem = nResultCol;
568ad27e761Sdrh   }else if( pDest->nMem!=nResultCol ){
569995ae279Sdrh     /* This happens when two SELECTs of a compound SELECT have differing
570995ae279Sdrh     ** numbers of result columns.  The error message will be generated by
571995ae279Sdrh     ** a higher-level routine. */
572ad27e761Sdrh     return;
5731013c932Sdrh   }
5741ece7325Sdrh   regResult = pDest->iMem;
575a2a49dc9Sdrh   if( nColumn>0 ){
576967e8b73Sdrh     for(i=0; i<nColumn; i++){
577d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
57882c3d636Sdrh     }
5799ed1dfa8Sdanielk1977   }else if( eDest!=SRT_Exists ){
5809ed1dfa8Sdanielk1977     /* If the destination is an EXISTS(...) expression, the actual
5819ed1dfa8Sdanielk1977     ** values returned by the SELECT are not required.
5829ed1dfa8Sdanielk1977     */
583d847eaadSdrh     for(i=0; i<nResultCol; i++){
584d847eaadSdrh       sqlite3ExprCode(pParse, pEList->a[i].pExpr, regResult+i);
58582c3d636Sdrh     }
586a2a49dc9Sdrh   }
587d847eaadSdrh   nColumn = nResultCol;
5882282792aSdrh 
589daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
590daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
591daffd0e5Sdrh   ** part of the result.
5922282792aSdrh   */
593ea48eb2eSdrh   if( hasDistinct ){
594f8875400Sdrh     assert( pEList!=0 );
595f8875400Sdrh     assert( pEList->nExpr==nColumn );
596d847eaadSdrh     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
597ea48eb2eSdrh     if( pOrderBy==0 ){
598b7654111Sdrh       codeOffset(v, p, iContinue);
599ea48eb2eSdrh     }
6002282792aSdrh   }
60182c3d636Sdrh 
6026c8c8ce0Sdanielk1977   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
603d2b3e23bSdrh     return;
604e305f43fSdrh   }
605e305f43fSdrh 
606c926afbcSdrh   switch( eDest ){
60782c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
60882c3d636Sdrh     ** table iParm.
6092282792aSdrh     */
61013449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
611c926afbcSdrh     case SRT_Union: {
6129cbf3425Sdrh       int r1;
6139cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
614d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
61513449892Sdrh       if( aff ){
61666a5167bSdrh         sqlite3VdbeChangeP4(v, -1, aff, P4_STATIC);
61713449892Sdrh       }
6189cbf3425Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
6199cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
620c926afbcSdrh       break;
621c926afbcSdrh     }
62282c3d636Sdrh 
62382c3d636Sdrh     /* Construct a record from the query result, but instead of
62482c3d636Sdrh     ** saving that record, use it as a key to delete elements from
62582c3d636Sdrh     ** the temporary table iParm.
62682c3d636Sdrh     */
627c926afbcSdrh     case SRT_Except: {
628e14006d0Sdrh       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
629c926afbcSdrh       break;
630c926afbcSdrh     }
6315338a5f7Sdanielk1977 #endif
6325338a5f7Sdanielk1977 
6335338a5f7Sdanielk1977     /* Store the result as data using a unique key.
6345338a5f7Sdanielk1977     */
6355338a5f7Sdanielk1977     case SRT_Table:
636b9bb7c18Sdrh     case SRT_EphemTab: {
637b7654111Sdrh       int r1 = sqlite3GetTempReg(pParse);
638d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
6395338a5f7Sdanielk1977       if( pOrderBy ){
640b7654111Sdrh         pushOntoSorter(pParse, pOrderBy, p, r1);
6415338a5f7Sdanielk1977       }else{
642b7654111Sdrh         int r2 = sqlite3GetTempReg(pParse);
643b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
644b7654111Sdrh         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
645b7654111Sdrh         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
646b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r2);
6475338a5f7Sdanielk1977       }
648b7654111Sdrh       sqlite3ReleaseTempReg(pParse, r1);
6495338a5f7Sdanielk1977       break;
6505338a5f7Sdanielk1977     }
6512282792aSdrh 
65293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
6532282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
6542282792aSdrh     ** then there should be a single item on the stack.  Write this
6552282792aSdrh     ** item into the set table with bogus data.
6562282792aSdrh     */
657c926afbcSdrh     case SRT_Set: {
65852b36cabSdrh       int addr2;
659e014a838Sdanielk1977 
660967e8b73Sdrh       assert( nColumn==1 );
661d847eaadSdrh       addr2 = sqlite3VdbeAddOp1(v, OP_IsNull, regResult);
6626c8c8ce0Sdanielk1977       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
663c926afbcSdrh       if( pOrderBy ){
664de941c60Sdrh         /* At first glance you would think we could optimize out the
665de941c60Sdrh         ** ORDER BY in this case since the order of entries in the set
666de941c60Sdrh         ** does not matter.  But there might be a LIMIT clause, in which
667de941c60Sdrh         ** case the order does matter */
668d847eaadSdrh         pushOntoSorter(pParse, pOrderBy, p, regResult);
669c926afbcSdrh       }else{
670b7654111Sdrh         int r1 = sqlite3GetTempReg(pParse);
671d847eaadSdrh         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
672*da250ea5Sdrh         sqlite3ExprCacheAffinityChange(pParse, regResult, 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{
697e55cbd72Sdrh         sqlite3ExprCodeMove(pParse, 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);
719*da250ea5Sdrh         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
720ac82fcf5Sdrh       }
721142e30dfSdrh       break;
722142e30dfSdrh     }
723142e30dfSdrh 
7246a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER)
725d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
726d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
727d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
728d7489c39Sdrh     ** about the actual results of the select.
729d7489c39Sdrh     */
730c926afbcSdrh     default: {
731f46f905aSdrh       assert( eDest==SRT_Discard );
732c926afbcSdrh       break;
733c926afbcSdrh     }
73493758c8dSdanielk1977 #endif
735c926afbcSdrh   }
736ec7429aeSdrh 
737ec7429aeSdrh   /* Jump to the end of the loop if the LIMIT is reached.
738ec7429aeSdrh   */
739ec7429aeSdrh   if( p->iLimit>=0 && pOrderBy==0 ){
7408558cde1Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
7413c84ddffSdrh     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
742ec7429aeSdrh   }
74382c3d636Sdrh }
74482c3d636Sdrh 
74582c3d636Sdrh /*
746dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records
747dece1a84Sdrh ** the collating sequence for each expression in that expression list.
748dece1a84Sdrh **
7490342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
7500342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to
7510342b1f5Sdrh ** implement that clause.  If the ExprList is the result set of a SELECT
7520342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual
7530342b1f5Sdrh ** index to implement a DISTINCT test.
7540342b1f5Sdrh **
755dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
756dece1a84Sdrh ** function is responsible for seeing that this structure is eventually
75766a5167bSdrh ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
75866a5167bSdrh ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
759dece1a84Sdrh */
760dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
761dece1a84Sdrh   sqlite3 *db = pParse->db;
762dece1a84Sdrh   int nExpr;
763dece1a84Sdrh   KeyInfo *pInfo;
764dece1a84Sdrh   struct ExprList_item *pItem;
765dece1a84Sdrh   int i;
766dece1a84Sdrh 
767dece1a84Sdrh   nExpr = pList->nExpr;
76817435752Sdrh   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
769dece1a84Sdrh   if( pInfo ){
7702646da7eSdrh     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
771dece1a84Sdrh     pInfo->nField = nExpr;
77214db2665Sdanielk1977     pInfo->enc = ENC(db);
773dece1a84Sdrh     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
774dece1a84Sdrh       CollSeq *pColl;
775dece1a84Sdrh       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
776dece1a84Sdrh       if( !pColl ){
777dece1a84Sdrh         pColl = db->pDfltColl;
778dece1a84Sdrh       }
779dece1a84Sdrh       pInfo->aColl[i] = pColl;
780dece1a84Sdrh       pInfo->aSortOrder[i] = pItem->sortOrder;
781dece1a84Sdrh     }
782dece1a84Sdrh   }
783dece1a84Sdrh   return pInfo;
784dece1a84Sdrh }
785dece1a84Sdrh 
786dece1a84Sdrh 
787dece1a84Sdrh /*
788d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
789d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
790d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
791d8bc7086Sdrh ** routine generates the code needed to do that.
792d8bc7086Sdrh */
793c926afbcSdrh static void generateSortTail(
794cdd536f0Sdrh   Parse *pParse,    /* Parsing context */
795c926afbcSdrh   Select *p,        /* The SELECT statement */
796c926afbcSdrh   Vdbe *v,          /* Generate code into this VDBE */
797c926afbcSdrh   int nColumn,      /* Number of columns of data */
7986c8c8ce0Sdanielk1977   SelectDest *pDest /* Write the sorted results here */
799c926afbcSdrh ){
8000342b1f5Sdrh   int brk = sqlite3VdbeMakeLabel(v);
8010342b1f5Sdrh   int cont = sqlite3VdbeMakeLabel(v);
802d8bc7086Sdrh   int addr;
8030342b1f5Sdrh   int iTab;
80461fc595fSdrh   int pseudoTab = 0;
8050342b1f5Sdrh   ExprList *pOrderBy = p->pOrderBy;
806ffbc3088Sdrh 
8076c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
8086c8c8ce0Sdanielk1977   int iParm = pDest->iParm;
8096c8c8ce0Sdanielk1977 
8102d401ab8Sdrh   int regRow;
8112d401ab8Sdrh   int regRowid;
8122d401ab8Sdrh 
8139d2985c7Sdrh   iTab = pOrderBy->iECursor;
814cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
815cdd536f0Sdrh     pseudoTab = pParse->nTab++;
816cd3e8f7cSdanielk1977     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nColumn);
8179882d999Sdanielk1977     sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, eDest==SRT_Callback);
818cdd536f0Sdrh   }
81966a5167bSdrh   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, brk);
820b7654111Sdrh   codeOffset(v, p, cont);
8212d401ab8Sdrh   regRow = sqlite3GetTempReg(pParse);
8222d401ab8Sdrh   regRowid = sqlite3GetTempReg(pParse);
8232d401ab8Sdrh   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
824c926afbcSdrh   switch( eDest ){
825c926afbcSdrh     case SRT_Table:
826b9bb7c18Sdrh     case SRT_EphemTab: {
8272d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
8282d401ab8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
8292d401ab8Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
830c926afbcSdrh       break;
831c926afbcSdrh     }
83293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
833c926afbcSdrh     case SRT_Set: {
8342d401ab8Sdrh       int j1;
835c926afbcSdrh       assert( nColumn==1 );
8362d401ab8Sdrh       j1 = sqlite3VdbeAddOp1(v, OP_IsNull, regRow);
837a7a8e14bSdanielk1977       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
838*da250ea5Sdrh       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
839a7a8e14bSdanielk1977       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
8406a288a33Sdrh       sqlite3VdbeJumpHere(v, j1);
841c926afbcSdrh       break;
842c926afbcSdrh     }
843c926afbcSdrh     case SRT_Mem: {
844c926afbcSdrh       assert( nColumn==1 );
845e55cbd72Sdrh       sqlite3ExprCodeMove(pParse, regRow, iParm);
846ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
847c926afbcSdrh       break;
848c926afbcSdrh     }
84993758c8dSdanielk1977 #endif
850ce665cf6Sdrh     case SRT_Callback:
851ac82fcf5Sdrh     case SRT_Subroutine: {
852ac82fcf5Sdrh       int i;
8532d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid);
8542d401ab8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid);
855ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
8569882d999Sdanielk1977         assert( regRow!=pDest->iMem+i );
8571013c932Sdrh         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
858ac82fcf5Sdrh       }
859ce665cf6Sdrh       if( eDest==SRT_Callback ){
8601013c932Sdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
861*da250ea5Sdrh         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
862ce665cf6Sdrh       }else{
86366a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Gosub, 0, iParm);
864ce665cf6Sdrh       }
865ac82fcf5Sdrh       break;
866ac82fcf5Sdrh     }
867c926afbcSdrh     default: {
868f46f905aSdrh       /* Do nothing */
869c926afbcSdrh       break;
870c926afbcSdrh     }
871c926afbcSdrh   }
8722d401ab8Sdrh   sqlite3ReleaseTempReg(pParse, regRow);
8732d401ab8Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
874ec7429aeSdrh 
875ec7429aeSdrh   /* Jump to the end of the loop when the LIMIT is reached
876ec7429aeSdrh   */
877ec7429aeSdrh   if( p->iLimit>=0 ){
8788558cde1Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
8793c84ddffSdrh     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, brk);
880ec7429aeSdrh   }
881ec7429aeSdrh 
882ec7429aeSdrh   /* The bottom of the loop
883ec7429aeSdrh   */
8840342b1f5Sdrh   sqlite3VdbeResolveLabel(v, cont);
88566a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
8860342b1f5Sdrh   sqlite3VdbeResolveLabel(v, brk);
887cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
88866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
889cdd536f0Sdrh   }
890cdd536f0Sdrh 
891d8bc7086Sdrh }
892d8bc7086Sdrh 
893d8bc7086Sdrh /*
894517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
895517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
896e78e8284Sdrh **
897955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the
898955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The
899955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
900955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The
901955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is
902955de52cSdanielk1977 ** considered a column by this function.
903e78e8284Sdrh **
904955de52cSdanielk1977 **   SELECT col FROM tbl;
905955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl;
906955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl);
907955de52cSdanielk1977 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
908955de52cSdanielk1977 **
909955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL.
910fcb78a49Sdrh */
911955de52cSdanielk1977 static const char *columnType(
912955de52cSdanielk1977   NameContext *pNC,
913955de52cSdanielk1977   Expr *pExpr,
914955de52cSdanielk1977   const char **pzOriginDb,
915955de52cSdanielk1977   const char **pzOriginTab,
916955de52cSdanielk1977   const char **pzOriginCol
917955de52cSdanielk1977 ){
918955de52cSdanielk1977   char const *zType = 0;
919955de52cSdanielk1977   char const *zOriginDb = 0;
920955de52cSdanielk1977   char const *zOriginTab = 0;
921955de52cSdanielk1977   char const *zOriginCol = 0;
922517eb646Sdanielk1977   int j;
923b3bce662Sdanielk1977   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
9245338a5f7Sdanielk1977 
92500e279d9Sdanielk1977   switch( pExpr->op ){
92630bcf5dbSdrh     case TK_AGG_COLUMN:
92700e279d9Sdanielk1977     case TK_COLUMN: {
928955de52cSdanielk1977       /* The expression is a column. Locate the table the column is being
929955de52cSdanielk1977       ** extracted from in NameContext.pSrcList. This table may be real
930955de52cSdanielk1977       ** database table or a subquery.
931955de52cSdanielk1977       */
932955de52cSdanielk1977       Table *pTab = 0;            /* Table structure column is extracted from */
933955de52cSdanielk1977       Select *pS = 0;             /* Select the column is extracted from */
934955de52cSdanielk1977       int iCol = pExpr->iColumn;  /* Index of column in pTab */
935b3bce662Sdanielk1977       while( pNC && !pTab ){
936b3bce662Sdanielk1977         SrcList *pTabList = pNC->pSrcList;
937b3bce662Sdanielk1977         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
938b3bce662Sdanielk1977         if( j<pTabList->nSrc ){
9396a3ea0e6Sdrh           pTab = pTabList->a[j].pTab;
940955de52cSdanielk1977           pS = pTabList->a[j].pSelect;
941b3bce662Sdanielk1977         }else{
942b3bce662Sdanielk1977           pNC = pNC->pNext;
943b3bce662Sdanielk1977         }
944b3bce662Sdanielk1977       }
945955de52cSdanielk1977 
9467e62779aSdrh       if( pTab==0 ){
9477e62779aSdrh         /* FIX ME:
9487e62779aSdrh         ** This can occurs if you have something like "SELECT new.x;" inside
9497e62779aSdrh         ** a trigger.  In other words, if you reference the special "new"
9507e62779aSdrh         ** table in the result set of a select.  We do not have a good way
9517e62779aSdrh         ** to find the actual table type, so call it "TEXT".  This is really
9527e62779aSdrh         ** something of a bug, but I do not know how to fix it.
9537e62779aSdrh         **
9547e62779aSdrh         ** This code does not produce the correct answer - it just prevents
9557e62779aSdrh         ** a segfault.  See ticket #1229.
9567e62779aSdrh         */
9577e62779aSdrh         zType = "TEXT";
9587e62779aSdrh         break;
9597e62779aSdrh       }
960955de52cSdanielk1977 
961b3bce662Sdanielk1977       assert( pTab );
962955de52cSdanielk1977       if( pS ){
963955de52cSdanielk1977         /* The "table" is actually a sub-select or a view in the FROM clause
964955de52cSdanielk1977         ** of the SELECT statement. Return the declaration type and origin
965955de52cSdanielk1977         ** data for the result-set column of the sub-select.
966955de52cSdanielk1977         */
967955de52cSdanielk1977         if( iCol>=0 && iCol<pS->pEList->nExpr ){
968955de52cSdanielk1977           /* If iCol is less than zero, then the expression requests the
969955de52cSdanielk1977           ** rowid of the sub-select or view. This expression is legal (see
970955de52cSdanielk1977           ** test case misc2.2.2) - it always evaluates to NULL.
971955de52cSdanielk1977           */
972955de52cSdanielk1977           NameContext sNC;
973955de52cSdanielk1977           Expr *p = pS->pEList->a[iCol].pExpr;
974955de52cSdanielk1977           sNC.pSrcList = pS->pSrc;
975955de52cSdanielk1977           sNC.pNext = 0;
976955de52cSdanielk1977           sNC.pParse = pNC->pParse;
977955de52cSdanielk1977           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
978955de52cSdanielk1977         }
9794b2688abSdanielk1977       }else if( pTab->pSchema ){
980955de52cSdanielk1977         /* A real table */
981955de52cSdanielk1977         assert( !pS );
982fcb78a49Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
983fcb78a49Sdrh         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
984fcb78a49Sdrh         if( iCol<0 ){
985fcb78a49Sdrh           zType = "INTEGER";
986955de52cSdanielk1977           zOriginCol = "rowid";
987fcb78a49Sdrh         }else{
988fcb78a49Sdrh           zType = pTab->aCol[iCol].zType;
989955de52cSdanielk1977           zOriginCol = pTab->aCol[iCol].zName;
990955de52cSdanielk1977         }
991955de52cSdanielk1977         zOriginTab = pTab->zName;
992955de52cSdanielk1977         if( pNC->pParse ){
993955de52cSdanielk1977           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
994955de52cSdanielk1977           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
995955de52cSdanielk1977         }
996fcb78a49Sdrh       }
99700e279d9Sdanielk1977       break;
998736c22b8Sdrh     }
99993758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
100000e279d9Sdanielk1977     case TK_SELECT: {
1001955de52cSdanielk1977       /* The expression is a sub-select. Return the declaration type and
1002955de52cSdanielk1977       ** origin info for the single column in the result set of the SELECT
1003955de52cSdanielk1977       ** statement.
1004955de52cSdanielk1977       */
1005b3bce662Sdanielk1977       NameContext sNC;
100600e279d9Sdanielk1977       Select *pS = pExpr->pSelect;
1007955de52cSdanielk1977       Expr *p = pS->pEList->a[0].pExpr;
1008955de52cSdanielk1977       sNC.pSrcList = pS->pSrc;
1009b3bce662Sdanielk1977       sNC.pNext = pNC;
1010955de52cSdanielk1977       sNC.pParse = pNC->pParse;
1011955de52cSdanielk1977       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
101200e279d9Sdanielk1977       break;
1013fcb78a49Sdrh     }
101493758c8dSdanielk1977 #endif
101500e279d9Sdanielk1977   }
101600e279d9Sdanielk1977 
1017955de52cSdanielk1977   if( pzOriginDb ){
1018955de52cSdanielk1977     assert( pzOriginTab && pzOriginCol );
1019955de52cSdanielk1977     *pzOriginDb = zOriginDb;
1020955de52cSdanielk1977     *pzOriginTab = zOriginTab;
1021955de52cSdanielk1977     *pzOriginCol = zOriginCol;
1022955de52cSdanielk1977   }
1023517eb646Sdanielk1977   return zType;
1024517eb646Sdanielk1977 }
1025517eb646Sdanielk1977 
1026517eb646Sdanielk1977 /*
1027517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
1028517eb646Sdanielk1977 ** in the result set.
1029517eb646Sdanielk1977 */
1030517eb646Sdanielk1977 static void generateColumnTypes(
1031517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
1032517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
1033517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
1034517eb646Sdanielk1977 ){
10353f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE
1036517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
1037517eb646Sdanielk1977   int i;
1038b3bce662Sdanielk1977   NameContext sNC;
1039b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
1040955de52cSdanielk1977   sNC.pParse = pParse;
1041517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
1042517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
10433f913576Sdrh     const char *zType;
10443f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1045955de52cSdanielk1977     const char *zOrigDb = 0;
1046955de52cSdanielk1977     const char *zOrigTab = 0;
1047955de52cSdanielk1977     const char *zOrigCol = 0;
10483f913576Sdrh     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
1049955de52cSdanielk1977 
105085b623f2Sdrh     /* The vdbe must make its own copy of the column-type and other
10514b1ae99dSdanielk1977     ** column specific strings, in case the schema is reset before this
10524b1ae99dSdanielk1977     ** virtual machine is deleted.
1053fbcd585fSdanielk1977     */
105466a5167bSdrh     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P4_TRANSIENT);
105566a5167bSdrh     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P4_TRANSIENT);
105666a5167bSdrh     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P4_TRANSIENT);
10573f913576Sdrh #else
10583f913576Sdrh     zType = columnType(&sNC, p, 0, 0, 0);
10593f913576Sdrh #endif
10603f913576Sdrh     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P4_TRANSIENT);
1061fcb78a49Sdrh   }
10623f913576Sdrh #endif /* SQLITE_OMIT_DECLTYPE */
1063fcb78a49Sdrh }
1064fcb78a49Sdrh 
1065fcb78a49Sdrh /*
1066fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
1067fcb78a49Sdrh ** in the result set.  This information is used to provide the
1068fcabd464Sdrh ** azCol[] values in the callback.
106982c3d636Sdrh */
1070832508b7Sdrh static void generateColumnNames(
1071832508b7Sdrh   Parse *pParse,      /* Parser context */
1072ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
1073832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
1074832508b7Sdrh ){
1075d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
10766a3ea0e6Sdrh   int i, j;
10779bb575fdSdrh   sqlite3 *db = pParse->db;
1078fcabd464Sdrh   int fullNames, shortNames;
1079fcabd464Sdrh 
1080fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN
10813cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
10823cf86063Sdanielk1977   if( pParse->explain ){
108361de0d1bSdanielk1977     return;
10843cf86063Sdanielk1977   }
10855338a5f7Sdanielk1977 #endif
10863cf86063Sdanielk1977 
1087d6502758Sdrh   assert( v!=0 );
108817435752Sdrh   if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
1089d8bc7086Sdrh   pParse->colNamesSet = 1;
1090fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
1091fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
109222322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
109382c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
109482c3d636Sdrh     Expr *p;
10955a38705eSdrh     p = pEList->a[i].pExpr;
10965a38705eSdrh     if( p==0 ) continue;
109782c3d636Sdrh     if( pEList->a[i].zName ){
109882c3d636Sdrh       char *zName = pEList->a[i].zName;
1099955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
110082c3d636Sdrh       continue;
110182c3d636Sdrh     }
1102fa173a76Sdrh     if( p->op==TK_COLUMN && pTabList ){
11036a3ea0e6Sdrh       Table *pTab;
110497665873Sdrh       char *zCol;
11058aff1015Sdrh       int iCol = p->iColumn;
11066a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
11076a3ea0e6Sdrh       assert( j<pTabList->nSrc );
11086a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
11098aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
111097665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1111b1363206Sdrh       if( iCol<0 ){
111247a6db2bSdrh         zCol = "rowid";
1113b1363206Sdrh       }else{
1114b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
1115b1363206Sdrh       }
1116fcabd464Sdrh       if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
1117955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
1118fcabd464Sdrh       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
111982c3d636Sdrh         char *zName = 0;
112082c3d636Sdrh         char *zTab;
112182c3d636Sdrh 
11226a3ea0e6Sdrh         zTab = pTabList->a[j].zAlias;
1123fcabd464Sdrh         if( fullNames || zTab==0 ) zTab = pTab->zName;
1124f93339deSdrh         sqlite3SetString(&zName, zTab, ".", zCol, (char*)0);
112566a5167bSdrh         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P4_DYNAMIC);
112682c3d636Sdrh       }else{
1127955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
112882c3d636Sdrh       }
11296977fea8Sdrh     }else if( p->span.z && p->span.z[0] ){
1130955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
11313cf86063Sdanielk1977       /* sqlite3VdbeCompressSpace(v, addr); */
11321bee3d7bSdrh     }else{
11331bee3d7bSdrh       char zName[30];
11341bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
11355bb3eb9bSdrh       sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1);
1136955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0);
113782c3d636Sdrh     }
113882c3d636Sdrh   }
113976d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
11405080aaa7Sdrh }
114182c3d636Sdrh 
114293758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
114382c3d636Sdrh /*
1144d8bc7086Sdrh ** Name of the connection operator, used for error messages.
1145d8bc7086Sdrh */
1146d8bc7086Sdrh static const char *selectOpName(int id){
1147d8bc7086Sdrh   char *z;
1148d8bc7086Sdrh   switch( id ){
1149d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
1150d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
1151d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
1152d8bc7086Sdrh     default:           z = "UNION";       break;
1153d8bc7086Sdrh   }
1154d8bc7086Sdrh   return z;
1155d8bc7086Sdrh }
115693758c8dSdanielk1977 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1157d8bc7086Sdrh 
1158d8bc7086Sdrh /*
1159315555caSdrh ** Forward declaration
1160315555caSdrh */
11619b3187e1Sdrh static int prepSelectStmt(Parse*, Select*);
1162315555caSdrh 
1163315555caSdrh /*
116422f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
116522f70c32Sdrh ** the result set of that SELECT.
116622f70c32Sdrh */
11674adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
116822f70c32Sdrh   Table *pTab;
1169b733d037Sdrh   int i, j;
117022f70c32Sdrh   ExprList *pEList;
1171290c1948Sdrh   Column *aCol, *pCol;
117217435752Sdrh   sqlite3 *db = pParse->db;
117322f70c32Sdrh 
117492378253Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
11759b3187e1Sdrh   if( prepSelectStmt(pParse, pSelect) ){
117622f70c32Sdrh     return 0;
117722f70c32Sdrh   }
1178142bdf40Sdanielk1977   if( sqlite3SelectResolve(pParse, pSelect, 0) ){
1179142bdf40Sdanielk1977     return 0;
1180142bdf40Sdanielk1977   }
118117435752Sdrh   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
118222f70c32Sdrh   if( pTab==0 ){
118322f70c32Sdrh     return 0;
118422f70c32Sdrh   }
1185ed8a3bb1Sdrh   pTab->nRef = 1;
118617435752Sdrh   pTab->zName = zTabName ? sqlite3DbStrDup(db, zTabName) : 0;
118722f70c32Sdrh   pEList = pSelect->pEList;
118822f70c32Sdrh   pTab->nCol = pEList->nExpr;
1189417be79cSdrh   assert( pTab->nCol>0 );
119017435752Sdrh   pTab->aCol = aCol = sqlite3DbMallocZero(db, sizeof(pTab->aCol[0])*pTab->nCol);
1191290c1948Sdrh   for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
119279d5f63fSdrh     Expr *p, *pR;
1193517eb646Sdanielk1977     char *zType;
119491bb0eedSdrh     char *zName;
11952564ef97Sdrh     int nName;
1196b3bf556eSdanielk1977     CollSeq *pColl;
119779d5f63fSdrh     int cnt;
1198b3bce662Sdanielk1977     NameContext sNC;
119979d5f63fSdrh 
120079d5f63fSdrh     /* Get an appropriate name for the column
120179d5f63fSdrh     */
120279d5f63fSdrh     p = pEList->a[i].pExpr;
1203290c1948Sdrh     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
120491bb0eedSdrh     if( (zName = pEList->a[i].zName)!=0 ){
120579d5f63fSdrh       /* If the column contains an "AS <name>" phrase, use <name> as the name */
120617435752Sdrh       zName = sqlite3DbStrDup(db, zName);
1207517eb646Sdanielk1977     }else if( p->op==TK_DOT
1208b733d037Sdrh               && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
120979d5f63fSdrh       /* For columns of the from A.B use B as the name */
121017435752Sdrh       zName = sqlite3MPrintf(db, "%T", &pR->token);
1211b733d037Sdrh     }else if( p->span.z && p->span.z[0] ){
121279d5f63fSdrh       /* Use the original text of the column expression as its name */
121317435752Sdrh       zName = sqlite3MPrintf(db, "%T", &p->span);
121422f70c32Sdrh     }else{
121579d5f63fSdrh       /* If all else fails, make up a name */
121617435752Sdrh       zName = sqlite3MPrintf(db, "column%d", i+1);
121722f70c32Sdrh     }
12187751940dSdanielk1977     if( !zName || db->mallocFailed ){
12197751940dSdanielk1977       db->mallocFailed = 1;
122017435752Sdrh       sqlite3_free(zName);
1221a04a34ffSdanielk1977       sqlite3DeleteTable(pTab);
1222dd5b2fa5Sdrh       return 0;
1223dd5b2fa5Sdrh     }
12247751940dSdanielk1977     sqlite3Dequote(zName);
122579d5f63fSdrh 
122679d5f63fSdrh     /* Make sure the column name is unique.  If the name is not unique,
122779d5f63fSdrh     ** append a integer to the name so that it becomes unique.
122879d5f63fSdrh     */
12292564ef97Sdrh     nName = strlen(zName);
123079d5f63fSdrh     for(j=cnt=0; j<i; j++){
123179d5f63fSdrh       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
12322564ef97Sdrh         zName[nName] = 0;
12331e536953Sdanielk1977         zName = sqlite3MPrintf(db, "%z:%d", zName, ++cnt);
123479d5f63fSdrh         j = -1;
1235dd5b2fa5Sdrh         if( zName==0 ) break;
123679d5f63fSdrh       }
123779d5f63fSdrh     }
123891bb0eedSdrh     pCol->zName = zName;
1239e014a838Sdanielk1977 
124079d5f63fSdrh     /* Get the typename, type affinity, and collating sequence for the
124179d5f63fSdrh     ** column.
124279d5f63fSdrh     */
1243c43e8be8Sdrh     memset(&sNC, 0, sizeof(sNC));
1244b3bce662Sdanielk1977     sNC.pSrcList = pSelect->pSrc;
124517435752Sdrh     zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
1246290c1948Sdrh     pCol->zType = zType;
1247c60e9b82Sdanielk1977     pCol->affinity = sqlite3ExprAffinity(p);
1248b3bf556eSdanielk1977     pColl = sqlite3ExprCollSeq(pParse, p);
1249b3bf556eSdanielk1977     if( pColl ){
125017435752Sdrh       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
12510202b29eSdanielk1977     }
125222f70c32Sdrh   }
125322f70c32Sdrh   pTab->iPKey = -1;
125422f70c32Sdrh   return pTab;
125522f70c32Sdrh }
125622f70c32Sdrh 
125722f70c32Sdrh /*
12589b3187e1Sdrh ** Prepare a SELECT statement for processing by doing the following
12599b3187e1Sdrh ** things:
1260d8bc7086Sdrh **
12619b3187e1Sdrh **    (1)  Make sure VDBE cursor numbers have been assigned to every
12629b3187e1Sdrh **         element of the FROM clause.
12639b3187e1Sdrh **
12649b3187e1Sdrh **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
12659b3187e1Sdrh **         defines FROM clause.  When views appear in the FROM clause,
126663eb5f29Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
126763eb5f29Sdrh **         that implements the view.  A copy is made of the view's SELECT
126863eb5f29Sdrh **         statement so that we can freely modify or delete that statement
126963eb5f29Sdrh **         without worrying about messing up the presistent representation
127063eb5f29Sdrh **         of the view.
1271d8bc7086Sdrh **
12729b3187e1Sdrh **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
1273ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
1274ad2d8307Sdrh **
12759b3187e1Sdrh **    (4)  Scan the list of columns in the result set (pEList) looking
127654473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
127754473229Sdrh **         If found, expand each "*" to be every column in every table
127854473229Sdrh **         and TABLE.* to be every column in TABLE.
1279d8bc7086Sdrh **
1280d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
1281d8bc7086Sdrh ** in pParse and return non-zero.
1282d8bc7086Sdrh */
12839b3187e1Sdrh static int prepSelectStmt(Parse *pParse, Select *p){
128454473229Sdrh   int i, j, k, rc;
1285ad3cab52Sdrh   SrcList *pTabList;
1286daffd0e5Sdrh   ExprList *pEList;
1287290c1948Sdrh   struct SrcList_item *pFrom;
128817435752Sdrh   sqlite3 *db = pParse->db;
1289daffd0e5Sdrh 
129017435752Sdrh   if( p==0 || p->pSrc==0 || db->mallocFailed ){
12916f7adc8aSdrh     return 1;
12926f7adc8aSdrh   }
1293daffd0e5Sdrh   pTabList = p->pSrc;
1294daffd0e5Sdrh   pEList = p->pEList;
1295d8bc7086Sdrh 
12969b3187e1Sdrh   /* Make sure cursor numbers have been assigned to all entries in
12979b3187e1Sdrh   ** the FROM clause of the SELECT statement.
12989b3187e1Sdrh   */
12999b3187e1Sdrh   sqlite3SrcListAssignCursors(pParse, p->pSrc);
13009b3187e1Sdrh 
13019b3187e1Sdrh   /* Look up every table named in the FROM clause of the select.  If
13029b3187e1Sdrh   ** an entry of the FROM clause is a subquery instead of a table or view,
13039b3187e1Sdrh   ** then create a transient table structure to describe the subquery.
1304d8bc7086Sdrh   */
1305290c1948Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1306f0113000Sdanielk1977     Table *pTab;
13079b3187e1Sdrh     if( pFrom->pTab!=0 ){
13089b3187e1Sdrh       /* This statement has already been prepared.  There is no need
13099b3187e1Sdrh       ** to go further. */
13109b3187e1Sdrh       assert( i==0 );
1311d8bc7086Sdrh       return 0;
1312d8bc7086Sdrh     }
1313290c1948Sdrh     if( pFrom->zName==0 ){
131493758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
131522f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
1316290c1948Sdrh       assert( pFrom->pSelect!=0 );
1317290c1948Sdrh       if( pFrom->zAlias==0 ){
131891bb0eedSdrh         pFrom->zAlias =
13191e536953Sdanielk1977           sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pFrom->pSelect);
1320ad2d8307Sdrh       }
1321ed8a3bb1Sdrh       assert( pFrom->pTab==0 );
1322290c1948Sdrh       pFrom->pTab = pTab =
1323290c1948Sdrh         sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
132422f70c32Sdrh       if( pTab==0 ){
1325daffd0e5Sdrh         return 1;
1326daffd0e5Sdrh       }
1327b9bb7c18Sdrh       /* The isEphem flag indicates that the Table structure has been
13285cf590c1Sdrh       ** dynamically allocated and may be freed at any time.  In other words,
13295cf590c1Sdrh       ** pTab is not pointing to a persistent table structure that defines
13305cf590c1Sdrh       ** part of the schema. */
1331b9bb7c18Sdrh       pTab->isEphem = 1;
133293758c8dSdanielk1977 #endif
133322f70c32Sdrh     }else{
1334a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
1335ed8a3bb1Sdrh       assert( pFrom->pTab==0 );
1336290c1948Sdrh       pFrom->pTab = pTab =
1337ca424114Sdrh         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
1338a76b5dfcSdrh       if( pTab==0 ){
1339d8bc7086Sdrh         return 1;
1340d8bc7086Sdrh       }
1341ed8a3bb1Sdrh       pTab->nRef++;
134293626f48Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
134393626f48Sdanielk1977       if( pTab->pSelect || IsVirtual(pTab) ){
134463eb5f29Sdrh         /* We reach here if the named table is a really a view */
13454adee20fSdanielk1977         if( sqlite3ViewGetColumnNames(pParse, pTab) ){
1346417be79cSdrh           return 1;
1347417be79cSdrh         }
1348290c1948Sdrh         /* If pFrom->pSelect!=0 it means we are dealing with a
134963eb5f29Sdrh         ** view within a view.  The SELECT structure has already been
135063eb5f29Sdrh         ** copied by the outer view so we can skip the copy step here
135163eb5f29Sdrh         ** in the inner view.
135263eb5f29Sdrh         */
1353290c1948Sdrh         if( pFrom->pSelect==0 ){
135417435752Sdrh           pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
1355a76b5dfcSdrh         }
1356d8bc7086Sdrh       }
135793758c8dSdanielk1977 #endif
135822f70c32Sdrh     }
135963eb5f29Sdrh   }
1360d8bc7086Sdrh 
1361ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
1362ad2d8307Sdrh   */
1363ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
1364ad2d8307Sdrh 
13657c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
136654473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
136754473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
13687c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
13697c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
13707c917d19Sdrh   ** each one to the list of all columns in all tables.
137154473229Sdrh   **
137254473229Sdrh   ** The first loop just checks to see if there are any "*" operators
137354473229Sdrh   ** that need expanding.
1374d8bc7086Sdrh   */
13757c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
137654473229Sdrh     Expr *pE = pEList->a[k].pExpr;
137754473229Sdrh     if( pE->op==TK_ALL ) break;
137854473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
137954473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
13807c917d19Sdrh   }
138154473229Sdrh   rc = 0;
13827c917d19Sdrh   if( k<pEList->nExpr ){
138354473229Sdrh     /*
138454473229Sdrh     ** If we get here it means the result set contains one or more "*"
138554473229Sdrh     ** operators that need to be expanded.  Loop through each expression
138654473229Sdrh     ** in the result set and expand them one by one.
138754473229Sdrh     */
13887c917d19Sdrh     struct ExprList_item *a = pEList->a;
13897c917d19Sdrh     ExprList *pNew = 0;
1390d70dc52dSdrh     int flags = pParse->db->flags;
1391d70dc52dSdrh     int longNames = (flags & SQLITE_FullColNames)!=0 &&
1392d70dc52dSdrh                       (flags & SQLITE_ShortColNames)==0;
1393d70dc52dSdrh 
13947c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
139554473229Sdrh       Expr *pE = a[k].pExpr;
139654473229Sdrh       if( pE->op!=TK_ALL &&
139754473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
139854473229Sdrh         /* This particular expression does not need to be expanded.
139954473229Sdrh         */
140017435752Sdrh         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
1401261919ccSdanielk1977         if( pNew ){
14027c917d19Sdrh           pNew->a[pNew->nExpr-1].zName = a[k].zName;
1403261919ccSdanielk1977         }else{
1404261919ccSdanielk1977           rc = 1;
1405261919ccSdanielk1977         }
14067c917d19Sdrh         a[k].pExpr = 0;
14077c917d19Sdrh         a[k].zName = 0;
14087c917d19Sdrh       }else{
140954473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
141054473229Sdrh         ** expanded. */
141154473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
1412cf55b7aeSdrh         char *zTName;            /* text of name of TABLE */
141354473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
141417435752Sdrh           zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
141554473229Sdrh         }else{
1416cf55b7aeSdrh           zTName = 0;
141754473229Sdrh         }
1418290c1948Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1419290c1948Sdrh           Table *pTab = pFrom->pTab;
1420290c1948Sdrh           char *zTabName = pFrom->zAlias;
142154473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
142254473229Sdrh             zTabName = pTab->zName;
142354473229Sdrh           }
1424cf55b7aeSdrh           if( zTName && (zTabName==0 || zTabName[0]==0 ||
1425cf55b7aeSdrh                  sqlite3StrICmp(zTName, zTabName)!=0) ){
142654473229Sdrh             continue;
142754473229Sdrh           }
142854473229Sdrh           tableSeen = 1;
1429d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
1430f0113000Sdanielk1977             Expr *pExpr, *pRight;
1431ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
1432ad2d8307Sdrh 
1433034ca14fSdanielk1977             /* If a column is marked as 'hidden' (currently only possible
1434034ca14fSdanielk1977             ** for virtual tables), do not include it in the expanded
1435034ca14fSdanielk1977             ** result-set list.
1436034ca14fSdanielk1977             */
1437034ca14fSdanielk1977             if( IsHiddenColumn(&pTab->aCol[j]) ){
1438034ca14fSdanielk1977               assert(IsVirtual(pTab));
1439034ca14fSdanielk1977               continue;
1440034ca14fSdanielk1977             }
1441034ca14fSdanielk1977 
144291bb0eedSdrh             if( i>0 ){
144391bb0eedSdrh               struct SrcList_item *pLeft = &pTabList->a[i-1];
144461dfc31dSdrh               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
144591bb0eedSdrh                         columnIndex(pLeft->pTab, zName)>=0 ){
1446ad2d8307Sdrh                 /* In a NATURAL join, omit the join columns from the
1447ad2d8307Sdrh                 ** table on the right */
1448ad2d8307Sdrh                 continue;
1449ad2d8307Sdrh               }
145061dfc31dSdrh               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
1451ad2d8307Sdrh                 /* In a join with a USING clause, omit columns in the
1452ad2d8307Sdrh                 ** using clause from the table on the right. */
1453ad2d8307Sdrh                 continue;
1454ad2d8307Sdrh               }
145591bb0eedSdrh             }
1456a1644fd8Sdanielk1977             pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
145722f70c32Sdrh             if( pRight==0 ) break;
14581e536953Sdanielk1977             setQuotedToken(pParse, &pRight->token, zName);
1459d70dc52dSdrh             if( zTabName && (longNames || pTabList->nSrc>1) ){
1460a1644fd8Sdanielk1977               Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
1461a1644fd8Sdanielk1977               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
146222f70c32Sdrh               if( pExpr==0 ) break;
14631e536953Sdanielk1977               setQuotedToken(pParse, &pLeft->token, zTabName);
14641e536953Sdanielk1977               setToken(&pExpr->span,
14651e536953Sdanielk1977                   sqlite3MPrintf(db, "%s.%s", zTabName, zName));
14666977fea8Sdrh               pExpr->span.dyn = 1;
14676977fea8Sdrh               pExpr->token.z = 0;
14686977fea8Sdrh               pExpr->token.n = 0;
14696977fea8Sdrh               pExpr->token.dyn = 0;
147022f70c32Sdrh             }else{
147122f70c32Sdrh               pExpr = pRight;
14726977fea8Sdrh               pExpr->span = pExpr->token;
1473f3b863edSdanielk1977               pExpr->span.dyn = 0;
147422f70c32Sdrh             }
1475d70dc52dSdrh             if( longNames ){
147617435752Sdrh               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
1477d70dc52dSdrh             }else{
147817435752Sdrh               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
1479d8bc7086Sdrh             }
1480d8bc7086Sdrh           }
1481d70dc52dSdrh         }
148254473229Sdrh         if( !tableSeen ){
1483cf55b7aeSdrh           if( zTName ){
1484cf55b7aeSdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
1485f5db2d3eSdrh           }else{
14864adee20fSdanielk1977             sqlite3ErrorMsg(pParse, "no tables specified");
1487f5db2d3eSdrh           }
148854473229Sdrh           rc = 1;
148954473229Sdrh         }
149017435752Sdrh         sqlite3_free(zTName);
14917c917d19Sdrh       }
14927c917d19Sdrh     }
14934adee20fSdanielk1977     sqlite3ExprListDelete(pEList);
14947c917d19Sdrh     p->pEList = pNew;
1495d8bc7086Sdrh   }
1496bb4957f8Sdrh #if SQLITE_MAX_COLUMN
1497bb4957f8Sdrh   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1498e5c941b8Sdrh     sqlite3ErrorMsg(pParse, "too many columns in result set");
1499e5c941b8Sdrh     rc = SQLITE_ERROR;
1500e5c941b8Sdrh   }
1501bb4957f8Sdrh #endif
150217435752Sdrh   if( db->mallocFailed ){
1503f3b863edSdanielk1977     rc = SQLITE_NOMEM;
1504f3b863edSdanielk1977   }
150554473229Sdrh   return rc;
1506d8bc7086Sdrh }
1507d8bc7086Sdrh 
1508ff78bd2fSdrh /*
15099a99334dSdrh ** pE is a pointer to an expression which is a single term in
15109a99334dSdrh ** ORDER BY or GROUP BY clause.
1511d8bc7086Sdrh **
15129a99334dSdrh ** If pE evaluates to an integer constant i, then return i.
15139a99334dSdrh ** This is an indication to the caller that it should sort
15149a99334dSdrh ** by the i-th column of the result set.
15159a99334dSdrh **
15169a99334dSdrh ** If pE is a well-formed expression and the SELECT statement
15179a99334dSdrh ** is not compound, then return 0.  This indicates to the
15189a99334dSdrh ** caller that it should sort by the value of the ORDER BY
15199a99334dSdrh ** expression.
15209a99334dSdrh **
15219a99334dSdrh ** If the SELECT is compound, then attempt to match pE against
15229a99334dSdrh ** result set columns in the left-most SELECT statement.  Return
15239a99334dSdrh ** the index i of the matching column, as an indication to the
15249a99334dSdrh ** caller that it should sort by the i-th column.  If there is
15259a99334dSdrh ** no match, return -1 and leave an error message in pParse.
1526d8bc7086Sdrh */
15279a99334dSdrh static int matchOrderByTermToExprList(
15289a99334dSdrh   Parse *pParse,     /* Parsing context for error messages */
15299a99334dSdrh   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
15309a99334dSdrh   Expr *pE,          /* The specific ORDER BY term */
15319a99334dSdrh   int idx,           /* When ORDER BY term is this */
15329a99334dSdrh   int isCompound,    /* True if this is a compound SELECT */
15339a99334dSdrh   u8 *pHasAgg        /* True if expression contains aggregate functions */
1534d8bc7086Sdrh ){
15359a99334dSdrh   int i;             /* Loop counter */
15369a99334dSdrh   ExprList *pEList;  /* The columns of the result set */
15379a99334dSdrh   NameContext nc;    /* Name context for resolving pE */
15389a99334dSdrh 
15399a99334dSdrh 
15409a99334dSdrh   /* If the term is an integer constant, return the value of that
15419a99334dSdrh   ** constant */
15429a99334dSdrh   pEList = pSelect->pEList;
15439a99334dSdrh   if( sqlite3ExprIsInteger(pE, &i) ){
15449a99334dSdrh     if( i<=0 ){
15459a99334dSdrh       /* If i is too small, make it too big.  That way the calling
15469a99334dSdrh       ** function still sees a value that is out of range, but does
15479a99334dSdrh       ** not confuse the column number with 0 or -1 result code.
15489a99334dSdrh       */
15499a99334dSdrh       i = pEList->nExpr+1;
15509a99334dSdrh     }
15519a99334dSdrh     return i;
15529a99334dSdrh   }
15539a99334dSdrh 
15549a99334dSdrh   /* If the term is a simple identifier that try to match that identifier
15559a99334dSdrh   ** against a column name in the result set.
15569a99334dSdrh   */
15579a99334dSdrh   if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){
155817435752Sdrh     sqlite3 *db = pParse->db;
15599a99334dSdrh     char *zCol = sqlite3NameFromToken(db, &pE->token);
1560ef0bea92Sdrh     if( zCol==0 ){
15619a99334dSdrh       return -1;
15629a99334dSdrh     }
15639a99334dSdrh     for(i=0; i<pEList->nExpr; i++){
15649a99334dSdrh       char *zAs = pEList->a[i].zName;
15659a99334dSdrh       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
15669a99334dSdrh         sqlite3_free(zCol);
15679a99334dSdrh         return i+1;
15689a99334dSdrh       }
15699a99334dSdrh     }
15709a99334dSdrh     sqlite3_free(zCol);
15714c774314Sdrh   }
157270517ab9Sdanielk1977 
15739a99334dSdrh   /* Resolve all names in the ORDER BY term expression
15749a99334dSdrh   */
157570517ab9Sdanielk1977   memset(&nc, 0, sizeof(nc));
157670517ab9Sdanielk1977   nc.pParse = pParse;
15779a99334dSdrh   nc.pSrcList = pSelect->pSrc;
157870517ab9Sdanielk1977   nc.pEList = pEList;
157970517ab9Sdanielk1977   nc.allowAgg = 1;
15804c774314Sdrh   nc.nErr = 0;
15819a99334dSdrh   if( sqlite3ExprResolveNames(&nc, pE) ){
15821e281291Sdrh     if( isCompound ){
15831e281291Sdrh       sqlite3ErrorClear(pParse);
15841e281291Sdrh       return 0;
15851e281291Sdrh     }else{
15869a99334dSdrh       return -1;
15879a99334dSdrh     }
15881e281291Sdrh   }
15899a99334dSdrh   if( nc.hasAgg && pHasAgg ){
15909a99334dSdrh     *pHasAgg = 1;
15919a99334dSdrh   }
15929a99334dSdrh 
15939a99334dSdrh   /* For a compound SELECT, we need to try to match the ORDER BY
15949a99334dSdrh   ** expression against an expression in the result set
15959a99334dSdrh   */
15969a99334dSdrh   if( isCompound ){
15979a99334dSdrh     for(i=0; i<pEList->nExpr; i++){
15989a99334dSdrh       if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
15999a99334dSdrh         return i+1;
16009a99334dSdrh       }
16019a99334dSdrh     }
16024c774314Sdrh   }
16031e281291Sdrh   return 0;
160470517ab9Sdanielk1977 }
160570517ab9Sdanielk1977 
16069a99334dSdrh 
16079a99334dSdrh /*
16089a99334dSdrh ** Analyze and ORDER BY or GROUP BY clause in a simple SELECT statement.
16099a99334dSdrh ** Return the number of errors seen.
16109a99334dSdrh **
16119a99334dSdrh ** Every term of the ORDER BY or GROUP BY clause needs to be an
16129a99334dSdrh ** expression.  If any expression is an integer constant, then
16139a99334dSdrh ** that expression is replaced by the corresponding
16149a99334dSdrh ** expression from the result set.
16159a99334dSdrh */
16169a99334dSdrh static int processOrderGroupBy(
16179a99334dSdrh   Parse *pParse,        /* Parsing context.  Leave error messages here */
16189a99334dSdrh   Select *pSelect,      /* The SELECT statement containing the clause */
16199a99334dSdrh   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
16209a99334dSdrh   int isOrder,          /* 1 for ORDER BY.  0 for GROUP BY */
16219a99334dSdrh   u8 *pHasAgg           /* Set to TRUE if any term contains an aggregate */
16229a99334dSdrh ){
16239a99334dSdrh   int i;
16249a99334dSdrh   sqlite3 *db = pParse->db;
16259a99334dSdrh   ExprList *pEList;
16269a99334dSdrh 
162715cdbebeSdanielk1977   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
1628bb4957f8Sdrh #if SQLITE_MAX_COLUMN
1629bb4957f8Sdrh   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
16309a99334dSdrh     const char *zType = isOrder ? "ORDER" : "GROUP";
16319a99334dSdrh     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
16329a99334dSdrh     return 1;
16339a99334dSdrh   }
1634bb4957f8Sdrh #endif
16359a99334dSdrh   pEList = pSelect->pEList;
16369a99334dSdrh   if( pEList==0 ){
16379a99334dSdrh     return 0;
16389a99334dSdrh   }
16399a99334dSdrh   for(i=0; i<pOrderBy->nExpr; i++){
16409a99334dSdrh     int iCol;
16419a99334dSdrh     Expr *pE = pOrderBy->a[i].pExpr;
16429a99334dSdrh     iCol = matchOrderByTermToExprList(pParse, pSelect, pE, i+1, 0, pHasAgg);
164370517ab9Sdanielk1977     if( iCol<0 ){
16449a99334dSdrh       return 1;
16459a99334dSdrh     }
16469a99334dSdrh     if( iCol>pEList->nExpr ){
16479a99334dSdrh       const char *zType = isOrder ? "ORDER" : "GROUP";
164870517ab9Sdanielk1977       sqlite3ErrorMsg(pParse,
16499a99334dSdrh          "%r %s BY term out of range - should be "
16509a99334dSdrh          "between 1 and %d", i+1, zType, pEList->nExpr);
16519a99334dSdrh       return 1;
16529a99334dSdrh     }
16539a99334dSdrh     if( iCol>0 ){
16549a99334dSdrh       CollSeq *pColl = pE->pColl;
16559a99334dSdrh       int flags = pE->flags & EP_ExpCollate;
16569a99334dSdrh       sqlite3ExprDelete(pE);
16579a99334dSdrh       pE = sqlite3ExprDup(db, pEList->a[iCol-1].pExpr);
16589a99334dSdrh       pOrderBy->a[i].pExpr = pE;
165915cdbebeSdanielk1977       if( pE && pColl && flags ){
16609a99334dSdrh         pE->pColl = pColl;
16619a99334dSdrh         pE->flags |= flags;
16629a99334dSdrh       }
16639a99334dSdrh     }
16649a99334dSdrh   }
16659a99334dSdrh   return 0;
16669a99334dSdrh }
16679a99334dSdrh 
16689a99334dSdrh /*
16699a99334dSdrh ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement.  Return
16709a99334dSdrh ** the number of errors seen.
16719a99334dSdrh **
16729a99334dSdrh ** The processing depends on whether the SELECT is simple or compound.
16739a99334dSdrh ** For a simple SELECT statement, evry term of the ORDER BY or GROUP BY
16749a99334dSdrh ** clause needs to be an expression.  If any expression is an integer
16759a99334dSdrh ** constant, then that expression is replaced by the corresponding
16769a99334dSdrh ** expression from the result set.
16779a99334dSdrh **
16789a99334dSdrh ** For compound SELECT statements, every expression needs to be of
16799a99334dSdrh ** type TK_COLUMN with a iTable value as given in the 4th parameter.
16809a99334dSdrh ** If any expression is an integer, that becomes the column number.
16819a99334dSdrh ** Otherwise, match the expression against result set columns from
16829a99334dSdrh ** the left-most SELECT.
16839a99334dSdrh */
16849a99334dSdrh static int processCompoundOrderBy(
16859a99334dSdrh   Parse *pParse,        /* Parsing context.  Leave error messages here */
16869a99334dSdrh   Select *pSelect,      /* The SELECT statement containing the ORDER BY */
16879a99334dSdrh   int iTable            /* Output table for compound SELECT statements */
16889a99334dSdrh ){
16899a99334dSdrh   int i;
16909a99334dSdrh   ExprList *pOrderBy;
16919a99334dSdrh   ExprList *pEList;
16921e281291Sdrh   sqlite3 *db;
16931e281291Sdrh   int moreToDo = 1;
16949a99334dSdrh 
16959a99334dSdrh   pOrderBy = pSelect->pOrderBy;
16969a99334dSdrh   if( pOrderBy==0 ) return 0;
1697bb4957f8Sdrh   db = pParse->db;
1698bb4957f8Sdrh #if SQLITE_MAX_COLUMN
1699bb4957f8Sdrh   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
17009a99334dSdrh     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
17019a99334dSdrh     return 1;
17029a99334dSdrh   }
1703bb4957f8Sdrh #endif
17041e281291Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
17051e281291Sdrh     pOrderBy->a[i].done = 0;
17061e281291Sdrh   }
17079a99334dSdrh   while( pSelect->pPrior ){
17089a99334dSdrh     pSelect = pSelect->pPrior;
17099a99334dSdrh   }
17101e281291Sdrh   while( pSelect && moreToDo ){
17111e281291Sdrh     moreToDo = 0;
17129a99334dSdrh     for(i=0; i<pOrderBy->nExpr; i++){
1713ac559264Sdanielk1977       int iCol = -1;
17148f0ecaaeSdrh       Expr *pE, *pDup;
17151e281291Sdrh       if( pOrderBy->a[i].done ) continue;
17161e281291Sdrh       pE = pOrderBy->a[i].pExpr;
17178f0ecaaeSdrh       pDup = sqlite3ExprDup(db, pE);
1718ac559264Sdanielk1977       if( !db->mallocFailed ){
1719ac559264Sdanielk1977         assert(pDup);
17201e281291Sdrh         iCol = matchOrderByTermToExprList(pParse, pSelect, pDup, i+1, 1, 0);
1721ac559264Sdanielk1977       }
17221e281291Sdrh       sqlite3ExprDelete(pDup);
17239a99334dSdrh       if( iCol<0 ){
17249a99334dSdrh         return 1;
17259a99334dSdrh       }
17261e281291Sdrh       pEList = pSelect->pEList;
17271e281291Sdrh       if( pEList==0 ){
17281e281291Sdrh         return 1;
17291e281291Sdrh       }
17309a99334dSdrh       if( iCol>pEList->nExpr ){
17319a99334dSdrh         sqlite3ErrorMsg(pParse,
17329a99334dSdrh            "%r ORDER BY term out of range - should be "
17339a99334dSdrh            "between 1 and %d", i+1, pEList->nExpr);
17349a99334dSdrh         return 1;
17359a99334dSdrh       }
17361e281291Sdrh       if( iCol>0 ){
1737967e8b73Sdrh         pE->op = TK_COLUMN;
1738d8bc7086Sdrh         pE->iTable = iTable;
1739a58fdfb1Sdanielk1977         pE->iAgg = -1;
17409a99334dSdrh         pE->iColumn = iCol-1;
17419a99334dSdrh         pE->pTab = 0;
17421e281291Sdrh         pOrderBy->a[i].done = 1;
17431e281291Sdrh       }else{
17441e281291Sdrh         moreToDo = 1;
17451e281291Sdrh       }
17461e281291Sdrh     }
17471e281291Sdrh     pSelect = pSelect->pNext;
17481e281291Sdrh   }
17491e281291Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
17501e281291Sdrh     if( pOrderBy->a[i].done==0 ){
17511e281291Sdrh       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
17521e281291Sdrh             "column in the result set", i+1);
17531e281291Sdrh       return 1;
17541e281291Sdrh     }
175570517ab9Sdanielk1977   }
17569a99334dSdrh   return 0;
1757d8bc7086Sdrh }
1758d8bc7086Sdrh 
1759d8bc7086Sdrh /*
1760d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1761d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1762d8bc7086Sdrh */
17634adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1764d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1765d8bc7086Sdrh   if( v==0 ){
17664adee20fSdanielk1977     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1767949f9cd5Sdrh #ifndef SQLITE_OMIT_TRACE
1768949f9cd5Sdrh     if( v ){
1769949f9cd5Sdrh       sqlite3VdbeAddOp0(v, OP_Trace);
1770949f9cd5Sdrh     }
1771949f9cd5Sdrh #endif
1772d8bc7086Sdrh   }
1773d8bc7086Sdrh   return v;
1774d8bc7086Sdrh }
1775d8bc7086Sdrh 
177615007a99Sdrh 
1777d8bc7086Sdrh /*
17787b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
1779ec7429aeSdrh ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
17807b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
1781a2dc3b1aSdanielk1977 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1782a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute
1783a2dc3b1aSdanielk1977 ** the limit and offset.  If there is no limit and/or offset, then
1784a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative.
17857b58daeaSdrh **
1786d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if
1787ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset.  iLimit and
17887b58daeaSdrh ** iOffset should have been preset to appropriate default values
17897b58daeaSdrh ** (usually but not always -1) prior to calling this routine.
1790ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
17917b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
17927b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
17937b58daeaSdrh ** SELECT statements.
17947b58daeaSdrh */
1795ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
179602afc861Sdrh   Vdbe *v = 0;
179702afc861Sdrh   int iLimit = 0;
179815007a99Sdrh   int iOffset;
1799b7654111Sdrh   int addr1;
180015007a99Sdrh 
18017b58daeaSdrh   /*
18027b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
18037b58daeaSdrh   ** contraversy about what the correct behavior should be.
18047b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
18057b58daeaSdrh   ** no rows.
18067b58daeaSdrh   */
1807a2dc3b1aSdanielk1977   if( p->pLimit ){
18080a07c107Sdrh     p->iLimit = iLimit = ++pParse->nMem;
180915007a99Sdrh     v = sqlite3GetVdbe(pParse);
18107b58daeaSdrh     if( v==0 ) return;
1811b7654111Sdrh     sqlite3ExprCode(pParse, p->pLimit, iLimit);
1812b7654111Sdrh     sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
1813d4e70ebdSdrh     VdbeComment((v, "LIMIT counter"));
18143c84ddffSdrh     sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
18157b58daeaSdrh   }
1816a2dc3b1aSdanielk1977   if( p->pOffset ){
18170a07c107Sdrh     p->iOffset = iOffset = ++pParse->nMem;
1818b7654111Sdrh     if( p->pLimit ){
1819b7654111Sdrh       pParse->nMem++;   /* Allocate an extra register for limit+offset */
1820b7654111Sdrh     }
182115007a99Sdrh     v = sqlite3GetVdbe(pParse);
18227b58daeaSdrh     if( v==0 ) return;
1823b7654111Sdrh     sqlite3ExprCode(pParse, p->pOffset, iOffset);
1824b7654111Sdrh     sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
1825d4e70ebdSdrh     VdbeComment((v, "OFFSET counter"));
18263c84ddffSdrh     addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
1827b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
182815007a99Sdrh     sqlite3VdbeJumpHere(v, addr1);
1829d59ba6ceSdrh     if( p->pLimit ){
1830b7654111Sdrh       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
1831d4e70ebdSdrh       VdbeComment((v, "LIMIT+OFFSET"));
1832b7654111Sdrh       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
1833b7654111Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
1834b7654111Sdrh       sqlite3VdbeJumpHere(v, addr1);
1835b7654111Sdrh     }
1836d59ba6ceSdrh   }
18377b58daeaSdrh }
18387b58daeaSdrh 
18397b58daeaSdrh /*
18400342b1f5Sdrh ** Allocate a virtual index to use for sorting.
1841d3d39e93Sdrh */
18424db38a70Sdrh static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
18430342b1f5Sdrh   if( pOrderBy ){
1844dc1bdc4fSdanielk1977     int addr;
18459d2985c7Sdrh     assert( pOrderBy->iECursor==0 );
18469d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
184766a5167bSdrh     addr = sqlite3VdbeAddOp2(pParse->pVdbe, OP_OpenEphemeral,
18489d2985c7Sdrh                             pOrderBy->iECursor, pOrderBy->nExpr+1);
1849b9bb7c18Sdrh     assert( p->addrOpenEphm[2] == -1 );
1850b9bb7c18Sdrh     p->addrOpenEphm[2] = addr;
1851736c22b8Sdrh   }
1852dc1bdc4fSdanielk1977 }
1853dc1bdc4fSdanielk1977 
1854b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1855fbc4ee7bSdrh /*
1856fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
1857fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
1858fbc4ee7bSdrh ** the column has no default collating sequence.
1859fbc4ee7bSdrh **
1860fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
1861fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
1862fbc4ee7bSdrh */
1863dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1864fbc4ee7bSdrh   CollSeq *pRet;
1865dc1bdc4fSdanielk1977   if( p->pPrior ){
1866dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1867fbc4ee7bSdrh   }else{
1868fbc4ee7bSdrh     pRet = 0;
1869dc1bdc4fSdanielk1977   }
1870fbc4ee7bSdrh   if( pRet==0 ){
1871dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1872dc1bdc4fSdanielk1977   }
1873dc1bdc4fSdanielk1977   return pRet;
1874d3d39e93Sdrh }
1875b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1876d3d39e93Sdrh 
1877b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1878d3d39e93Sdrh /*
187982c3d636Sdrh ** This routine is called to process a query that is really the union
188082c3d636Sdrh ** or intersection of two or more separate queries.
1881c926afbcSdrh **
1882e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1883e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1884e78e8284Sdrh ** in which case this routine will be called recursively.
1885e78e8284Sdrh **
1886e78e8284Sdrh ** The results of the total query are to be written into a destination
1887e78e8284Sdrh ** of type eDest with parameter iParm.
1888e78e8284Sdrh **
1889e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1890e78e8284Sdrh **
1891e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1892e78e8284Sdrh **
1893e78e8284Sdrh ** This statement is parsed up as follows:
1894e78e8284Sdrh **
1895e78e8284Sdrh **     SELECT c FROM t3
1896e78e8284Sdrh **      |
1897e78e8284Sdrh **      `----->  SELECT b FROM t2
1898e78e8284Sdrh **                |
18994b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1900e78e8284Sdrh **
1901e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1902e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1903e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1904e78e8284Sdrh **
1905e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1906e78e8284Sdrh ** individual selects always group from left to right.
190782c3d636Sdrh */
190884ac9d02Sdanielk1977 static int multiSelect(
1909fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
1910fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
19116c8c8ce0Sdanielk1977   SelectDest *pDest,    /* What to do with query results */
191284ac9d02Sdanielk1977   char *aff             /* If eDest is SRT_Union, the affinity string */
191384ac9d02Sdanielk1977 ){
191484ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
191510e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
191610e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
19178cdbf836Sdrh   int nCol;             /* Number of columns in the result set */
19180342b1f5Sdrh   ExprList *pOrderBy;   /* The ORDER BY clause on p */
19190342b1f5Sdrh   int aSetP2[2];        /* Set P2 value of these op to number of columns */
19200342b1f5Sdrh   int nSetP2 = 0;       /* Number of slots in aSetP2[] used */
19211013c932Sdrh   SelectDest dest;      /* Alternative data destination */
192282c3d636Sdrh 
19231013c932Sdrh   dest = *pDest;
19246c8c8ce0Sdanielk1977 
19257b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1926fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
192782c3d636Sdrh   */
192884ac9d02Sdanielk1977   if( p==0 || p->pPrior==0 ){
192984ac9d02Sdanielk1977     rc = 1;
193084ac9d02Sdanielk1977     goto multi_select_end;
193184ac9d02Sdanielk1977   }
1932d8bc7086Sdrh   pPrior = p->pPrior;
19330342b1f5Sdrh   assert( pPrior->pRightmost!=pPrior );
19340342b1f5Sdrh   assert( pPrior->pRightmost==p->pRightmost );
1935d8bc7086Sdrh   if( pPrior->pOrderBy ){
19364adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1937da93d238Sdrh       selectOpName(p->op));
193884ac9d02Sdanielk1977     rc = 1;
193984ac9d02Sdanielk1977     goto multi_select_end;
194082c3d636Sdrh   }
1941a2dc3b1aSdanielk1977   if( pPrior->pLimit ){
19424adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
19437b58daeaSdrh       selectOpName(p->op));
194484ac9d02Sdanielk1977     rc = 1;
194584ac9d02Sdanielk1977     goto multi_select_end;
19467b58daeaSdrh   }
194782c3d636Sdrh 
1948d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
1949d8bc7086Sdrh   */
19504adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
195184ac9d02Sdanielk1977   if( v==0 ){
195284ac9d02Sdanielk1977     rc = 1;
195384ac9d02Sdanielk1977     goto multi_select_end;
195484ac9d02Sdanielk1977   }
1955d8bc7086Sdrh 
19561cc3d75fSdrh   /* Create the destination temporary table if necessary
19571cc3d75fSdrh   */
19586c8c8ce0Sdanielk1977   if( dest.eDest==SRT_EphemTab ){
1959b4964b72Sdanielk1977     assert( p->pEList );
19600342b1f5Sdrh     assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
196166a5167bSdrh     aSetP2[nSetP2++] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, 0);
19626c8c8ce0Sdanielk1977     dest.eDest = SRT_Table;
19631cc3d75fSdrh   }
19641cc3d75fSdrh 
1965f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1966d8bc7086Sdrh   */
19670342b1f5Sdrh   pOrderBy = p->pOrderBy;
196882c3d636Sdrh   switch( p->op ){
1969f46f905aSdrh     case TK_ALL: {
19700342b1f5Sdrh       if( pOrderBy==0 ){
1971ec7429aeSdrh         int addr = 0;
1972a2dc3b1aSdanielk1977         assert( !pPrior->pLimit );
1973a2dc3b1aSdanielk1977         pPrior->pLimit = p->pLimit;
1974a2dc3b1aSdanielk1977         pPrior->pOffset = p->pOffset;
19756c8c8ce0Sdanielk1977         rc = sqlite3Select(pParse, pPrior, &dest, 0, 0, 0, aff);
1976ad68cb6bSdanielk1977         p->pLimit = 0;
1977ad68cb6bSdanielk1977         p->pOffset = 0;
197884ac9d02Sdanielk1977         if( rc ){
197984ac9d02Sdanielk1977           goto multi_select_end;
198084ac9d02Sdanielk1977         }
1981f46f905aSdrh         p->pPrior = 0;
19827b58daeaSdrh         p->iLimit = pPrior->iLimit;
19837b58daeaSdrh         p->iOffset = pPrior->iOffset;
1984ec7429aeSdrh         if( p->iLimit>=0 ){
19853c84ddffSdrh           addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
1986d4e70ebdSdrh           VdbeComment((v, "Jump ahead if LIMIT reached"));
1987ec7429aeSdrh         }
19886c8c8ce0Sdanielk1977         rc = sqlite3Select(pParse, p, &dest, 0, 0, 0, aff);
1989f46f905aSdrh         p->pPrior = pPrior;
199084ac9d02Sdanielk1977         if( rc ){
199184ac9d02Sdanielk1977           goto multi_select_end;
199284ac9d02Sdanielk1977         }
1993ec7429aeSdrh         if( addr ){
1994ec7429aeSdrh           sqlite3VdbeJumpHere(v, addr);
1995ec7429aeSdrh         }
1996f46f905aSdrh         break;
1997f46f905aSdrh       }
1998f46f905aSdrh       /* For UNION ALL ... ORDER BY fall through to the next case */
1999f46f905aSdrh     }
200082c3d636Sdrh     case TK_EXCEPT:
200182c3d636Sdrh     case TK_UNION: {
2002d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
2003742f947bSdanielk1977       int op = 0;      /* One of the SRT_ operations to apply to self */
2004d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
2005a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
2006dc1bdc4fSdanielk1977       int addr;
20076c8c8ce0Sdanielk1977       SelectDest uniondest;
200882c3d636Sdrh 
2009d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
20106c8c8ce0Sdanielk1977       if( dest.eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
2011d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
2012c926afbcSdrh         ** right.
2013d8bc7086Sdrh         */
20146c8c8ce0Sdanielk1977         unionTab = dest.iParm;
201582c3d636Sdrh       }else{
2016d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
2017d8bc7086Sdrh         ** intermediate results.
2018d8bc7086Sdrh         */
201982c3d636Sdrh         unionTab = pParse->nTab++;
20209a99334dSdrh         if( processCompoundOrderBy(pParse, p, unionTab) ){
202184ac9d02Sdanielk1977           rc = 1;
202284ac9d02Sdanielk1977           goto multi_select_end;
2023d8bc7086Sdrh         }
202466a5167bSdrh         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
20250342b1f5Sdrh         if( priorOp==SRT_Table ){
20260342b1f5Sdrh           assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
20270342b1f5Sdrh           aSetP2[nSetP2++] = addr;
20280342b1f5Sdrh         }else{
2029b9bb7c18Sdrh           assert( p->addrOpenEphm[0] == -1 );
2030b9bb7c18Sdrh           p->addrOpenEphm[0] = addr;
2031b9bb7c18Sdrh           p->pRightmost->usesEphm = 1;
2032dc1bdc4fSdanielk1977         }
20330342b1f5Sdrh         createSortingIndex(pParse, p, pOrderBy);
203484ac9d02Sdanielk1977         assert( p->pEList );
2035d8bc7086Sdrh       }
2036d8bc7086Sdrh 
2037d8bc7086Sdrh       /* Code the SELECT statements to our left
2038d8bc7086Sdrh       */
2039b3bce662Sdanielk1977       assert( !pPrior->pOrderBy );
20401013c932Sdrh       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
20416c8c8ce0Sdanielk1977       rc = sqlite3Select(pParse, pPrior, &uniondest, 0, 0, 0, aff);
204284ac9d02Sdanielk1977       if( rc ){
204384ac9d02Sdanielk1977         goto multi_select_end;
204484ac9d02Sdanielk1977       }
2045d8bc7086Sdrh 
2046d8bc7086Sdrh       /* Code the current SELECT statement
2047d8bc7086Sdrh       */
2048d8bc7086Sdrh       switch( p->op ){
2049d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
2050d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
2051d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
2052d8bc7086Sdrh       }
205382c3d636Sdrh       p->pPrior = 0;
2054c926afbcSdrh       p->pOrderBy = 0;
20554b14b4d7Sdrh       p->disallowOrderBy = pOrderBy!=0;
2056a2dc3b1aSdanielk1977       pLimit = p->pLimit;
2057a2dc3b1aSdanielk1977       p->pLimit = 0;
2058a2dc3b1aSdanielk1977       pOffset = p->pOffset;
2059a2dc3b1aSdanielk1977       p->pOffset = 0;
20606c8c8ce0Sdanielk1977       uniondest.eDest = op;
20616c8c8ce0Sdanielk1977       rc = sqlite3Select(pParse, p, &uniondest, 0, 0, 0, aff);
20625bd1bf2eSdrh       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
20635bd1bf2eSdrh       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
20645bd1bf2eSdrh       sqlite3ExprListDelete(p->pOrderBy);
206582c3d636Sdrh       p->pPrior = pPrior;
2066c926afbcSdrh       p->pOrderBy = pOrderBy;
2067a2dc3b1aSdanielk1977       sqlite3ExprDelete(p->pLimit);
2068a2dc3b1aSdanielk1977       p->pLimit = pLimit;
2069a2dc3b1aSdanielk1977       p->pOffset = pOffset;
2070be5fd490Sdrh       p->iLimit = -1;
2071be5fd490Sdrh       p->iOffset = -1;
207284ac9d02Sdanielk1977       if( rc ){
207384ac9d02Sdanielk1977         goto multi_select_end;
207484ac9d02Sdanielk1977       }
207584ac9d02Sdanielk1977 
2076d8bc7086Sdrh 
2077d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
2078d8bc7086Sdrh       ** it is that we currently need.
2079d8bc7086Sdrh       */
20806c8c8ce0Sdanielk1977       if( dest.eDest!=priorOp || unionTab!=dest.iParm ){
20816b56344dSdrh         int iCont, iBreak, iStart;
208282c3d636Sdrh         assert( p->pEList );
20836c8c8ce0Sdanielk1977         if( dest.eDest==SRT_Callback ){
208492378253Sdrh           Select *pFirst = p;
208592378253Sdrh           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
208692378253Sdrh           generateColumnNames(pParse, 0, pFirst->pEList);
208741202ccaSdrh         }
20884adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
20894adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
2090ec7429aeSdrh         computeLimitRegisters(pParse, p, iBreak);
209166a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
20924adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
2093d2b3e23bSdrh         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
20946c8c8ce0Sdanielk1977                         pOrderBy, -1, &dest, iCont, iBreak, 0);
20954adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
209666a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
20974adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
209866a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
209982c3d636Sdrh       }
210082c3d636Sdrh       break;
210182c3d636Sdrh     }
210282c3d636Sdrh     case TK_INTERSECT: {
210382c3d636Sdrh       int tab1, tab2;
21046b56344dSdrh       int iCont, iBreak, iStart;
2105a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset;
2106dc1bdc4fSdanielk1977       int addr;
21071013c932Sdrh       SelectDest intersectdest;
21089cbf3425Sdrh       int r1;
210982c3d636Sdrh 
2110d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
21116206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
2112d8bc7086Sdrh       ** by allocating the tables we will need.
2113d8bc7086Sdrh       */
211482c3d636Sdrh       tab1 = pParse->nTab++;
211582c3d636Sdrh       tab2 = pParse->nTab++;
21169a99334dSdrh       if( processCompoundOrderBy(pParse, p, tab1) ){
211784ac9d02Sdanielk1977         rc = 1;
211884ac9d02Sdanielk1977         goto multi_select_end;
2119d8bc7086Sdrh       }
21200342b1f5Sdrh       createSortingIndex(pParse, p, pOrderBy);
2121dc1bdc4fSdanielk1977 
212266a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
2123b9bb7c18Sdrh       assert( p->addrOpenEphm[0] == -1 );
2124b9bb7c18Sdrh       p->addrOpenEphm[0] = addr;
2125b9bb7c18Sdrh       p->pRightmost->usesEphm = 1;
212684ac9d02Sdanielk1977       assert( p->pEList );
2127d8bc7086Sdrh 
2128d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
2129d8bc7086Sdrh       */
21301013c932Sdrh       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
21316c8c8ce0Sdanielk1977       rc = sqlite3Select(pParse, pPrior, &intersectdest, 0, 0, 0, aff);
213284ac9d02Sdanielk1977       if( rc ){
213384ac9d02Sdanielk1977         goto multi_select_end;
213484ac9d02Sdanielk1977       }
2135d8bc7086Sdrh 
2136d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
2137d8bc7086Sdrh       */
213866a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
2139b9bb7c18Sdrh       assert( p->addrOpenEphm[1] == -1 );
2140b9bb7c18Sdrh       p->addrOpenEphm[1] = addr;
214182c3d636Sdrh       p->pPrior = 0;
2142a2dc3b1aSdanielk1977       pLimit = p->pLimit;
2143a2dc3b1aSdanielk1977       p->pLimit = 0;
2144a2dc3b1aSdanielk1977       pOffset = p->pOffset;
2145a2dc3b1aSdanielk1977       p->pOffset = 0;
21466c8c8ce0Sdanielk1977       intersectdest.iParm = tab2;
21476c8c8ce0Sdanielk1977       rc = sqlite3Select(pParse, p, &intersectdest, 0, 0, 0, aff);
214882c3d636Sdrh       p->pPrior = pPrior;
2149a2dc3b1aSdanielk1977       sqlite3ExprDelete(p->pLimit);
2150a2dc3b1aSdanielk1977       p->pLimit = pLimit;
2151a2dc3b1aSdanielk1977       p->pOffset = pOffset;
215284ac9d02Sdanielk1977       if( rc ){
215384ac9d02Sdanielk1977         goto multi_select_end;
215484ac9d02Sdanielk1977       }
2155d8bc7086Sdrh 
2156d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
2157d8bc7086Sdrh       ** tables.
2158d8bc7086Sdrh       */
215982c3d636Sdrh       assert( p->pEList );
21606c8c8ce0Sdanielk1977       if( dest.eDest==SRT_Callback ){
216192378253Sdrh         Select *pFirst = p;
216292378253Sdrh         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
216392378253Sdrh         generateColumnNames(pParse, 0, pFirst->pEList);
216441202ccaSdrh       }
21654adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
21664adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
2167ec7429aeSdrh       computeLimitRegisters(pParse, p, iBreak);
216866a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
21699cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
21709cbf3425Sdrh       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
21719cbf3425Sdrh       sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1);
21729cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
2173d2b3e23bSdrh       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
21746c8c8ce0Sdanielk1977                       pOrderBy, -1, &dest, iCont, iBreak, 0);
21754adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
217666a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
21774adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
217866a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
217966a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
218082c3d636Sdrh       break;
218182c3d636Sdrh     }
218282c3d636Sdrh   }
21838cdbf836Sdrh 
21848cdbf836Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
21858cdbf836Sdrh   ** in their result sets.
21868cdbf836Sdrh   */
218782c3d636Sdrh   assert( p->pEList && pPrior->pEList );
218882c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
21894adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
2190da93d238Sdrh       " do not have the same number of result columns", selectOpName(p->op));
219184ac9d02Sdanielk1977     rc = 1;
219284ac9d02Sdanielk1977     goto multi_select_end;
21932282792aSdrh   }
219484ac9d02Sdanielk1977 
21958cdbf836Sdrh   /* Set the number of columns in temporary tables
21968cdbf836Sdrh   */
21978cdbf836Sdrh   nCol = p->pEList->nExpr;
21980342b1f5Sdrh   while( nSetP2 ){
21990342b1f5Sdrh     sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
22008cdbf836Sdrh   }
22018cdbf836Sdrh 
2202fbc4ee7bSdrh   /* Compute collating sequences used by either the ORDER BY clause or
2203fbc4ee7bSdrh   ** by any temporary tables needed to implement the compound select.
2204fbc4ee7bSdrh   ** Attach the KeyInfo structure to all temporary tables.  Invoke the
2205fbc4ee7bSdrh   ** ORDER BY processing if there is an ORDER BY clause.
22068cdbf836Sdrh   **
22078cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
22088cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
22098cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
22108cdbf836Sdrh   ** no temp tables are required.
2211fbc4ee7bSdrh   */
2212b9bb7c18Sdrh   if( pOrderBy || p->usesEphm ){
2213fbc4ee7bSdrh     int i;                        /* Loop counter */
2214fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
22150342b1f5Sdrh     Select *pLoop;                /* For looping through SELECT statements */
22161e31e0b2Sdrh     int nKeyCol;                  /* Number of entries in pKeyInfo->aCol[] */
2217f68d7d17Sdrh     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
2218f68d7d17Sdrh     CollSeq **aCopy;              /* A copy of pKeyInfo->aColl[] */
2219fbc4ee7bSdrh 
22200342b1f5Sdrh     assert( p->pRightmost==p );
22211e31e0b2Sdrh     nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0);
222217435752Sdrh     pKeyInfo = sqlite3DbMallocZero(pParse->db,
222317435752Sdrh                        sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1));
2224dc1bdc4fSdanielk1977     if( !pKeyInfo ){
2225dc1bdc4fSdanielk1977       rc = SQLITE_NOMEM;
2226dc1bdc4fSdanielk1977       goto multi_select_end;
2227dc1bdc4fSdanielk1977     }
2228dc1bdc4fSdanielk1977 
222914db2665Sdanielk1977     pKeyInfo->enc = ENC(pParse->db);
2230dc1bdc4fSdanielk1977     pKeyInfo->nField = nCol;
2231dc1bdc4fSdanielk1977 
22320342b1f5Sdrh     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
22330342b1f5Sdrh       *apColl = multiSelectCollSeq(pParse, p, i);
22340342b1f5Sdrh       if( 0==*apColl ){
22350342b1f5Sdrh         *apColl = pParse->db->pDfltColl;
2236dc1bdc4fSdanielk1977       }
2237dc1bdc4fSdanielk1977     }
2238dc1bdc4fSdanielk1977 
22390342b1f5Sdrh     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
22400342b1f5Sdrh       for(i=0; i<2; i++){
2241b9bb7c18Sdrh         int addr = pLoop->addrOpenEphm[i];
22420342b1f5Sdrh         if( addr<0 ){
22430342b1f5Sdrh           /* If [0] is unused then [1] is also unused.  So we can
22440342b1f5Sdrh           ** always safely abort as soon as the first unused slot is found */
2245b9bb7c18Sdrh           assert( pLoop->addrOpenEphm[1]<0 );
22460342b1f5Sdrh           break;
22470342b1f5Sdrh         }
22480342b1f5Sdrh         sqlite3VdbeChangeP2(v, addr, nCol);
224966a5167bSdrh         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
22500ee5a1e7Sdrh         pLoop->addrOpenEphm[i] = -1;
22510342b1f5Sdrh       }
2252dc1bdc4fSdanielk1977     }
2253dc1bdc4fSdanielk1977 
22540342b1f5Sdrh     if( pOrderBy ){
22550342b1f5Sdrh       struct ExprList_item *pOTerm = pOrderBy->a;
22564efc083fSdrh       int nOrderByExpr = pOrderBy->nExpr;
22570342b1f5Sdrh       int addr;
22584db38a70Sdrh       u8 *pSortOrder;
22590342b1f5Sdrh 
2260f68d7d17Sdrh       /* Reuse the same pKeyInfo for the ORDER BY as was used above for
2261f68d7d17Sdrh       ** the compound select statements.  Except we have to change out the
2262f68d7d17Sdrh       ** pKeyInfo->aColl[] values.  Some of the aColl[] values will be
2263f68d7d17Sdrh       ** reused when constructing the pKeyInfo for the ORDER BY, so make
2264f68d7d17Sdrh       ** a copy.  Sufficient space to hold both the nCol entries for
2265f68d7d17Sdrh       ** the compound select and the nOrderbyExpr entries for the ORDER BY
2266f68d7d17Sdrh       ** was allocated above.  But we need to move the compound select
2267f68d7d17Sdrh       ** entries out of the way before constructing the ORDER BY entries.
2268f68d7d17Sdrh       ** Move the compound select entries into aCopy[] where they can be
2269f68d7d17Sdrh       ** accessed and reused when constructing the ORDER BY entries.
2270f68d7d17Sdrh       ** Because nCol might be greater than or less than nOrderByExpr
2271f68d7d17Sdrh       ** we have to use memmove() when doing the copy.
2272f68d7d17Sdrh       */
22731e31e0b2Sdrh       aCopy = &pKeyInfo->aColl[nOrderByExpr];
22744efc083fSdrh       pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
2275f68d7d17Sdrh       memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
2276f68d7d17Sdrh 
22770342b1f5Sdrh       apColl = pKeyInfo->aColl;
22784efc083fSdrh       for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
22790342b1f5Sdrh         Expr *pExpr = pOTerm->pExpr;
22808b4c40d8Sdrh         if( (pExpr->flags & EP_ExpCollate) ){
22818b4c40d8Sdrh           assert( pExpr->pColl!=0 );
22828b4c40d8Sdrh           *apColl = pExpr->pColl;
228384ac9d02Sdanielk1977         }else{
22840342b1f5Sdrh           *apColl = aCopy[pExpr->iColumn];
228584ac9d02Sdanielk1977         }
22864db38a70Sdrh         *pSortOrder = pOTerm->sortOrder;
228784ac9d02Sdanielk1977       }
22880342b1f5Sdrh       assert( p->pRightmost==p );
2289b9bb7c18Sdrh       assert( p->addrOpenEphm[2]>=0 );
2290b9bb7c18Sdrh       addr = p->addrOpenEphm[2];
2291a670b226Sdanielk1977       sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2);
22924efc083fSdrh       pKeyInfo->nField = nOrderByExpr;
229366a5167bSdrh       sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
22944db38a70Sdrh       pKeyInfo = 0;
22956c8c8ce0Sdanielk1977       generateSortTail(pParse, p, v, p->pEList->nExpr, &dest);
2296dc1bdc4fSdanielk1977     }
2297dc1bdc4fSdanielk1977 
229817435752Sdrh     sqlite3_free(pKeyInfo);
2299dc1bdc4fSdanielk1977   }
2300dc1bdc4fSdanielk1977 
2301dc1bdc4fSdanielk1977 multi_select_end:
23021013c932Sdrh   pDest->iMem = dest.iMem;
2303ad27e761Sdrh   pDest->nMem = dest.nMem;
230484ac9d02Sdanielk1977   return rc;
23052282792aSdrh }
2306b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
23072282792aSdrh 
2308b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
230917435752Sdrh /* Forward Declarations */
231017435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*);
231117435752Sdrh static void substSelect(sqlite3*, Select *, int, ExprList *);
231217435752Sdrh 
23132282792aSdrh /*
2314832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
23156a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
231684e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
23176a3ea0e6Sdrh ** unchanged.)
2318832508b7Sdrh **
2319832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
2320832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
2321832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
2322832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
2323832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
2324832508b7Sdrh ** of the subquery rather the result set of the subquery.
2325832508b7Sdrh */
232617435752Sdrh static void substExpr(
232717435752Sdrh   sqlite3 *db,        /* Report malloc errors to this connection */
232817435752Sdrh   Expr *pExpr,        /* Expr in which substitution occurs */
232917435752Sdrh   int iTable,         /* Table to be substituted */
233017435752Sdrh   ExprList *pEList    /* Substitute expressions */
233117435752Sdrh ){
2332832508b7Sdrh   if( pExpr==0 ) return;
233350350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
233450350a15Sdrh     if( pExpr->iColumn<0 ){
233550350a15Sdrh       pExpr->op = TK_NULL;
233650350a15Sdrh     }else{
2337832508b7Sdrh       Expr *pNew;
233884e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
2339832508b7Sdrh       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
2340832508b7Sdrh       pNew = pEList->a[pExpr->iColumn].pExpr;
2341832508b7Sdrh       assert( pNew!=0 );
2342832508b7Sdrh       pExpr->op = pNew->op;
2343d94a6698Sdrh       assert( pExpr->pLeft==0 );
234417435752Sdrh       pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
2345d94a6698Sdrh       assert( pExpr->pRight==0 );
234617435752Sdrh       pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
2347d94a6698Sdrh       assert( pExpr->pList==0 );
234817435752Sdrh       pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
2349832508b7Sdrh       pExpr->iTable = pNew->iTable;
2350fbbe005aSdanielk1977       pExpr->pTab = pNew->pTab;
2351832508b7Sdrh       pExpr->iColumn = pNew->iColumn;
2352832508b7Sdrh       pExpr->iAgg = pNew->iAgg;
235317435752Sdrh       sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
235417435752Sdrh       sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
235517435752Sdrh       pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
2356a1cb183dSdanielk1977       pExpr->flags = pNew->flags;
235750350a15Sdrh     }
2358832508b7Sdrh   }else{
235917435752Sdrh     substExpr(db, pExpr->pLeft, iTable, pEList);
236017435752Sdrh     substExpr(db, pExpr->pRight, iTable, pEList);
236117435752Sdrh     substSelect(db, pExpr->pSelect, iTable, pEList);
236217435752Sdrh     substExprList(db, pExpr->pList, iTable, pEList);
2363832508b7Sdrh   }
2364832508b7Sdrh }
236517435752Sdrh static void substExprList(
236617435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
236717435752Sdrh   ExprList *pList,     /* List to scan and in which to make substitutes */
236817435752Sdrh   int iTable,          /* Table to be substituted */
236917435752Sdrh   ExprList *pEList     /* Substitute values */
237017435752Sdrh ){
2371832508b7Sdrh   int i;
2372832508b7Sdrh   if( pList==0 ) return;
2373832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
237417435752Sdrh     substExpr(db, pList->a[i].pExpr, iTable, pEList);
2375832508b7Sdrh   }
2376832508b7Sdrh }
237717435752Sdrh static void substSelect(
237817435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
237917435752Sdrh   Select *p,           /* SELECT statement in which to make substitutions */
238017435752Sdrh   int iTable,          /* Table to be replaced */
238117435752Sdrh   ExprList *pEList     /* Substitute values */
238217435752Sdrh ){
2383b3bce662Sdanielk1977   if( !p ) return;
238417435752Sdrh   substExprList(db, p->pEList, iTable, pEList);
238517435752Sdrh   substExprList(db, p->pGroupBy, iTable, pEList);
238617435752Sdrh   substExprList(db, p->pOrderBy, iTable, pEList);
238717435752Sdrh   substExpr(db, p->pHaving, iTable, pEList);
238817435752Sdrh   substExpr(db, p->pWhere, iTable, pEList);
238917435752Sdrh   substSelect(db, p->pPrior, iTable, pEList);
2390b3bce662Sdanielk1977 }
2391b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_VIEW) */
2392832508b7Sdrh 
2393b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
2394832508b7Sdrh /*
23951350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
23961350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
23971350b030Sdrh ** occurs.
23981350b030Sdrh **
23991350b030Sdrh ** To understand the concept of flattening, consider the following
24001350b030Sdrh ** query:
24011350b030Sdrh **
24021350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
24031350b030Sdrh **
24041350b030Sdrh ** The default way of implementing this query is to execute the
24051350b030Sdrh ** subquery first and store the results in a temporary table, then
24061350b030Sdrh ** run the outer query on that temporary table.  This requires two
24071350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
24081350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
2409832508b7Sdrh ** optimized.
24101350b030Sdrh **
2411832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
24121350b030Sdrh ** a single flat select, like this:
24131350b030Sdrh **
24141350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
24151350b030Sdrh **
24161350b030Sdrh ** The code generated for this simpification gives the same result
2417832508b7Sdrh ** but only has to scan the data once.  And because indices might
2418832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
2419832508b7Sdrh ** avoided.
24201350b030Sdrh **
2421832508b7Sdrh ** Flattening is only attempted if all of the following are true:
24221350b030Sdrh **
2423832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
24241350b030Sdrh **
2425832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
2426832508b7Sdrh **
24278af4d3acSdrh **   (3)  The subquery is not the right operand of a left outer join, or
24288af4d3acSdrh **        the subquery is not itself a join.  (Ticket #306)
2429832508b7Sdrh **
2430832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
2431832508b7Sdrh **
2432832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
2433832508b7Sdrh **        aggregates.
2434832508b7Sdrh **
2435832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
2436832508b7Sdrh **        DISTINCT.
2437832508b7Sdrh **
243808192d5fSdrh **   (7)  The subquery has a FROM clause.
243908192d5fSdrh **
2440df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
2441df199a25Sdrh **
2442df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
2443df199a25Sdrh **        aggregates.
2444df199a25Sdrh **
2445df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
2446df199a25Sdrh **        use LIMIT.
2447df199a25Sdrh **
2448174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
2449174b6195Sdrh **
24503fc673e6Sdrh **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
24513fc673e6Sdrh **        subquery has no WHERE clause.  (added by ticket #350)
24523fc673e6Sdrh **
2453ac83963aSdrh **  (13)  The subquery and outer query do not both use LIMIT
2454ac83963aSdrh **
2455ac83963aSdrh **  (14)  The subquery does not use OFFSET
2456ac83963aSdrh **
2457ad91c6cdSdrh **  (15)  The outer query is not part of a compound select or the
2458ad91c6cdSdrh **        subquery does not have both an ORDER BY and a LIMIT clause.
2459ad91c6cdSdrh **        (See ticket #2339)
2460ad91c6cdSdrh **
2461c52e355dSdrh **  (16)  The outer query is not an aggregate or the subquery does
2462c52e355dSdrh **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
2463c52e355dSdrh **        until we introduced the group_concat() function.
2464c52e355dSdrh **
2465832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
2466832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
2467832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
2468832508b7Sdrh **
2469665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
2470832508b7Sdrh ** If flattening is attempted this routine returns 1.
2471832508b7Sdrh **
2472832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
2473832508b7Sdrh ** the subquery before this routine runs.
24741350b030Sdrh */
24758c74a8caSdrh static int flattenSubquery(
247617435752Sdrh   sqlite3 *db,         /* Database connection */
24778c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
24788c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
24798c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
24808c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
24818c74a8caSdrh ){
24820bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
2483ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
2484ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
24850bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
24866a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
248791bb0eedSdrh   int i;              /* Loop counter */
248891bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
248991bb0eedSdrh   struct SrcList_item *pSubitem;   /* The subquery */
24901350b030Sdrh 
2491832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
2492832508b7Sdrh   */
2493832508b7Sdrh   if( p==0 ) return 0;
2494832508b7Sdrh   pSrc = p->pSrc;
2495ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
249691bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
249791bb0eedSdrh   pSub = pSubitem->pSelect;
2498832508b7Sdrh   assert( pSub!=0 );
2499ac83963aSdrh   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
2500ac83963aSdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
2501832508b7Sdrh   pSubSrc = pSub->pSrc;
2502832508b7Sdrh   assert( pSubSrc );
2503ac83963aSdrh   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
2504ac83963aSdrh   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
2505ac83963aSdrh   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
2506ac83963aSdrh   ** became arbitrary expressions, we were forced to add restrictions (13)
2507ac83963aSdrh   ** and (14). */
2508ac83963aSdrh   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
2509ac83963aSdrh   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
2510ad91c6cdSdrh   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
2511ad91c6cdSdrh     return 0;                                            /* Restriction (15) */
2512ad91c6cdSdrh   }
2513ac83963aSdrh   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
2514ac83963aSdrh   if( (pSub->isDistinct || pSub->pLimit)
2515ac83963aSdrh          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
2516df199a25Sdrh      return 0;
2517df199a25Sdrh   }
2518ac83963aSdrh   if( p->isDistinct && subqueryIsAgg ) return 0;         /* Restriction (6)  */
2519ac83963aSdrh   if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){
2520ac83963aSdrh      return 0;                                           /* Restriction (11) */
2521ac83963aSdrh   }
2522c52e355dSdrh   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
2523832508b7Sdrh 
25248af4d3acSdrh   /* Restriction 3:  If the subquery is a join, make sure the subquery is
25258af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
25268af4d3acSdrh   ** is not allowed:
25278af4d3acSdrh   **
25288af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
25298af4d3acSdrh   **
25308af4d3acSdrh   ** If we flatten the above, we would get
25318af4d3acSdrh   **
25328af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
25338af4d3acSdrh   **
25348af4d3acSdrh   ** which is not at all the same thing.
25358af4d3acSdrh   */
253661dfc31dSdrh   if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){
25378af4d3acSdrh     return 0;
25388af4d3acSdrh   }
25398af4d3acSdrh 
25403fc673e6Sdrh   /* Restriction 12:  If the subquery is the right operand of a left outer
25413fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
25423fc673e6Sdrh   ** An examples of why this is not allowed:
25433fc673e6Sdrh   **
25443fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
25453fc673e6Sdrh   **
25463fc673e6Sdrh   ** If we flatten the above, we would get
25473fc673e6Sdrh   **
25483fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
25493fc673e6Sdrh   **
25503fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
25513fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
25523fc673e6Sdrh   */
255361dfc31dSdrh   if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){
25543fc673e6Sdrh     return 0;
25553fc673e6Sdrh   }
25563fc673e6Sdrh 
25570bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
255863eb5f29Sdrh   ** iFrom-th entry of the FROM clause in the outer query.
2559832508b7Sdrh   */
2560c31c2eb8Sdrh 
2561c31c2eb8Sdrh   /* Move all of the FROM elements of the subquery into the
2562c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
2563c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
2564c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
2565c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
2566c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
2567c31c2eb8Sdrh   ** elements we are now copying in.
2568c31c2eb8Sdrh   */
256991bb0eedSdrh   iParent = pSubitem->iCursor;
2570c31c2eb8Sdrh   {
2571c31c2eb8Sdrh     int nSubSrc = pSubSrc->nSrc;
257291bb0eedSdrh     int jointype = pSubitem->jointype;
2573c31c2eb8Sdrh 
2574a04a34ffSdanielk1977     sqlite3DeleteTable(pSubitem->pTab);
257517435752Sdrh     sqlite3_free(pSubitem->zDatabase);
257617435752Sdrh     sqlite3_free(pSubitem->zName);
257717435752Sdrh     sqlite3_free(pSubitem->zAlias);
2578cfa063b3Sdrh     pSubitem->pTab = 0;
2579cfa063b3Sdrh     pSubitem->zDatabase = 0;
2580cfa063b3Sdrh     pSubitem->zName = 0;
2581cfa063b3Sdrh     pSubitem->zAlias = 0;
2582c31c2eb8Sdrh     if( nSubSrc>1 ){
2583c31c2eb8Sdrh       int extra = nSubSrc - 1;
2584c31c2eb8Sdrh       for(i=1; i<nSubSrc; i++){
258517435752Sdrh         pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0);
2586cfa063b3Sdrh         if( pSrc==0 ){
2587cfa063b3Sdrh           p->pSrc = 0;
2588cfa063b3Sdrh           return 1;
2589cfa063b3Sdrh         }
2590c31c2eb8Sdrh       }
2591c31c2eb8Sdrh       p->pSrc = pSrc;
2592c31c2eb8Sdrh       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2593c31c2eb8Sdrh         pSrc->a[i] = pSrc->a[i-extra];
2594c31c2eb8Sdrh       }
2595c31c2eb8Sdrh     }
2596c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
2597c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
2598c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2599c31c2eb8Sdrh     }
260061dfc31dSdrh     pSrc->a[iFrom].jointype = jointype;
2601c31c2eb8Sdrh   }
2602c31c2eb8Sdrh 
2603c31c2eb8Sdrh   /* Now begin substituting subquery result set expressions for
2604c31c2eb8Sdrh   ** references to the iParent in the outer query.
2605c31c2eb8Sdrh   **
2606c31c2eb8Sdrh   ** Example:
2607c31c2eb8Sdrh   **
2608c31c2eb8Sdrh   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2609c31c2eb8Sdrh   **   \                     \_____________ subquery __________/          /
2610c31c2eb8Sdrh   **    \_____________________ outer query ______________________________/
2611c31c2eb8Sdrh   **
2612c31c2eb8Sdrh   ** We look at every expression in the outer query and every place we see
2613c31c2eb8Sdrh   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2614c31c2eb8Sdrh   */
2615832508b7Sdrh   pList = p->pEList;
2616832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
26176977fea8Sdrh     Expr *pExpr;
26186977fea8Sdrh     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
261917435752Sdrh       pList->a[i].zName =
262017435752Sdrh              sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
2621832508b7Sdrh     }
2622832508b7Sdrh   }
26231e536953Sdanielk1977   substExprList(db, p->pEList, iParent, pSub->pEList);
26241b2e0329Sdrh   if( isAgg ){
26251e536953Sdanielk1977     substExprList(db, p->pGroupBy, iParent, pSub->pEList);
26261e536953Sdanielk1977     substExpr(db, p->pHaving, iParent, pSub->pEList);
26271b2e0329Sdrh   }
2628174b6195Sdrh   if( pSub->pOrderBy ){
2629174b6195Sdrh     assert( p->pOrderBy==0 );
2630174b6195Sdrh     p->pOrderBy = pSub->pOrderBy;
2631174b6195Sdrh     pSub->pOrderBy = 0;
2632174b6195Sdrh   }else if( p->pOrderBy ){
26331e536953Sdanielk1977     substExprList(db, p->pOrderBy, iParent, pSub->pEList);
2634174b6195Sdrh   }
2635832508b7Sdrh   if( pSub->pWhere ){
263617435752Sdrh     pWhere = sqlite3ExprDup(db, pSub->pWhere);
2637832508b7Sdrh   }else{
2638832508b7Sdrh     pWhere = 0;
2639832508b7Sdrh   }
2640832508b7Sdrh   if( subqueryIsAgg ){
2641832508b7Sdrh     assert( p->pHaving==0 );
26421b2e0329Sdrh     p->pHaving = p->pWhere;
26431b2e0329Sdrh     p->pWhere = pWhere;
26441e536953Sdanielk1977     substExpr(db, p->pHaving, iParent, pSub->pEList);
264517435752Sdrh     p->pHaving = sqlite3ExprAnd(db, p->pHaving,
264617435752Sdrh                                 sqlite3ExprDup(db, pSub->pHaving));
26471b2e0329Sdrh     assert( p->pGroupBy==0 );
264817435752Sdrh     p->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
2649832508b7Sdrh   }else{
26501e536953Sdanielk1977     substExpr(db, p->pWhere, iParent, pSub->pEList);
265117435752Sdrh     p->pWhere = sqlite3ExprAnd(db, p->pWhere, pWhere);
2652832508b7Sdrh   }
2653c31c2eb8Sdrh 
2654c31c2eb8Sdrh   /* The flattened query is distinct if either the inner or the
2655c31c2eb8Sdrh   ** outer query is distinct.
2656c31c2eb8Sdrh   */
2657832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
26588c74a8caSdrh 
2659a58fdfb1Sdanielk1977   /*
2660a58fdfb1Sdanielk1977   ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2661ac83963aSdrh   **
2662ac83963aSdrh   ** One is tempted to try to add a and b to combine the limits.  But this
2663ac83963aSdrh   ** does not work if either limit is negative.
2664a58fdfb1Sdanielk1977   */
2665a2dc3b1aSdanielk1977   if( pSub->pLimit ){
2666a2dc3b1aSdanielk1977     p->pLimit = pSub->pLimit;
2667a2dc3b1aSdanielk1977     pSub->pLimit = 0;
2668df199a25Sdrh   }
26698c74a8caSdrh 
2670c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
2671c31c2eb8Sdrh   ** success.
2672c31c2eb8Sdrh   */
26734adee20fSdanielk1977   sqlite3SelectDelete(pSub);
2674832508b7Sdrh   return 1;
26751350b030Sdrh }
2676b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */
26771350b030Sdrh 
26781350b030Sdrh /*
2679a9d1ccb9Sdanielk1977 ** Analyze the SELECT statement passed as an argument to see if it
2680a9d1ccb9Sdanielk1977 ** is a min() or max() query. Return ORDERBY_MIN or ORDERBY_MAX if
2681a9d1ccb9Sdanielk1977 ** it is, or 0 otherwise. At present, a query is considered to be
2682a9d1ccb9Sdanielk1977 ** a min()/max() query if:
2683a9d1ccb9Sdanielk1977 **
2684738bdcfbSdanielk1977 **   1. There is a single object in the FROM clause.
2685738bdcfbSdanielk1977 **
2686738bdcfbSdanielk1977 **   2. There is a single expression in the result set, and it is
2687738bdcfbSdanielk1977 **      either min(x) or max(x), where x is a column reference.
2688a9d1ccb9Sdanielk1977 */
2689a9d1ccb9Sdanielk1977 static int minMaxQuery(Parse *pParse, Select *p){
2690a9d1ccb9Sdanielk1977   Expr *pExpr;
2691a9d1ccb9Sdanielk1977   ExprList *pEList = p->pEList;
2692a9d1ccb9Sdanielk1977 
2693a9d1ccb9Sdanielk1977   if( pEList->nExpr!=1 ) return ORDERBY_NORMAL;
2694a9d1ccb9Sdanielk1977   pExpr = pEList->a[0].pExpr;
2695a9d1ccb9Sdanielk1977   pEList = pExpr->pList;
2696a9d1ccb9Sdanielk1977   if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0;
2697a9d1ccb9Sdanielk1977   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return ORDERBY_NORMAL;
2698a9d1ccb9Sdanielk1977   if( pExpr->token.n!=3 ) return ORDERBY_NORMAL;
2699a9d1ccb9Sdanielk1977   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
2700a9d1ccb9Sdanielk1977     return ORDERBY_MIN;
2701a9d1ccb9Sdanielk1977   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
2702a9d1ccb9Sdanielk1977     return ORDERBY_MAX;
2703a9d1ccb9Sdanielk1977   }
2704a9d1ccb9Sdanielk1977   return ORDERBY_NORMAL;
2705a9d1ccb9Sdanielk1977 }
2706a9d1ccb9Sdanielk1977 
2707a9d1ccb9Sdanielk1977 /*
2708b3bce662Sdanielk1977 ** This routine resolves any names used in the result set of the
2709b3bce662Sdanielk1977 ** supplied SELECT statement. If the SELECT statement being resolved
2710b3bce662Sdanielk1977 ** is a sub-select, then pOuterNC is a pointer to the NameContext
2711b3bce662Sdanielk1977 ** of the parent SELECT.
2712b3bce662Sdanielk1977 */
2713b3bce662Sdanielk1977 int sqlite3SelectResolve(
2714b3bce662Sdanielk1977   Parse *pParse,         /* The parser context */
2715b3bce662Sdanielk1977   Select *p,             /* The SELECT statement being coded. */
2716b3bce662Sdanielk1977   NameContext *pOuterNC  /* The outer name context. May be NULL. */
2717b3bce662Sdanielk1977 ){
2718b3bce662Sdanielk1977   ExprList *pEList;          /* Result set. */
2719b3bce662Sdanielk1977   int i;                     /* For-loop variable used in multiple places */
2720b3bce662Sdanielk1977   NameContext sNC;           /* Local name-context */
272113449892Sdrh   ExprList *pGroupBy;        /* The group by clause */
2722b3bce662Sdanielk1977 
2723b3bce662Sdanielk1977   /* If this routine has run before, return immediately. */
2724b3bce662Sdanielk1977   if( p->isResolved ){
2725b3bce662Sdanielk1977     assert( !pOuterNC );
2726b3bce662Sdanielk1977     return SQLITE_OK;
2727b3bce662Sdanielk1977   }
2728b3bce662Sdanielk1977   p->isResolved = 1;
2729b3bce662Sdanielk1977 
2730b3bce662Sdanielk1977   /* If there have already been errors, do nothing. */
2731b3bce662Sdanielk1977   if( pParse->nErr>0 ){
2732b3bce662Sdanielk1977     return SQLITE_ERROR;
2733b3bce662Sdanielk1977   }
2734b3bce662Sdanielk1977 
2735b3bce662Sdanielk1977   /* Prepare the select statement. This call will allocate all cursors
2736b3bce662Sdanielk1977   ** required to handle the tables and subqueries in the FROM clause.
2737b3bce662Sdanielk1977   */
2738b3bce662Sdanielk1977   if( prepSelectStmt(pParse, p) ){
2739b3bce662Sdanielk1977     return SQLITE_ERROR;
2740b3bce662Sdanielk1977   }
2741b3bce662Sdanielk1977 
2742a2dc3b1aSdanielk1977   /* Resolve the expressions in the LIMIT and OFFSET clauses. These
2743a2dc3b1aSdanielk1977   ** are not allowed to refer to any names, so pass an empty NameContext.
2744a2dc3b1aSdanielk1977   */
2745ffe07b2dSdrh   memset(&sNC, 0, sizeof(sNC));
2746b3bce662Sdanielk1977   sNC.pParse = pParse;
2747a2dc3b1aSdanielk1977   if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2748a2dc3b1aSdanielk1977       sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2749a2dc3b1aSdanielk1977     return SQLITE_ERROR;
2750a2dc3b1aSdanielk1977   }
2751a2dc3b1aSdanielk1977 
2752a2dc3b1aSdanielk1977   /* Set up the local name-context to pass to ExprResolveNames() to
2753a2dc3b1aSdanielk1977   ** resolve the expression-list.
2754a2dc3b1aSdanielk1977   */
2755a2dc3b1aSdanielk1977   sNC.allowAgg = 1;
2756a2dc3b1aSdanielk1977   sNC.pSrcList = p->pSrc;
2757a2dc3b1aSdanielk1977   sNC.pNext = pOuterNC;
2758b3bce662Sdanielk1977 
2759b3bce662Sdanielk1977   /* Resolve names in the result set. */
2760b3bce662Sdanielk1977   pEList = p->pEList;
2761b3bce662Sdanielk1977   if( !pEList ) return SQLITE_ERROR;
2762b3bce662Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
2763b3bce662Sdanielk1977     Expr *pX = pEList->a[i].pExpr;
2764b3bce662Sdanielk1977     if( sqlite3ExprResolveNames(&sNC, pX) ){
2765b3bce662Sdanielk1977       return SQLITE_ERROR;
2766b3bce662Sdanielk1977     }
2767b3bce662Sdanielk1977   }
2768b3bce662Sdanielk1977 
2769b3bce662Sdanielk1977   /* If there are no aggregate functions in the result-set, and no GROUP BY
2770b3bce662Sdanielk1977   ** expression, do not allow aggregates in any of the other expressions.
2771b3bce662Sdanielk1977   */
2772b3bce662Sdanielk1977   assert( !p->isAgg );
277313449892Sdrh   pGroupBy = p->pGroupBy;
277413449892Sdrh   if( pGroupBy || sNC.hasAgg ){
2775b3bce662Sdanielk1977     p->isAgg = 1;
2776b3bce662Sdanielk1977   }else{
2777b3bce662Sdanielk1977     sNC.allowAgg = 0;
2778b3bce662Sdanielk1977   }
2779b3bce662Sdanielk1977 
2780b3bce662Sdanielk1977   /* If a HAVING clause is present, then there must be a GROUP BY clause.
2781b3bce662Sdanielk1977   */
278213449892Sdrh   if( p->pHaving && !pGroupBy ){
2783b3bce662Sdanielk1977     sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2784b3bce662Sdanielk1977     return SQLITE_ERROR;
2785b3bce662Sdanielk1977   }
2786b3bce662Sdanielk1977 
2787b3bce662Sdanielk1977   /* Add the expression list to the name-context before parsing the
2788b3bce662Sdanielk1977   ** other expressions in the SELECT statement. This is so that
2789b3bce662Sdanielk1977   ** expressions in the WHERE clause (etc.) can refer to expressions by
2790b3bce662Sdanielk1977   ** aliases in the result set.
2791b3bce662Sdanielk1977   **
2792b3bce662Sdanielk1977   ** Minor point: If this is the case, then the expression will be
2793b3bce662Sdanielk1977   ** re-evaluated for each reference to it.
2794b3bce662Sdanielk1977   */
2795b3bce662Sdanielk1977   sNC.pEList = p->pEList;
2796b3bce662Sdanielk1977   if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2797994c80afSdrh      sqlite3ExprResolveNames(&sNC, p->pHaving) ){
2798b3bce662Sdanielk1977     return SQLITE_ERROR;
2799b3bce662Sdanielk1977   }
28009a99334dSdrh   if( p->pPrior==0 ){
280101874bfcSdanielk1977     if( processOrderGroupBy(pParse, p, p->pOrderBy, 1, &sNC.hasAgg) ){
2802994c80afSdrh       return SQLITE_ERROR;
2803994c80afSdrh     }
28049a99334dSdrh   }
28059a99334dSdrh   if( processOrderGroupBy(pParse, p, pGroupBy, 0, &sNC.hasAgg) ){
28064c774314Sdrh     return SQLITE_ERROR;
2807994c80afSdrh   }
2808b3bce662Sdanielk1977 
28091e536953Sdanielk1977   if( pParse->db->mallocFailed ){
28109afe689eSdanielk1977     return SQLITE_NOMEM;
28119afe689eSdanielk1977   }
28129afe689eSdanielk1977 
281313449892Sdrh   /* Make sure the GROUP BY clause does not contain aggregate functions.
281413449892Sdrh   */
281513449892Sdrh   if( pGroupBy ){
281613449892Sdrh     struct ExprList_item *pItem;
281713449892Sdrh 
281813449892Sdrh     for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
281913449892Sdrh       if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
282013449892Sdrh         sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
282113449892Sdrh             "the GROUP BY clause");
282213449892Sdrh         return SQLITE_ERROR;
282313449892Sdrh       }
282413449892Sdrh     }
282513449892Sdrh   }
282613449892Sdrh 
2827f6bbe022Sdrh   /* If this is one SELECT of a compound, be sure to resolve names
2828f6bbe022Sdrh   ** in the other SELECTs.
2829f6bbe022Sdrh   */
2830f6bbe022Sdrh   if( p->pPrior ){
2831f6bbe022Sdrh     return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC);
2832f6bbe022Sdrh   }else{
2833b3bce662Sdanielk1977     return SQLITE_OK;
2834b3bce662Sdanielk1977   }
2835f6bbe022Sdrh }
2836b3bce662Sdanielk1977 
2837b3bce662Sdanielk1977 /*
283813449892Sdrh ** Reset the aggregate accumulator.
283913449892Sdrh **
284013449892Sdrh ** The aggregate accumulator is a set of memory cells that hold
284113449892Sdrh ** intermediate results while calculating an aggregate.  This
284213449892Sdrh ** routine simply stores NULLs in all of those memory cells.
2843b3bce662Sdanielk1977 */
284413449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
284513449892Sdrh   Vdbe *v = pParse->pVdbe;
284613449892Sdrh   int i;
2847c99130fdSdrh   struct AggInfo_func *pFunc;
284813449892Sdrh   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
284913449892Sdrh     return;
285013449892Sdrh   }
285113449892Sdrh   for(i=0; i<pAggInfo->nColumn; i++){
28524c583128Sdrh     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
285313449892Sdrh   }
2854c99130fdSdrh   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
28554c583128Sdrh     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
2856c99130fdSdrh     if( pFunc->iDistinct>=0 ){
2857c99130fdSdrh       Expr *pE = pFunc->pExpr;
2858c99130fdSdrh       if( pE->pList==0 || pE->pList->nExpr!=1 ){
2859c99130fdSdrh         sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
2860c99130fdSdrh            "by an expression");
2861c99130fdSdrh         pFunc->iDistinct = -1;
2862c99130fdSdrh       }else{
2863c99130fdSdrh         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
286466a5167bSdrh         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
286566a5167bSdrh                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
2866c99130fdSdrh       }
2867c99130fdSdrh     }
286813449892Sdrh   }
2869b3bce662Sdanielk1977 }
2870b3bce662Sdanielk1977 
2871b3bce662Sdanielk1977 /*
287213449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function
287313449892Sdrh ** in the AggInfo structure.
2874b3bce662Sdanielk1977 */
287513449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
287613449892Sdrh   Vdbe *v = pParse->pVdbe;
287713449892Sdrh   int i;
287813449892Sdrh   struct AggInfo_func *pF;
287913449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
2880a10a34b8Sdrh     ExprList *pList = pF->pExpr->pList;
288166a5167bSdrh     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
288266a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
2883b3bce662Sdanielk1977   }
288413449892Sdrh }
288513449892Sdrh 
288613449892Sdrh /*
288713449892Sdrh ** Update the accumulator memory cells for an aggregate based on
288813449892Sdrh ** the current cursor position.
288913449892Sdrh */
289013449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
289113449892Sdrh   Vdbe *v = pParse->pVdbe;
289213449892Sdrh   int i;
289313449892Sdrh   struct AggInfo_func *pF;
289413449892Sdrh   struct AggInfo_col *pC;
289513449892Sdrh 
289613449892Sdrh   pAggInfo->directMode = 1;
289713449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
289813449892Sdrh     int nArg;
2899c99130fdSdrh     int addrNext = 0;
290098757157Sdrh     int regAgg;
290113449892Sdrh     ExprList *pList = pF->pExpr->pList;
290213449892Sdrh     if( pList ){
290313449892Sdrh       nArg = pList->nExpr;
2904892d3179Sdrh       regAgg = sqlite3GetTempRange(pParse, nArg);
2905892d3179Sdrh       sqlite3ExprCodeExprList(pParse, pList, regAgg);
290613449892Sdrh     }else{
290713449892Sdrh       nArg = 0;
290898757157Sdrh       regAgg = 0;
290913449892Sdrh     }
2910c99130fdSdrh     if( pF->iDistinct>=0 ){
2911c99130fdSdrh       addrNext = sqlite3VdbeMakeLabel(v);
2912c99130fdSdrh       assert( nArg==1 );
29132dcef11bSdrh       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
2914c99130fdSdrh     }
291513449892Sdrh     if( pF->pFunc->needCollSeq ){
291613449892Sdrh       CollSeq *pColl = 0;
291713449892Sdrh       struct ExprList_item *pItem;
291813449892Sdrh       int j;
291943617e9aSdrh       assert( pList!=0 );  /* pList!=0 if pF->pFunc->needCollSeq is true */
292043617e9aSdrh       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
292113449892Sdrh         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
292213449892Sdrh       }
292313449892Sdrh       if( !pColl ){
292413449892Sdrh         pColl = pParse->db->pDfltColl;
292513449892Sdrh       }
292666a5167bSdrh       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
292713449892Sdrh     }
292898757157Sdrh     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
292966a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
293098757157Sdrh     sqlite3VdbeChangeP5(v, nArg);
2931892d3179Sdrh     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
2932*da250ea5Sdrh     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
2933c99130fdSdrh     if( addrNext ){
2934c99130fdSdrh       sqlite3VdbeResolveLabel(v, addrNext);
2935c99130fdSdrh     }
293613449892Sdrh   }
293713449892Sdrh   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
2938389a1adbSdrh     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
293913449892Sdrh   }
294013449892Sdrh   pAggInfo->directMode = 0;
294113449892Sdrh }
294213449892Sdrh 
29438f2c54e6Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
29448f2c54e6Sdanielk1977 /*
29458f2c54e6Sdanielk1977 ** This function is used when a SELECT statement is used to create a
29468f2c54e6Sdanielk1977 ** temporary table for iterating through when running an INSTEAD OF
29478f2c54e6Sdanielk1977 ** UPDATE or INSTEAD OF DELETE trigger.
29488f2c54e6Sdanielk1977 **
29498f2c54e6Sdanielk1977 ** If possible, the SELECT statement is modified so that NULL values
29508f2c54e6Sdanielk1977 ** are stored in the temporary table for all columns for which the
29518f2c54e6Sdanielk1977 ** corresponding bit in argument mask is not set. If mask takes the
29528f2c54e6Sdanielk1977 ** special value 0xffffffff, then all columns are populated.
29538f2c54e6Sdanielk1977 */
2954d2b3e23bSdrh void sqlite3SelectMask(Parse *pParse, Select *p, u32 mask){
2955cdf3020cSdanielk1977   if( p && !p->pPrior && !p->isDistinct && mask!=0xffffffff ){
29568f2c54e6Sdanielk1977     ExprList *pEList;
29578f2c54e6Sdanielk1977     int i;
2958d2b3e23bSdrh     sqlite3SelectResolve(pParse, p, 0);
29598f2c54e6Sdanielk1977     pEList = p->pEList;
2960cdf3020cSdanielk1977     for(i=0; pEList && i<pEList->nExpr && i<32; i++){
29618f2c54e6Sdanielk1977       if( !(mask&((u32)1<<i)) ){
29628f2c54e6Sdanielk1977         sqlite3ExprDelete(pEList->a[i].pExpr);
29638f2c54e6Sdanielk1977         pEList->a[i].pExpr = sqlite3Expr(pParse->db, TK_NULL, 0, 0, 0);
29648f2c54e6Sdanielk1977       }
29658f2c54e6Sdanielk1977     }
29668f2c54e6Sdanielk1977   }
29678f2c54e6Sdanielk1977 }
29688f2c54e6Sdanielk1977 #endif
2969b3bce662Sdanielk1977 
2970b3bce662Sdanielk1977 /*
29719bb61fe7Sdrh ** Generate code for the given SELECT statement.
29729bb61fe7Sdrh **
2973fef5208cSdrh ** The results are distributed in various ways depending on the
29746c8c8ce0Sdanielk1977 ** contents of the SelectDest structure pointed to by argument pDest
29756c8c8ce0Sdanielk1977 ** as follows:
2976fef5208cSdrh **
29776c8c8ce0Sdanielk1977 **     pDest->eDest    Result
2978fef5208cSdrh **     ------------    -------------------------------------------
2979fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
2980fef5208cSdrh **
29816c8c8ce0Sdanielk1977 **     SRT_Mem         Store first result in memory cell pDest->iParm
2982fef5208cSdrh **
29836c8c8ce0Sdanielk1977 **     SRT_Set         Store non-null results as keys of table pDest->iParm.
29846c8c8ce0Sdanielk1977 **                     Apply the affinity pDest->affinity before storing them.
2985fef5208cSdrh **
29866c8c8ce0Sdanielk1977 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
298782c3d636Sdrh **
29886c8c8ce0Sdanielk1977 **     SRT_Except      Remove results from the temporary table pDest->iParm.
2989c4a3c779Sdrh **
29906c8c8ce0Sdanielk1977 **     SRT_Table       Store results in temporary table pDest->iParm
29919bb61fe7Sdrh **
29926c8c8ce0Sdanielk1977 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
29936c8c8ce0Sdanielk1977 **                     the result there. The cursor is left open after
29946c8c8ce0Sdanielk1977 **                     returning.
29956c8c8ce0Sdanielk1977 **
29966c8c8ce0Sdanielk1977 **     SRT_Subroutine  For each row returned, push the results onto the
29976c8c8ce0Sdanielk1977 **                     vdbe stack and call the subroutine (via OP_Gosub)
29986c8c8ce0Sdanielk1977 **                     at address pDest->iParm.
29996c8c8ce0Sdanielk1977 **
30006c8c8ce0Sdanielk1977 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
30016c8c8ce0Sdanielk1977 **                     set is not empty.
30026c8c8ce0Sdanielk1977 **
30036c8c8ce0Sdanielk1977 **     SRT_Discard     Throw the results away.
30046c8c8ce0Sdanielk1977 **
30056c8c8ce0Sdanielk1977 ** See the selectInnerLoop() function for a canonical listing of the
30066c8c8ce0Sdanielk1977 ** allowed values of eDest and their meanings.
3007e78e8284Sdrh **
30089bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
30099bb61fe7Sdrh ** encountered, then an appropriate error message is left in
30109bb61fe7Sdrh ** pParse->zErrMsg.
30119bb61fe7Sdrh **
30129bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
30139bb61fe7Sdrh ** calling function needs to do that.
30141b2e0329Sdrh **
30151b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
30161b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
30171b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
30181b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
30191b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
30201b2e0329Sdrh ** can be changed.
3021e78e8284Sdrh **
3022e78e8284Sdrh ** Example 1:   The meaning of the pParent parameter.
3023e78e8284Sdrh **
3024e78e8284Sdrh **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
3025e78e8284Sdrh **    \                      \_______ subquery _______/        /
3026e78e8284Sdrh **     \                                                      /
3027e78e8284Sdrh **      \____________________ outer query ___________________/
3028e78e8284Sdrh **
3029e78e8284Sdrh ** This routine is called for the outer query first.   For that call,
3030e78e8284Sdrh ** pParent will be NULL.  During the processing of the outer query, this
3031e78e8284Sdrh ** routine is called recursively to handle the subquery.  For the recursive
3032e78e8284Sdrh ** call, pParent will point to the outer query.  Because the subquery is
3033e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will
3034e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.)
30359bb61fe7Sdrh */
30364adee20fSdanielk1977 int sqlite3Select(
3037cce7d176Sdrh   Parse *pParse,         /* The parser context */
30389bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
30396c8c8ce0Sdanielk1977   SelectDest *pDest,     /* What to do with the query results */
3040832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
3041832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
304284ac9d02Sdanielk1977   int *pParentAgg,       /* True if pParent uses aggregate functions */
3043b3bce662Sdanielk1977   char *aff              /* If eDest is SRT_Union, the affinity string */
3044cce7d176Sdrh ){
304513449892Sdrh   int i, j;              /* Loop counters */
304613449892Sdrh   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
304713449892Sdrh   Vdbe *v;               /* The virtual machine under construction */
3048b3bce662Sdanielk1977   int isAgg;             /* True for select lists like "count(*)" */
3049a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
3050ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
30519bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
30529bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
30532282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
30542282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
305519a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
305619a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
30571d83f052Sdrh   int rc = 1;            /* Value to return from this function */
3058b9bb7c18Sdrh   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
305913449892Sdrh   AggInfo sAggInfo;      /* Information used by aggregate queries */
3060ec7429aeSdrh   int iEnd;              /* Address of the end of the query */
306117435752Sdrh   sqlite3 *db;           /* The database connection */
30629bb61fe7Sdrh 
306317435752Sdrh   db = pParse->db;
306417435752Sdrh   if( p==0 || db->mallocFailed || pParse->nErr ){
30656f7adc8aSdrh     return 1;
30666f7adc8aSdrh   }
30674adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
306813449892Sdrh   memset(&sAggInfo, 0, sizeof(sAggInfo));
3069daffd0e5Sdrh 
30709a99334dSdrh   pOrderBy = p->pOrderBy;
30716c8c8ce0Sdanielk1977   if( IgnorableOrderby(pDest) ){
30729a99334dSdrh     p->pOrderBy = 0;
30739ed1dfa8Sdanielk1977 
30749ed1dfa8Sdanielk1977     /* In these cases the DISTINCT operator makes no difference to the
30759ed1dfa8Sdanielk1977     ** results, so remove it if it were specified.
30769ed1dfa8Sdanielk1977     */
30779ed1dfa8Sdanielk1977     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
30789ed1dfa8Sdanielk1977            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
30799ed1dfa8Sdanielk1977     p->isDistinct = 0;
30809a99334dSdrh   }
30819a99334dSdrh   if( sqlite3SelectResolve(pParse, p, 0) ){
30829a99334dSdrh     goto select_end;
30839a99334dSdrh   }
30849a99334dSdrh   p->pOrderBy = pOrderBy;
30859a99334dSdrh 
3086b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
308782c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
308882c3d636Sdrh   */
308982c3d636Sdrh   if( p->pPrior ){
30900342b1f5Sdrh     if( p->pRightmost==0 ){
30911e281291Sdrh       Select *pLoop, *pRight = 0;
30920325d873Sdrh       int cnt = 0;
3093bb4957f8Sdrh       int mxSelect;
30940325d873Sdrh       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
30950342b1f5Sdrh         pLoop->pRightmost = p;
30961e281291Sdrh         pLoop->pNext = pRight;
30971e281291Sdrh         pRight = pLoop;
30980342b1f5Sdrh       }
3099bb4957f8Sdrh       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
3100bb4957f8Sdrh       if( mxSelect && cnt>mxSelect ){
31010325d873Sdrh         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
31020325d873Sdrh         return 1;
31030325d873Sdrh       }
31040342b1f5Sdrh     }
31056c8c8ce0Sdanielk1977     return multiSelect(pParse, p, pDest, aff);
310682c3d636Sdrh   }
3107b7f9164eSdrh #endif
310882c3d636Sdrh 
310982c3d636Sdrh   /* Make local copies of the parameters for this query.
311082c3d636Sdrh   */
31119bb61fe7Sdrh   pTabList = p->pSrc;
31129bb61fe7Sdrh   pWhere = p->pWhere;
31132282792aSdrh   pGroupBy = p->pGroupBy;
31142282792aSdrh   pHaving = p->pHaving;
3115b3bce662Sdanielk1977   isAgg = p->isAgg;
311619a775c2Sdrh   isDistinct = p->isDistinct;
3117b3bce662Sdanielk1977   pEList = p->pEList;
3118b3bce662Sdanielk1977   if( pEList==0 ) goto select_end;
31199bb61fe7Sdrh 
31209bb61fe7Sdrh   /*
31219bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
31229bb61fe7Sdrh   ** errors before this routine starts.
31239bb61fe7Sdrh   */
31241d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
3125cce7d176Sdrh 
31262282792aSdrh   /* If writing to memory or generating a set
31272282792aSdrh   ** only a single column may be output.
312819a775c2Sdrh   */
312993758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
31306c8c8ce0Sdanielk1977   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
31311d83f052Sdrh     goto select_end;
313219a775c2Sdrh   }
313393758c8dSdanielk1977 #endif
313419a775c2Sdrh 
3135c926afbcSdrh   /* ORDER BY is ignored for some destinations.
31362282792aSdrh   */
31376c8c8ce0Sdanielk1977   if( IgnorableOrderby(pDest) ){
3138acd4c695Sdrh     pOrderBy = 0;
31392282792aSdrh   }
31402282792aSdrh 
3141d820cb1bSdrh   /* Begin generating code.
3142d820cb1bSdrh   */
31434adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
3144d820cb1bSdrh   if( v==0 ) goto select_end;
3145d820cb1bSdrh 
3146d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
3147d820cb1bSdrh   */
314851522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3149ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
3150742f947bSdanielk1977     const char *zSavedAuthContext = 0;
3151c31c2eb8Sdrh     int needRestoreContext;
315213449892Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
31531013c932Sdrh     SelectDest dest;
3154c31c2eb8Sdrh 
31551787ccabSdanielk1977     if( pItem->pSelect==0 || pItem->isPopulated ) continue;
315613449892Sdrh     if( pItem->zName!=0 ){
31575cf590c1Sdrh       zSavedAuthContext = pParse->zAuthContext;
315813449892Sdrh       pParse->zAuthContext = pItem->zName;
3159c31c2eb8Sdrh       needRestoreContext = 1;
3160c31c2eb8Sdrh     }else{
3161c31c2eb8Sdrh       needRestoreContext = 0;
31625cf590c1Sdrh     }
3163fc976065Sdanielk1977     /* Increment Parse.nHeight by the height of the largest expression
3164fc976065Sdanielk1977     ** tree refered to by this, the parent select. The child select
3165fc976065Sdanielk1977     ** may contain expression trees of at most
3166fc976065Sdanielk1977     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
3167fc976065Sdanielk1977     ** more conservative than necessary, but much easier than enforcing
3168fc976065Sdanielk1977     ** an exact limit.
3169fc976065Sdanielk1977     */
3170fc976065Sdanielk1977     pParse->nHeight += sqlite3SelectExprHeight(p);
31711013c932Sdrh     sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
31726c8c8ce0Sdanielk1977     sqlite3Select(pParse, pItem->pSelect, &dest, p, i, &isAgg, 0);
3173cfa063b3Sdrh     if( db->mallocFailed ){
3174cfa063b3Sdrh       goto select_end;
3175cfa063b3Sdrh     }
3176fc976065Sdanielk1977     pParse->nHeight -= sqlite3SelectExprHeight(p);
3177c31c2eb8Sdrh     if( needRestoreContext ){
31785cf590c1Sdrh       pParse->zAuthContext = zSavedAuthContext;
31795cf590c1Sdrh     }
3180832508b7Sdrh     pTabList = p->pSrc;
3181832508b7Sdrh     pWhere = p->pWhere;
31826c8c8ce0Sdanielk1977     if( !IgnorableOrderby(pDest) ){
3183832508b7Sdrh       pOrderBy = p->pOrderBy;
3184acd4c695Sdrh     }
3185832508b7Sdrh     pGroupBy = p->pGroupBy;
3186832508b7Sdrh     pHaving = p->pHaving;
3187832508b7Sdrh     isDistinct = p->isDistinct;
31881b2e0329Sdrh   }
318951522cd3Sdrh #endif
31901b2e0329Sdrh 
31911b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
31921b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
31931b2e0329Sdrh   */
3194b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
31951b2e0329Sdrh   if( pParent && pParentAgg &&
319617435752Sdrh       flattenSubquery(db, pParent, parentTab, *pParentAgg, isAgg) ){
31971b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
3198b3bce662Sdanielk1977     goto select_end;
31991b2e0329Sdrh   }
3200b7f9164eSdrh #endif
3201832508b7Sdrh 
32020318d441Sdanielk1977   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
32030318d441Sdanielk1977   ** GROUP BY may use an index, DISTINCT never does.
32043c4809a2Sdanielk1977   */
32053c4809a2Sdanielk1977   if( p->isDistinct && !p->isAgg && !p->pGroupBy ){
32063c4809a2Sdanielk1977     p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
32073c4809a2Sdanielk1977     pGroupBy = p->pGroupBy;
32083c4809a2Sdanielk1977     p->isDistinct = 0;
32093c4809a2Sdanielk1977     isDistinct = 0;
32103c4809a2Sdanielk1977   }
32113c4809a2Sdanielk1977 
32128b4c40d8Sdrh   /* If there is an ORDER BY clause, then this sorting
32138b4c40d8Sdrh   ** index might end up being unused if the data can be
32149d2985c7Sdrh   ** extracted in pre-sorted order.  If that is the case, then the
3215b9bb7c18Sdrh   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
32169d2985c7Sdrh   ** we figure out that the sorting index is not needed.  The addrSortIndex
32179d2985c7Sdrh   ** variable is used to facilitate that change.
32187cedc8d4Sdanielk1977   */
32197cedc8d4Sdanielk1977   if( pOrderBy ){
32200342b1f5Sdrh     KeyInfo *pKeyInfo;
32210342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
32229d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
3223b9bb7c18Sdrh     p->addrOpenEphm[2] = addrSortIndex =
322466a5167bSdrh       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
322566a5167bSdrh                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
322666a5167bSdrh                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
32279d2985c7Sdrh   }else{
32289d2985c7Sdrh     addrSortIndex = -1;
32297cedc8d4Sdanielk1977   }
32307cedc8d4Sdanielk1977 
32312d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
32322d0794e3Sdrh   */
32336c8c8ce0Sdanielk1977   if( pDest->eDest==SRT_EphemTab ){
323466a5167bSdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
32352d0794e3Sdrh   }
32362d0794e3Sdrh 
3237f42bacc2Sdrh   /* Set the limiter.
3238f42bacc2Sdrh   */
3239f42bacc2Sdrh   iEnd = sqlite3VdbeMakeLabel(v);
3240f42bacc2Sdrh   computeLimitRegisters(pParse, p, iEnd);
3241f42bacc2Sdrh 
3242dece1a84Sdrh   /* Open a virtual index to use for the distinct set.
3243cce7d176Sdrh   */
324419a775c2Sdrh   if( isDistinct ){
32450342b1f5Sdrh     KeyInfo *pKeyInfo;
32463c4809a2Sdanielk1977     assert( isAgg || pGroupBy );
3247832508b7Sdrh     distinct = pParse->nTab++;
32480342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
324966a5167bSdrh     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
325066a5167bSdrh                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
3251832508b7Sdrh   }else{
3252832508b7Sdrh     distinct = -1;
3253efb7251dSdrh   }
3254832508b7Sdrh 
325513449892Sdrh   /* Aggregate and non-aggregate queries are handled differently */
325613449892Sdrh   if( !isAgg && pGroupBy==0 ){
325713449892Sdrh     /* This case is for non-aggregate queries
325813449892Sdrh     ** Begin the database scan
3259832508b7Sdrh     */
3260a9d1ccb9Sdanielk1977     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
32611d83f052Sdrh     if( pWInfo==0 ) goto select_end;
3262cce7d176Sdrh 
3263b9bb7c18Sdrh     /* If sorting index that was created by a prior OP_OpenEphemeral
3264b9bb7c18Sdrh     ** instruction ended up not being needed, then change the OP_OpenEphemeral
32659d2985c7Sdrh     ** into an OP_Noop.
32669d2985c7Sdrh     */
32679d2985c7Sdrh     if( addrSortIndex>=0 && pOrderBy==0 ){
3268f8875400Sdrh       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
3269b9bb7c18Sdrh       p->addrOpenEphm[2] = -1;
32709d2985c7Sdrh     }
32719d2985c7Sdrh 
327213449892Sdrh     /* Use the standard inner loop
3273cce7d176Sdrh     */
32743c4809a2Sdanielk1977     assert(!isDistinct);
3275d2b3e23bSdrh     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
3276d2b3e23bSdrh                     pWInfo->iContinue, pWInfo->iBreak, aff);
32772282792aSdrh 
3278cce7d176Sdrh     /* End the database scan loop.
3279cce7d176Sdrh     */
32804adee20fSdanielk1977     sqlite3WhereEnd(pWInfo);
328113449892Sdrh   }else{
328213449892Sdrh     /* This is the processing for aggregate queries */
328313449892Sdrh     NameContext sNC;    /* Name context for processing aggregate information */
328413449892Sdrh     int iAMem;          /* First Mem address for storing current GROUP BY */
328513449892Sdrh     int iBMem;          /* First Mem address for previous GROUP BY */
328613449892Sdrh     int iUseFlag;       /* Mem address holding flag indicating that at least
328713449892Sdrh                         ** one row of the input to the aggregator has been
328813449892Sdrh                         ** processed */
328913449892Sdrh     int iAbortFlag;     /* Mem address which causes query abort if positive */
329013449892Sdrh     int groupBySort;    /* Rows come from source in GROUP BY order */
3291cce7d176Sdrh 
329213449892Sdrh 
329313449892Sdrh     /* The following variables hold addresses or labels for parts of the
329413449892Sdrh     ** virtual machine program we are putting together */
329513449892Sdrh     int addrOutputRow;      /* Start of subroutine that outputs a result row */
329613449892Sdrh     int addrSetAbort;       /* Set the abort flag and return */
329713449892Sdrh     int addrInitializeLoop; /* Start of code that initializes the input loop */
329813449892Sdrh     int addrTopOfLoop;      /* Top of the input loop */
329913449892Sdrh     int addrGroupByChange;  /* Code that runs when any GROUP BY term changes */
330013449892Sdrh     int addrProcessRow;     /* Code to process a single input row */
330113449892Sdrh     int addrEnd;            /* End of all processing */
3302b9bb7c18Sdrh     int addrSortingIdx;     /* The OP_OpenEphemeral for the sorting index */
3303e313382eSdrh     int addrReset;          /* Subroutine for resetting the accumulator */
330413449892Sdrh 
330513449892Sdrh     addrEnd = sqlite3VdbeMakeLabel(v);
330613449892Sdrh 
330713449892Sdrh     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
330813449892Sdrh     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
330913449892Sdrh     ** SELECT statement.
33102282792aSdrh     */
331113449892Sdrh     memset(&sNC, 0, sizeof(sNC));
331213449892Sdrh     sNC.pParse = pParse;
331313449892Sdrh     sNC.pSrcList = pTabList;
331413449892Sdrh     sNC.pAggInfo = &sAggInfo;
331513449892Sdrh     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
33169d2985c7Sdrh     sAggInfo.pGroupBy = pGroupBy;
3317d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pEList);
3318d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
3319d2b3e23bSdrh     if( pHaving ){
3320d2b3e23bSdrh       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
332113449892Sdrh     }
332213449892Sdrh     sAggInfo.nAccumulator = sAggInfo.nColumn;
332313449892Sdrh     for(i=0; i<sAggInfo.nFunc; i++){
3324d2b3e23bSdrh       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList);
332513449892Sdrh     }
332617435752Sdrh     if( db->mallocFailed ) goto select_end;
332713449892Sdrh 
332813449892Sdrh     /* Processing for aggregates with GROUP BY is very different and
33293c4809a2Sdanielk1977     ** much more complex than aggregates without a GROUP BY.
333013449892Sdrh     */
333113449892Sdrh     if( pGroupBy ){
333213449892Sdrh       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
333313449892Sdrh 
333413449892Sdrh       /* Create labels that we will be needing
333513449892Sdrh       */
333613449892Sdrh 
333713449892Sdrh       addrInitializeLoop = sqlite3VdbeMakeLabel(v);
333813449892Sdrh       addrGroupByChange = sqlite3VdbeMakeLabel(v);
333913449892Sdrh       addrProcessRow = sqlite3VdbeMakeLabel(v);
334013449892Sdrh 
334113449892Sdrh       /* If there is a GROUP BY clause we might need a sorting index to
334213449892Sdrh       ** implement it.  Allocate that sorting index now.  If it turns out
3343b9bb7c18Sdrh       ** that we do not need it after all, the OpenEphemeral instruction
334413449892Sdrh       ** will be converted into a Noop.
334513449892Sdrh       */
334613449892Sdrh       sAggInfo.sortingIdx = pParse->nTab++;
334713449892Sdrh       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
3348cd3e8f7cSdanielk1977       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
3349cd3e8f7cSdanielk1977           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
3350cd3e8f7cSdanielk1977           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
335113449892Sdrh 
335213449892Sdrh       /* Initialize memory locations used by GROUP BY aggregate processing
335313449892Sdrh       */
33540a07c107Sdrh       iUseFlag = ++pParse->nMem;
33550a07c107Sdrh       iAbortFlag = ++pParse->nMem;
33560a07c107Sdrh       iAMem = pParse->nMem + 1;
335713449892Sdrh       pParse->nMem += pGroupBy->nExpr;
33580a07c107Sdrh       iBMem = pParse->nMem + 1;
335913449892Sdrh       pParse->nMem += pGroupBy->nExpr;
33604c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
3361d4e70ebdSdrh       VdbeComment((v, "clear abort flag"));
33624c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
3363d4e70ebdSdrh       VdbeComment((v, "indicate accumulator empty"));
336466a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrInitializeLoop);
336513449892Sdrh 
336613449892Sdrh       /* Generate a subroutine that outputs a single row of the result
336713449892Sdrh       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
336813449892Sdrh       ** is less than or equal to zero, the subroutine is a no-op.  If
336913449892Sdrh       ** the processing calls for the query to abort, this subroutine
337013449892Sdrh       ** increments the iAbortFlag memory location before returning in
337113449892Sdrh       ** order to signal the caller to abort.
337213449892Sdrh       */
337313449892Sdrh       addrSetAbort = sqlite3VdbeCurrentAddr(v);
33744c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
3375d4e70ebdSdrh       VdbeComment((v, "set abort flag"));
337666a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
337713449892Sdrh       addrOutputRow = sqlite3VdbeCurrentAddr(v);
33783c84ddffSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
3379d4e70ebdSdrh       VdbeComment((v, "Groupby result generator entry point"));
338066a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
338113449892Sdrh       finalizeAggFunctions(pParse, &sAggInfo);
338213449892Sdrh       if( pHaving ){
338335573356Sdrh         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
338413449892Sdrh       }
3385d2b3e23bSdrh       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
33866c8c8ce0Sdanielk1977                       distinct, pDest,
338713449892Sdrh                       addrOutputRow+1, addrSetAbort, aff);
338866a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
3389d4e70ebdSdrh       VdbeComment((v, "end groupby result generator"));
339013449892Sdrh 
3391e313382eSdrh       /* Generate a subroutine that will reset the group-by accumulator
3392e313382eSdrh       */
3393e313382eSdrh       addrReset = sqlite3VdbeCurrentAddr(v);
3394e313382eSdrh       resetAccumulator(pParse, &sAggInfo);
339566a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
3396e313382eSdrh 
339713449892Sdrh       /* Begin a loop that will extract all source rows in GROUP BY order.
339813449892Sdrh       ** This might involve two separate loops with an OP_Sort in between, or
339913449892Sdrh       ** it might be a single loop that uses an index to extract information
340013449892Sdrh       ** in the right order to begin with.
340113449892Sdrh       */
340213449892Sdrh       sqlite3VdbeResolveLabel(v, addrInitializeLoop);
340366a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset);
3404a9d1ccb9Sdanielk1977       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
34055360ad34Sdrh       if( pWInfo==0 ) goto select_end;
340613449892Sdrh       if( pGroupBy==0 ){
340713449892Sdrh         /* The optimizer is able to deliver rows in group by order so
3408b9bb7c18Sdrh         ** we do not have to sort.  The OP_OpenEphemeral table will be
340913449892Sdrh         ** cancelled later because we still need to use the pKeyInfo
341013449892Sdrh         */
341113449892Sdrh         pGroupBy = p->pGroupBy;
341213449892Sdrh         groupBySort = 0;
341313449892Sdrh       }else{
341413449892Sdrh         /* Rows are coming out in undetermined order.  We have to push
341513449892Sdrh         ** each row into a sorting index, terminate the first loop,
341613449892Sdrh         ** then loop over the sorting index in order to get the output
341713449892Sdrh         ** in sorted order
341813449892Sdrh         */
3419892d3179Sdrh         int regBase;
3420892d3179Sdrh         int regRecord;
3421892d3179Sdrh         int nCol;
3422892d3179Sdrh         int nGroupBy;
3423892d3179Sdrh 
342413449892Sdrh         groupBySort = 1;
3425892d3179Sdrh         nGroupBy = pGroupBy->nExpr;
3426892d3179Sdrh         nCol = nGroupBy + 1;
3427892d3179Sdrh         j = nGroupBy+1;
342813449892Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
3429892d3179Sdrh           if( sAggInfo.aCol[i].iSorterColumn>=j ){
3430892d3179Sdrh             nCol++;
343113449892Sdrh             j++;
343213449892Sdrh           }
3433892d3179Sdrh         }
3434892d3179Sdrh         regBase = sqlite3GetTempRange(pParse, nCol);
3435892d3179Sdrh         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase);
3436892d3179Sdrh         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
3437892d3179Sdrh         j = nGroupBy+1;
3438892d3179Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
3439892d3179Sdrh           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
3440892d3179Sdrh           if( pCol->iSorterColumn>=j ){
3441e55cbd72Sdrh             int r1 = j + regBase;
3442e55cbd72Sdrh             int r2 = sqlite3ExprCodeGetColumn(pParse,
3443*da250ea5Sdrh                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
3444e55cbd72Sdrh             if( r1!=r2 ){
3445e55cbd72Sdrh               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
3446e55cbd72Sdrh             }
3447892d3179Sdrh             j++;
3448892d3179Sdrh           }
3449892d3179Sdrh         }
3450892d3179Sdrh         regRecord = sqlite3GetTempReg(pParse);
34511db639ceSdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
3452892d3179Sdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
3453892d3179Sdrh         sqlite3ReleaseTempReg(pParse, regRecord);
3454892d3179Sdrh         sqlite3ReleaseTempRange(pParse, regBase, nCol);
345513449892Sdrh         sqlite3WhereEnd(pWInfo);
345666a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
3457d4e70ebdSdrh         VdbeComment((v, "GROUP BY sort"));
345813449892Sdrh         sAggInfo.useSortingIdx = 1;
345913449892Sdrh       }
346013449892Sdrh 
346113449892Sdrh       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
346213449892Sdrh       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
346313449892Sdrh       ** Then compare the current GROUP BY terms against the GROUP BY terms
346413449892Sdrh       ** from the previous row currently stored in a0, a1, a2...
346513449892Sdrh       */
346613449892Sdrh       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
346713449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
346813449892Sdrh         if( groupBySort ){
34692dcef11bSdrh           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
347013449892Sdrh         }else{
347113449892Sdrh           sAggInfo.directMode = 1;
34722dcef11bSdrh           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
347313449892Sdrh         }
347413449892Sdrh       }
347513449892Sdrh       for(j=pGroupBy->nExpr-1; j>=0; j--){
347613449892Sdrh         if( j==0 ){
34772dcef11bSdrh           sqlite3VdbeAddOp3(v, OP_Eq, iAMem+j, addrProcessRow, iBMem+j);
347813449892Sdrh         }else{
34792dcef11bSdrh           sqlite3VdbeAddOp3(v, OP_Ne, iAMem+j, addrGroupByChange, iBMem+j);
348013449892Sdrh         }
348166a5167bSdrh         sqlite3VdbeChangeP4(v, -1, (void*)pKeyInfo->aColl[j], P4_COLLSEQ);
348235573356Sdrh         sqlite3VdbeChangeP5(v, SQLITE_NULLEQUAL);
348313449892Sdrh       }
348413449892Sdrh 
348513449892Sdrh       /* Generate code that runs whenever the GROUP BY changes.
348613449892Sdrh       ** Change in the GROUP BY are detected by the previous code
348713449892Sdrh       ** block.  If there were no changes, this block is skipped.
348813449892Sdrh       **
348913449892Sdrh       ** This code copies current group by terms in b0,b1,b2,...
349013449892Sdrh       ** over to a0,a1,a2.  It then calls the output subroutine
349113449892Sdrh       ** and resets the aggregate accumulator registers in preparation
349213449892Sdrh       ** for the next GROUP BY batch.
349313449892Sdrh       */
349413449892Sdrh       sqlite3VdbeResolveLabel(v, addrGroupByChange);
349513449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
3496e55cbd72Sdrh         sqlite3ExprCodeMove(pParse, iBMem+j, iAMem+j);
349713449892Sdrh       }
349866a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrOutputRow);
3499d4e70ebdSdrh       VdbeComment((v, "output one row"));
35003c84ddffSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
3501d4e70ebdSdrh       VdbeComment((v, "check abort flag"));
350266a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset);
3503d4e70ebdSdrh       VdbeComment((v, "reset accumulator"));
350413449892Sdrh 
350513449892Sdrh       /* Update the aggregate accumulators based on the content of
350613449892Sdrh       ** the current row
350713449892Sdrh       */
350813449892Sdrh       sqlite3VdbeResolveLabel(v, addrProcessRow);
350913449892Sdrh       updateAccumulator(pParse, &sAggInfo);
35104c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
3511d4e70ebdSdrh       VdbeComment((v, "indicate data in accumulator"));
351213449892Sdrh 
351313449892Sdrh       /* End of the loop
351413449892Sdrh       */
351513449892Sdrh       if( groupBySort ){
351666a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
351713449892Sdrh       }else{
351813449892Sdrh         sqlite3WhereEnd(pWInfo);
3519f8875400Sdrh         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
352013449892Sdrh       }
352113449892Sdrh 
352213449892Sdrh       /* Output the final row of result
352313449892Sdrh       */
352466a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrOutputRow);
3525d4e70ebdSdrh       VdbeComment((v, "output final row"));
352613449892Sdrh 
352713449892Sdrh     } /* endif pGroupBy */
352813449892Sdrh     else {
3529a9d1ccb9Sdanielk1977       ExprList *pMinMax = 0;
3530dba0137eSdanielk1977       ExprList *pDel = 0;
3531a9d1ccb9Sdanielk1977       u8 flag;
3532a9d1ccb9Sdanielk1977 
3533738bdcfbSdanielk1977       /* Check if the query is of one of the following forms:
3534738bdcfbSdanielk1977       **
3535738bdcfbSdanielk1977       **   SELECT min(x) FROM ...
3536738bdcfbSdanielk1977       **   SELECT max(x) FROM ...
3537738bdcfbSdanielk1977       **
3538738bdcfbSdanielk1977       ** If it is, then ask the code in where.c to attempt to sort results
3539738bdcfbSdanielk1977       ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
3540738bdcfbSdanielk1977       ** If where.c is able to produce results sorted in this order, then
3541738bdcfbSdanielk1977       ** add vdbe code to break out of the processing loop after the
3542738bdcfbSdanielk1977       ** first iteration (since the first iteration of the loop is
3543738bdcfbSdanielk1977       ** guaranteed to operate on the row with the minimum or maximum
3544738bdcfbSdanielk1977       ** value of x, the only row required).
3545738bdcfbSdanielk1977       **
3546738bdcfbSdanielk1977       ** A special flag must be passed to sqlite3WhereBegin() to slightly
3547738bdcfbSdanielk1977       ** modify behaviour as follows:
3548738bdcfbSdanielk1977       **
3549738bdcfbSdanielk1977       **   + If the query is a "SELECT min(x)", then the loop coded by
3550738bdcfbSdanielk1977       **     where.c should not iterate over any values with a NULL value
3551738bdcfbSdanielk1977       **     for x.
3552738bdcfbSdanielk1977       **
3553738bdcfbSdanielk1977       **   + The optimizer code in where.c (the thing that decides which
3554738bdcfbSdanielk1977       **     index or indices to use) should place a different priority on
3555738bdcfbSdanielk1977       **     satisfying the 'ORDER BY' clause than it does in other cases.
3556738bdcfbSdanielk1977       **     Refer to code and comments in where.c for details.
3557738bdcfbSdanielk1977       */
3558a9d1ccb9Sdanielk1977       flag = minMaxQuery(pParse, p);
3559a9d1ccb9Sdanielk1977       if( flag ){
35608cc74322Sdrh         pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList);
35610e359b30Sdrh         if( pMinMax && !db->mallocFailed ){
3562a9d1ccb9Sdanielk1977           pMinMax->a[0].sortOrder = ((flag==ORDERBY_MIN)?0:1);
3563a9d1ccb9Sdanielk1977           pMinMax->a[0].pExpr->op = TK_COLUMN;
3564a9d1ccb9Sdanielk1977         }
35651013c932Sdrh       }
3566a9d1ccb9Sdanielk1977 
356713449892Sdrh       /* This case runs if the aggregate has no GROUP BY clause.  The
356813449892Sdrh       ** processing is much simpler since there is only a single row
356913449892Sdrh       ** of output.
357013449892Sdrh       */
357113449892Sdrh       resetAccumulator(pParse, &sAggInfo);
3572a9d1ccb9Sdanielk1977       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
3573dba0137eSdanielk1977       if( pWInfo==0 ){
35741013c932Sdrh         sqlite3ExprListDelete(pDel);
3575dba0137eSdanielk1977         goto select_end;
3576dba0137eSdanielk1977       }
357713449892Sdrh       updateAccumulator(pParse, &sAggInfo);
3578a9d1ccb9Sdanielk1977       if( !pMinMax && flag ){
3579a9d1ccb9Sdanielk1977         sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
3580a9d1ccb9Sdanielk1977         VdbeComment((v, "%s() by index", (flag==ORDERBY_MIN?"min":"max")));
3581a9d1ccb9Sdanielk1977       }
358213449892Sdrh       sqlite3WhereEnd(pWInfo);
358313449892Sdrh       finalizeAggFunctions(pParse, &sAggInfo);
358413449892Sdrh       pOrderBy = 0;
35855774b806Sdrh       if( pHaving ){
358635573356Sdrh         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
35875774b806Sdrh       }
358813449892Sdrh       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
35896c8c8ce0Sdanielk1977                       pDest, addrEnd, addrEnd, aff);
3590a9d1ccb9Sdanielk1977 
3591dba0137eSdanielk1977       sqlite3ExprListDelete(pDel);
359213449892Sdrh     }
359313449892Sdrh     sqlite3VdbeResolveLabel(v, addrEnd);
359413449892Sdrh 
359513449892Sdrh   } /* endif aggregate query */
35962282792aSdrh 
3597cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
3598cce7d176Sdrh   ** and send them to the callback one by one.
3599cce7d176Sdrh   */
3600cce7d176Sdrh   if( pOrderBy ){
36016c8c8ce0Sdanielk1977     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
3602cce7d176Sdrh   }
36036a535340Sdrh 
360493758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
3605f620b4e2Sdrh   /* If this was a subquery, we have now converted the subquery into a
36061787ccabSdanielk1977   ** temporary table.  So set the SrcList_item.isPopulated flag to prevent
36071787ccabSdanielk1977   ** this subquery from being evaluated again and to force the use of
36081787ccabSdanielk1977   ** the temporary table.
3609f620b4e2Sdrh   */
3610f620b4e2Sdrh   if( pParent ){
3611f620b4e2Sdrh     assert( pParent->pSrc->nSrc>parentTab );
3612f620b4e2Sdrh     assert( pParent->pSrc->a[parentTab].pSelect==p );
36131787ccabSdanielk1977     pParent->pSrc->a[parentTab].isPopulated = 1;
3614f620b4e2Sdrh   }
361593758c8dSdanielk1977 #endif
3616f620b4e2Sdrh 
3617ec7429aeSdrh   /* Jump here to skip this query
3618ec7429aeSdrh   */
3619ec7429aeSdrh   sqlite3VdbeResolveLabel(v, iEnd);
3620ec7429aeSdrh 
36211d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
36221d83f052Sdrh   ** to indicate no errors.
36231d83f052Sdrh   */
36241d83f052Sdrh   rc = 0;
36251d83f052Sdrh 
36261d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
36271d83f052Sdrh   ** successful coding of the SELECT.
36281d83f052Sdrh   */
36291d83f052Sdrh select_end:
3630955de52cSdanielk1977 
3631955de52cSdanielk1977   /* Identify column names if we will be using them in a callback.  This
3632955de52cSdanielk1977   ** step is skipped if the output is going to some other destination.
3633955de52cSdanielk1977   */
36346c8c8ce0Sdanielk1977   if( rc==SQLITE_OK && pDest->eDest==SRT_Callback ){
3635955de52cSdanielk1977     generateColumnNames(pParse, pTabList, pEList);
3636955de52cSdanielk1977   }
3637955de52cSdanielk1977 
363817435752Sdrh   sqlite3_free(sAggInfo.aCol);
363917435752Sdrh   sqlite3_free(sAggInfo.aFunc);
36401d83f052Sdrh   return rc;
3641cce7d176Sdrh }
3642485f0039Sdrh 
364377a2a5e7Sdrh #if defined(SQLITE_DEBUG)
3644485f0039Sdrh /*
3645485f0039Sdrh *******************************************************************************
3646485f0039Sdrh ** The following code is used for testing and debugging only.  The code
3647485f0039Sdrh ** that follows does not appear in normal builds.
3648485f0039Sdrh **
3649485f0039Sdrh ** These routines are used to print out the content of all or part of a
3650485f0039Sdrh ** parse structures such as Select or Expr.  Such printouts are useful
3651485f0039Sdrh ** for helping to understand what is happening inside the code generator
3652485f0039Sdrh ** during the execution of complex SELECT statements.
3653485f0039Sdrh **
3654485f0039Sdrh ** These routine are not called anywhere from within the normal
3655485f0039Sdrh ** code base.  Then are intended to be called from within the debugger
3656485f0039Sdrh ** or from temporary "printf" statements inserted for debugging.
3657485f0039Sdrh */
36583a00f907Smlcreech static void sqlite3PrintExpr(Expr *p){
3659485f0039Sdrh   if( p->token.z && p->token.n>0 ){
3660485f0039Sdrh     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
3661485f0039Sdrh   }else{
3662485f0039Sdrh     sqlite3DebugPrintf("(%d", p->op);
3663485f0039Sdrh   }
3664485f0039Sdrh   if( p->pLeft ){
3665485f0039Sdrh     sqlite3DebugPrintf(" ");
3666485f0039Sdrh     sqlite3PrintExpr(p->pLeft);
3667485f0039Sdrh   }
3668485f0039Sdrh   if( p->pRight ){
3669485f0039Sdrh     sqlite3DebugPrintf(" ");
3670485f0039Sdrh     sqlite3PrintExpr(p->pRight);
3671485f0039Sdrh   }
3672485f0039Sdrh   sqlite3DebugPrintf(")");
3673485f0039Sdrh }
36743a00f907Smlcreech static void sqlite3PrintExprList(ExprList *pList){
3675485f0039Sdrh   int i;
3676485f0039Sdrh   for(i=0; i<pList->nExpr; i++){
3677485f0039Sdrh     sqlite3PrintExpr(pList->a[i].pExpr);
3678485f0039Sdrh     if( i<pList->nExpr-1 ){
3679485f0039Sdrh       sqlite3DebugPrintf(", ");
3680485f0039Sdrh     }
3681485f0039Sdrh   }
3682485f0039Sdrh }
36833a00f907Smlcreech static void sqlite3PrintSelect(Select *p, int indent){
3684485f0039Sdrh   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
3685485f0039Sdrh   sqlite3PrintExprList(p->pEList);
3686485f0039Sdrh   sqlite3DebugPrintf("\n");
3687485f0039Sdrh   if( p->pSrc ){
3688485f0039Sdrh     char *zPrefix;
3689485f0039Sdrh     int i;
3690485f0039Sdrh     zPrefix = "FROM";
3691485f0039Sdrh     for(i=0; i<p->pSrc->nSrc; i++){
3692485f0039Sdrh       struct SrcList_item *pItem = &p->pSrc->a[i];
3693485f0039Sdrh       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
3694485f0039Sdrh       zPrefix = "";
3695485f0039Sdrh       if( pItem->pSelect ){
3696485f0039Sdrh         sqlite3DebugPrintf("(\n");
3697485f0039Sdrh         sqlite3PrintSelect(pItem->pSelect, indent+10);
3698485f0039Sdrh         sqlite3DebugPrintf("%*s)", indent+8, "");
3699485f0039Sdrh       }else if( pItem->zName ){
3700485f0039Sdrh         sqlite3DebugPrintf("%s", pItem->zName);
3701485f0039Sdrh       }
3702485f0039Sdrh       if( pItem->pTab ){
3703485f0039Sdrh         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
3704485f0039Sdrh       }
3705485f0039Sdrh       if( pItem->zAlias ){
3706485f0039Sdrh         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
3707485f0039Sdrh       }
3708485f0039Sdrh       if( i<p->pSrc->nSrc-1 ){
3709485f0039Sdrh         sqlite3DebugPrintf(",");
3710485f0039Sdrh       }
3711485f0039Sdrh       sqlite3DebugPrintf("\n");
3712485f0039Sdrh     }
3713485f0039Sdrh   }
3714485f0039Sdrh   if( p->pWhere ){
3715485f0039Sdrh     sqlite3DebugPrintf("%*s WHERE ", indent, "");
3716485f0039Sdrh     sqlite3PrintExpr(p->pWhere);
3717485f0039Sdrh     sqlite3DebugPrintf("\n");
3718485f0039Sdrh   }
3719485f0039Sdrh   if( p->pGroupBy ){
3720485f0039Sdrh     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
3721485f0039Sdrh     sqlite3PrintExprList(p->pGroupBy);
3722485f0039Sdrh     sqlite3DebugPrintf("\n");
3723485f0039Sdrh   }
3724485f0039Sdrh   if( p->pHaving ){
3725485f0039Sdrh     sqlite3DebugPrintf("%*s HAVING ", indent, "");
3726485f0039Sdrh     sqlite3PrintExpr(p->pHaving);
3727485f0039Sdrh     sqlite3DebugPrintf("\n");
3728485f0039Sdrh   }
3729485f0039Sdrh   if( p->pOrderBy ){
3730485f0039Sdrh     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
3731485f0039Sdrh     sqlite3PrintExprList(p->pOrderBy);
3732485f0039Sdrh     sqlite3DebugPrintf("\n");
3733485f0039Sdrh   }
3734485f0039Sdrh }
3735485f0039Sdrh /* End of the structure debug printing code
3736485f0039Sdrh *****************************************************************************/
3737485f0039Sdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
3738