xref: /sqlite-3.40.0/src/select.c (revision b1fdb2ad)
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*b1fdb2adSdrh ** $Id: select.c,v 1.385 2008/01/05 04:06:04 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 
36eda639e1Sdrh 
37eda639e1Sdrh /*
389bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that
399bb61fe7Sdrh ** structure.
40cce7d176Sdrh */
414adee20fSdanielk1977 Select *sqlite3SelectNew(
4217435752Sdrh   Parse *pParse,        /* Parsing context */
43daffd0e5Sdrh   ExprList *pEList,     /* which columns to include in the result */
44ad3cab52Sdrh   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
45daffd0e5Sdrh   Expr *pWhere,         /* the WHERE clause */
46daffd0e5Sdrh   ExprList *pGroupBy,   /* the GROUP BY clause */
47daffd0e5Sdrh   Expr *pHaving,        /* the HAVING clause */
48daffd0e5Sdrh   ExprList *pOrderBy,   /* the ORDER BY clause */
499bbca4c1Sdrh   int isDistinct,       /* true if the DISTINCT keyword is present */
50a2dc3b1aSdanielk1977   Expr *pLimit,         /* LIMIT value.  NULL means not used */
51a2dc3b1aSdanielk1977   Expr *pOffset         /* OFFSET value.  NULL means no offset */
529bb61fe7Sdrh ){
539bb61fe7Sdrh   Select *pNew;
54eda639e1Sdrh   Select standin;
5517435752Sdrh   sqlite3 *db = pParse->db;
5617435752Sdrh   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
57a2dc3b1aSdanielk1977   assert( !pOffset || pLimit );   /* Can't have OFFSET without LIMIT. */
58daffd0e5Sdrh   if( pNew==0 ){
59eda639e1Sdrh     pNew = &standin;
60eda639e1Sdrh     memset(pNew, 0, sizeof(*pNew));
61eda639e1Sdrh   }
62b733d037Sdrh   if( pEList==0 ){
63a1644fd8Sdanielk1977     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
64b733d037Sdrh   }
659bb61fe7Sdrh   pNew->pEList = pEList;
669bb61fe7Sdrh   pNew->pSrc = pSrc;
679bb61fe7Sdrh   pNew->pWhere = pWhere;
689bb61fe7Sdrh   pNew->pGroupBy = pGroupBy;
699bb61fe7Sdrh   pNew->pHaving = pHaving;
709bb61fe7Sdrh   pNew->pOrderBy = pOrderBy;
719bb61fe7Sdrh   pNew->isDistinct = isDistinct;
7282c3d636Sdrh   pNew->op = TK_SELECT;
738103b7d2Sdrh   assert( pOffset==0 || pLimit!=0 );
74a2dc3b1aSdanielk1977   pNew->pLimit = pLimit;
75a2dc3b1aSdanielk1977   pNew->pOffset = pOffset;
767b58daeaSdrh   pNew->iLimit = -1;
777b58daeaSdrh   pNew->iOffset = -1;
78b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
79b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
80b9bb7c18Sdrh   pNew->addrOpenEphm[2] = -1;
81eda639e1Sdrh   if( pNew==&standin) {
82eda639e1Sdrh     clearSelect(pNew);
83eda639e1Sdrh     pNew = 0;
84daffd0e5Sdrh   }
859bb61fe7Sdrh   return pNew;
869bb61fe7Sdrh }
879bb61fe7Sdrh 
889bb61fe7Sdrh /*
89eda639e1Sdrh ** Delete the given Select structure and all of its substructures.
90eda639e1Sdrh */
91eda639e1Sdrh void sqlite3SelectDelete(Select *p){
92eda639e1Sdrh   if( p ){
93eda639e1Sdrh     clearSelect(p);
9417435752Sdrh     sqlite3_free(p);
95eda639e1Sdrh   }
96eda639e1Sdrh }
97eda639e1Sdrh 
98eda639e1Sdrh /*
9901f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
10001f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
10101f3f253Sdrh ** in terms of the following bit values:
10201f3f253Sdrh **
10301f3f253Sdrh **     JT_INNER
1043dec223cSdrh **     JT_CROSS
10501f3f253Sdrh **     JT_OUTER
10601f3f253Sdrh **     JT_NATURAL
10701f3f253Sdrh **     JT_LEFT
10801f3f253Sdrh **     JT_RIGHT
10901f3f253Sdrh **
11001f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
11101f3f253Sdrh **
11201f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
11301f3f253Sdrh ** a join type, but put an error in the pParse structure.
11401f3f253Sdrh */
1154adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
11601f3f253Sdrh   int jointype = 0;
11701f3f253Sdrh   Token *apAll[3];
11801f3f253Sdrh   Token *p;
1195719628aSdrh   static const struct {
120c182d163Sdrh     const char zKeyword[8];
121290c1948Sdrh     u8 nChar;
122290c1948Sdrh     u8 code;
12301f3f253Sdrh   } keywords[] = {
12401f3f253Sdrh     { "natural", 7, JT_NATURAL },
125195e6967Sdrh     { "left",    4, JT_LEFT|JT_OUTER },
126195e6967Sdrh     { "right",   5, JT_RIGHT|JT_OUTER },
127195e6967Sdrh     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
12801f3f253Sdrh     { "outer",   5, JT_OUTER },
12901f3f253Sdrh     { "inner",   5, JT_INNER },
1303dec223cSdrh     { "cross",   5, JT_INNER|JT_CROSS },
13101f3f253Sdrh   };
13201f3f253Sdrh   int i, j;
13301f3f253Sdrh   apAll[0] = pA;
13401f3f253Sdrh   apAll[1] = pB;
13501f3f253Sdrh   apAll[2] = pC;
136195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
13701f3f253Sdrh     p = apAll[i];
13801f3f253Sdrh     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
13901f3f253Sdrh       if( p->n==keywords[j].nChar
1402646da7eSdrh           && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
14101f3f253Sdrh         jointype |= keywords[j].code;
14201f3f253Sdrh         break;
14301f3f253Sdrh       }
14401f3f253Sdrh     }
14501f3f253Sdrh     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
14601f3f253Sdrh       jointype |= JT_ERROR;
14701f3f253Sdrh       break;
14801f3f253Sdrh     }
14901f3f253Sdrh   }
150ad2d8307Sdrh   if(
151ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
152195e6967Sdrh      (jointype & JT_ERROR)!=0
153ad2d8307Sdrh   ){
154ae29ffbeSdrh     const char *zSp1 = " ";
155ae29ffbeSdrh     const char *zSp2 = " ";
156ae29ffbeSdrh     if( pB==0 ){ zSp1++; }
157ae29ffbeSdrh     if( pC==0 ){ zSp2++; }
158ae29ffbeSdrh     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
159ae29ffbeSdrh        "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
16001f3f253Sdrh     jointype = JT_INNER;
161195e6967Sdrh   }else if( jointype & JT_RIGHT ){
1624adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
163da93d238Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported");
164195e6967Sdrh     jointype = JT_INNER;
16501f3f253Sdrh   }
16601f3f253Sdrh   return jointype;
16701f3f253Sdrh }
16801f3f253Sdrh 
16901f3f253Sdrh /*
170ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
171ad2d8307Sdrh ** is not contained in the table.
172ad2d8307Sdrh */
173ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
174ad2d8307Sdrh   int i;
175ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
1764adee20fSdanielk1977     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
177ad2d8307Sdrh   }
178ad2d8307Sdrh   return -1;
179ad2d8307Sdrh }
180ad2d8307Sdrh 
181ad2d8307Sdrh /*
18291bb0eedSdrh ** Set the value of a token to a '\000'-terminated string.
18391bb0eedSdrh */
18491bb0eedSdrh static void setToken(Token *p, const char *z){
1852646da7eSdrh   p->z = (u8*)z;
186261919ccSdanielk1977   p->n = z ? strlen(z) : 0;
18791bb0eedSdrh   p->dyn = 0;
18891bb0eedSdrh }
18991bb0eedSdrh 
190c182d163Sdrh /*
191f3b863edSdanielk1977 ** Set the token to the double-quoted and escaped version of the string pointed
192f3b863edSdanielk1977 ** to by z. For example;
193f3b863edSdanielk1977 **
194f3b863edSdanielk1977 **    {a"bc}  ->  {"a""bc"}
195f3b863edSdanielk1977 */
1961e536953Sdanielk1977 static void setQuotedToken(Parse *pParse, Token *p, const char *z){
1971e536953Sdanielk1977   p->z = (u8 *)sqlite3MPrintf(0, "\"%w\"", z);
198f3b863edSdanielk1977   p->dyn = 1;
199f3b863edSdanielk1977   if( p->z ){
200f3b863edSdanielk1977     p->n = strlen((char *)p->z);
2011e536953Sdanielk1977   }else{
2021e536953Sdanielk1977     pParse->db->mallocFailed = 1;
203f3b863edSdanielk1977   }
204f3b863edSdanielk1977 }
205f3b863edSdanielk1977 
206f3b863edSdanielk1977 /*
207c182d163Sdrh ** Create an expression node for an identifier with the name of zName
208c182d163Sdrh */
20917435752Sdrh Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
210c182d163Sdrh   Token dummy;
211c182d163Sdrh   setToken(&dummy, zName);
21217435752Sdrh   return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
213c182d163Sdrh }
214c182d163Sdrh 
21591bb0eedSdrh 
21691bb0eedSdrh /*
217ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the
218ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2.
219ad2d8307Sdrh */
220ad2d8307Sdrh static void addWhereTerm(
22117435752Sdrh   Parse *pParse,           /* Parsing context */
222ad2d8307Sdrh   const char *zCol,        /* Name of the column */
223ad2d8307Sdrh   const Table *pTab1,      /* First table */
224030530deSdrh   const char *zAlias1,     /* Alias for first table.  May be NULL */
225ad2d8307Sdrh   const Table *pTab2,      /* Second table */
226030530deSdrh   const char *zAlias2,     /* Alias for second table.  May be NULL */
22722d6a53aSdrh   int iRightJoinTable,     /* VDBE cursor for the right table */
228ad2d8307Sdrh   Expr **ppExpr            /* Add the equality term to this expression */
229ad2d8307Sdrh ){
230ad2d8307Sdrh   Expr *pE1a, *pE1b, *pE1c;
231ad2d8307Sdrh   Expr *pE2a, *pE2b, *pE2c;
232ad2d8307Sdrh   Expr *pE;
233ad2d8307Sdrh 
23417435752Sdrh   pE1a = sqlite3CreateIdExpr(pParse, zCol);
23517435752Sdrh   pE2a = sqlite3CreateIdExpr(pParse, zCol);
236030530deSdrh   if( zAlias1==0 ){
237030530deSdrh     zAlias1 = pTab1->zName;
238030530deSdrh   }
23917435752Sdrh   pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
240030530deSdrh   if( zAlias2==0 ){
241030530deSdrh     zAlias2 = pTab2->zName;
242030530deSdrh   }
24317435752Sdrh   pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
24417435752Sdrh   pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
24517435752Sdrh   pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
2461e536953Sdanielk1977   pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
247206f3d96Sdrh   if( pE ){
2481f16230bSdrh     ExprSetProperty(pE, EP_FromJoin);
24922d6a53aSdrh     pE->iRightJoinTable = iRightJoinTable;
250206f3d96Sdrh   }
251f4ce8ed0Sdrh   *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
252ad2d8307Sdrh }
253ad2d8307Sdrh 
254ad2d8307Sdrh /*
2551f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
25622d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the
25722d6a53aSdrh ** expression.
2581cc093c2Sdrh **
259e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
2601cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
2611f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
2621f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
2631f16230bSdrh ** WHERE clause during join processing but we need to remember that they
2641f16230bSdrh ** originated in the ON or USING clause.
26522d6a53aSdrh **
26622d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the
26722d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not
26822d6a53aSdrh ** explicitly mentioned in the expression.  That information is needed
26922d6a53aSdrh ** for cases like this:
27022d6a53aSdrh **
27122d6a53aSdrh **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
27222d6a53aSdrh **
27322d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5
27422d6a53aSdrh ** term until after the t2 loop of the join.  In that way, a
27522d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
27622d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately
27722d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in
27822d6a53aSdrh ** the output, which is incorrect.
2791cc093c2Sdrh */
28022d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){
2811cc093c2Sdrh   while( p ){
2821f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
28322d6a53aSdrh     p->iRightJoinTable = iTable;
28422d6a53aSdrh     setJoinExpr(p->pLeft, iTable);
2851cc093c2Sdrh     p = p->pRight;
2861cc093c2Sdrh   }
2871cc093c2Sdrh }
2881cc093c2Sdrh 
2891cc093c2Sdrh /*
290ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
291ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
292ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
293ad2d8307Sdrh **
29491bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure.
29591bb0eedSdrh ** The left most table is the first entry in Select.pSrc.  The right-most
29691bb0eedSdrh ** table is the last entry.  The join operator is held in the entry to
29791bb0eedSdrh ** the left.  Thus entry 0 contains the join operator for the join between
29891bb0eedSdrh ** entries 0 and 1.  Any ON or USING clauses associated with the join are
29991bb0eedSdrh ** also attached to the left entry.
30091bb0eedSdrh **
301ad2d8307Sdrh ** This routine returns the number of errors encountered.
302ad2d8307Sdrh */
303ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
30491bb0eedSdrh   SrcList *pSrc;                  /* All tables in the FROM clause */
30591bb0eedSdrh   int i, j;                       /* Loop counters */
30691bb0eedSdrh   struct SrcList_item *pLeft;     /* Left table being joined */
30791bb0eedSdrh   struct SrcList_item *pRight;    /* Right table being joined */
308ad2d8307Sdrh 
30991bb0eedSdrh   pSrc = p->pSrc;
31091bb0eedSdrh   pLeft = &pSrc->a[0];
31191bb0eedSdrh   pRight = &pLeft[1];
31291bb0eedSdrh   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
31391bb0eedSdrh     Table *pLeftTab = pLeft->pTab;
31491bb0eedSdrh     Table *pRightTab = pRight->pTab;
31591bb0eedSdrh 
31691bb0eedSdrh     if( pLeftTab==0 || pRightTab==0 ) continue;
317ad2d8307Sdrh 
318ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
319ad2d8307Sdrh     ** every column that the two tables have in common.
320ad2d8307Sdrh     */
32161dfc31dSdrh     if( pRight->jointype & JT_NATURAL ){
32261dfc31dSdrh       if( pRight->pOn || pRight->pUsing ){
3234adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
324ad2d8307Sdrh            "an ON or USING clause", 0);
325ad2d8307Sdrh         return 1;
326ad2d8307Sdrh       }
32791bb0eedSdrh       for(j=0; j<pLeftTab->nCol; j++){
32891bb0eedSdrh         char *zName = pLeftTab->aCol[j].zName;
32991bb0eedSdrh         if( columnIndex(pRightTab, zName)>=0 ){
3301e536953Sdanielk1977           addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
33122d6a53aSdrh                               pRightTab, pRight->zAlias,
33222d6a53aSdrh                               pRight->iCursor, &p->pWhere);
33322d6a53aSdrh 
334ad2d8307Sdrh         }
335ad2d8307Sdrh       }
336ad2d8307Sdrh     }
337ad2d8307Sdrh 
338ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
339ad2d8307Sdrh     */
34061dfc31dSdrh     if( pRight->pOn && pRight->pUsing ){
3414adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
342da93d238Sdrh         "clauses in the same join");
343ad2d8307Sdrh       return 1;
344ad2d8307Sdrh     }
345ad2d8307Sdrh 
346ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
34791bb0eedSdrh     ** an AND operator.
348ad2d8307Sdrh     */
34961dfc31dSdrh     if( pRight->pOn ){
35061dfc31dSdrh       setJoinExpr(pRight->pOn, pRight->iCursor);
35117435752Sdrh       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
35261dfc31dSdrh       pRight->pOn = 0;
353ad2d8307Sdrh     }
354ad2d8307Sdrh 
355ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
356ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
357ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
358ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
359ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
360ad2d8307Sdrh     ** not contained in both tables to be joined.
361ad2d8307Sdrh     */
36261dfc31dSdrh     if( pRight->pUsing ){
36361dfc31dSdrh       IdList *pList = pRight->pUsing;
364ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
36591bb0eedSdrh         char *zName = pList->a[j].zName;
36691bb0eedSdrh         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
3674adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
36891bb0eedSdrh             "not present in both tables", zName);
369ad2d8307Sdrh           return 1;
370ad2d8307Sdrh         }
3711e536953Sdanielk1977         addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
37222d6a53aSdrh                             pRightTab, pRight->zAlias,
37322d6a53aSdrh                             pRight->iCursor, &p->pWhere);
374ad2d8307Sdrh       }
375ad2d8307Sdrh     }
376ad2d8307Sdrh   }
377ad2d8307Sdrh   return 0;
378ad2d8307Sdrh }
379ad2d8307Sdrh 
380ad2d8307Sdrh /*
381c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
382c926afbcSdrh ** stack into the sorter.
383c926afbcSdrh */
384d59ba6ceSdrh static void pushOntoSorter(
385d59ba6ceSdrh   Parse *pParse,         /* Parser context */
386d59ba6ceSdrh   ExprList *pOrderBy,    /* The ORDER BY clause */
387d59ba6ceSdrh   Select *pSelect        /* The whole SELECT statement */
388d59ba6ceSdrh ){
389d59ba6ceSdrh   Vdbe *v = pParse->pVdbe;
390389a1adbSdrh   sqlite3ExprCodeExprList(pParse, pOrderBy, 0);
39166a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, 0);
39266a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Pull, pOrderBy->nExpr + 1, 0);
39366a5167bSdrh   sqlite3VdbeAddOp2(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0);
39466a5167bSdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, 0);
395d59ba6ceSdrh   if( pSelect->iLimit>=0 ){
39615007a99Sdrh     int addr1, addr2;
39766a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_IfMemZero, pSelect->iLimit+1, 0);
39866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_MemIncr, -1, pSelect->iLimit+1);
39966a5167bSdrh     addr2 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
400d59ba6ceSdrh     sqlite3VdbeJumpHere(v, addr1);
40166a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Last, pOrderBy->iECursor, 0);
40266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Delete, pOrderBy->iECursor, 0);
40315007a99Sdrh     sqlite3VdbeJumpHere(v, addr2);
404d59ba6ceSdrh     pSelect->iLimit = -1;
405d59ba6ceSdrh   }
406c926afbcSdrh }
407c926afbcSdrh 
408c926afbcSdrh /*
409ec7429aeSdrh ** Add code to implement the OFFSET
410ea48eb2eSdrh */
411ec7429aeSdrh static void codeOffset(
412bab39e13Sdrh   Vdbe *v,          /* Generate code into this VM */
413ea48eb2eSdrh   Select *p,        /* The SELECT statement being coded */
414ea48eb2eSdrh   int iContinue,    /* Jump here to skip the current record */
415ea48eb2eSdrh   int nPop          /* Number of times to pop stack when jumping */
416ea48eb2eSdrh ){
41713449892Sdrh   if( p->iOffset>=0 && iContinue!=0 ){
41815007a99Sdrh     int addr;
41966a5167bSdrh     sqlite3VdbeAddOp2(v, OP_MemIncr, -1, p->iOffset);
42066a5167bSdrh     addr = sqlite3VdbeAddOp2(v, OP_IfMemNeg, p->iOffset, 0);
421ea48eb2eSdrh     if( nPop>0 ){
42266a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Pop, nPop, 0);
423ea48eb2eSdrh     }
42466a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
425d4e70ebdSdrh     VdbeComment((v, "skip OFFSET records"));
42615007a99Sdrh     sqlite3VdbeJumpHere(v, addr);
427ea48eb2eSdrh   }
428ea48eb2eSdrh }
429ea48eb2eSdrh 
430ea48eb2eSdrh /*
431c99130fdSdrh ** Add code that will check to make sure the top N elements of the
432c99130fdSdrh ** stack are distinct.  iTab is a sorting index that holds previously
433c99130fdSdrh ** seen combinations of the N values.  A new entry is made in iTab
434c99130fdSdrh ** if the current N values are new.
435c99130fdSdrh **
436f8875400Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the
437c99130fdSdrh ** stack if the top N elements are not distinct.
438c99130fdSdrh */
439a2a49dc9Sdrh static void codeDistinct_OLD(
440c99130fdSdrh   Vdbe *v,           /* Generate code into this VM */
441c99130fdSdrh   int iTab,          /* A sorting index used to test for distinctness */
442c99130fdSdrh   int addrRepeat,    /* Jump to here if not distinct */
443f8875400Sdrh   int N              /* The top N elements of the stack must be distinct */
444c99130fdSdrh ){
44566a5167bSdrh   sqlite3VdbeAddOp2(v, OP_MakeRecord, -N, 0);
44666a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3);
44766a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Pop, N+1, 0);
44866a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Goto, 0, addrRepeat);
449d4e70ebdSdrh   VdbeComment((v, "skip indistinct records"));
45066a5167bSdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, 0);
451c99130fdSdrh }
452c99130fdSdrh 
453e305f43fSdrh /*
454a2a49dc9Sdrh ** Add code that will check to make sure the top N elements of the
455a2a49dc9Sdrh ** stack are distinct.  iTab is a sorting index that holds previously
456a2a49dc9Sdrh ** seen combinations of the N values.  A new entry is made in iTab
457a2a49dc9Sdrh ** if the current N values are new.
458a2a49dc9Sdrh **
459a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the
460a2a49dc9Sdrh ** stack if the top N elements are not distinct.
461a2a49dc9Sdrh */
462a2a49dc9Sdrh static void codeDistinct(
463a2a49dc9Sdrh   Vdbe *v,           /* Generate code into this VM */
464a2a49dc9Sdrh   int iTab,          /* A sorting index used to test for distinctness */
465a2a49dc9Sdrh   int addrRepeat,    /* Jump to here if not distinct */
466a2a49dc9Sdrh   int iMem           /* First element */
467a2a49dc9Sdrh ){
46866a5167bSdrh   sqlite3VdbeAddOp2(v, OP_RegMakeRec, iMem, 0);
46966a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3);
47066a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Pop, 1, 0);
47166a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Goto, 0, addrRepeat);
472a2a49dc9Sdrh   VdbeComment((v, "skip indistinct records"));
47366a5167bSdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, 0);
474a2a49dc9Sdrh }
475a2a49dc9Sdrh 
476a2a49dc9Sdrh /*
477e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression
478e305f43fSdrh ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
479e305f43fSdrh ** column.  We do this in a subroutine because the error occurs in multiple
480e305f43fSdrh ** places.
481e305f43fSdrh */
4826c8c8ce0Sdanielk1977 static int checkForMultiColumnSelectError(
4836c8c8ce0Sdanielk1977   Parse *pParse,       /* Parse context. */
4846c8c8ce0Sdanielk1977   SelectDest *pDest,   /* Destination of SELECT results */
4856c8c8ce0Sdanielk1977   int nExpr            /* Number of result columns returned by SELECT */
4866c8c8ce0Sdanielk1977 ){
4876c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
488e305f43fSdrh   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
489e305f43fSdrh     sqlite3ErrorMsg(pParse, "only a single result allowed for "
490e305f43fSdrh        "a SELECT that is part of an expression");
491e305f43fSdrh     return 1;
492e305f43fSdrh   }else{
493e305f43fSdrh     return 0;
494e305f43fSdrh   }
495e305f43fSdrh }
496c99130fdSdrh 
497c99130fdSdrh /*
4982282792aSdrh ** This routine generates the code for the inside of the inner loop
4992282792aSdrh ** of a SELECT.
50082c3d636Sdrh **
50138640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
50238640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
50338640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
50438640e15Sdrh ** datatypes for each column.
5052282792aSdrh */
5062282792aSdrh static int selectInnerLoop(
5072282792aSdrh   Parse *pParse,          /* The parser context */
508df199a25Sdrh   Select *p,              /* The complete select statement being coded */
5092282792aSdrh   ExprList *pEList,       /* List of values being extracted */
51082c3d636Sdrh   int srcTab,             /* Pull data from this table */
511967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
5122282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
5132282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
5146c8c8ce0Sdanielk1977   SelectDest *pDest,      /* How to dispose of the results */
5152282792aSdrh   int iContinue,          /* Jump here to continue with next row */
51684ac9d02Sdanielk1977   int iBreak,             /* Jump here to break out of the inner loop */
51784ac9d02Sdanielk1977   char *aff               /* affinity string if eDest is SRT_Union */
5182282792aSdrh ){
5192282792aSdrh   Vdbe *v = pParse->pVdbe;
520a2a49dc9Sdrh   int i, n;
521ea48eb2eSdrh   int hasDistinct;        /* True if the DISTINCT keyword is present */
522a2a49dc9Sdrh   int iMem;               /* Start of memory holding result set */
5236c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
5246c8c8ce0Sdanielk1977   int iParm = pDest->iParm;
52538640e15Sdrh 
526daffd0e5Sdrh   if( v==0 ) return 0;
52738640e15Sdrh   assert( pEList!=0 );
5282282792aSdrh 
529df199a25Sdrh   /* If there was a LIMIT clause on the SELECT statement, then do the check
530df199a25Sdrh   ** to see if this row should be output.
531df199a25Sdrh   */
532eda639e1Sdrh   hasDistinct = distinct>=0 && pEList->nExpr>0;
533ea48eb2eSdrh   if( pOrderBy==0 && !hasDistinct ){
534ec7429aeSdrh     codeOffset(v, p, iContinue, 0);
535df199a25Sdrh   }
536df199a25Sdrh 
537967e8b73Sdrh   /* Pull the requested columns.
5382282792aSdrh   */
53938640e15Sdrh   if( nColumn>0 ){
540a2a49dc9Sdrh     n = nColumn;
541a2a49dc9Sdrh   }else{
542a2a49dc9Sdrh     n = pEList->nExpr;
543a2a49dc9Sdrh   }
5440a07c107Sdrh   iMem = ++pParse->nMem;
545a2a49dc9Sdrh   pParse->nMem += n+1;
5464c583128Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, n, iMem);
547a2a49dc9Sdrh   if( nColumn>0 ){
548967e8b73Sdrh     for(i=0; i<nColumn; i++){
54966a5167bSdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, iMem+i+1);
55082c3d636Sdrh     }
5519ed1dfa8Sdanielk1977   }else if( eDest!=SRT_Exists ){
5529ed1dfa8Sdanielk1977     /* If the destination is an EXISTS(...) expression, the actual
5539ed1dfa8Sdanielk1977     ** values returned by the SELECT are not required.
5549ed1dfa8Sdanielk1977     */
555a2a49dc9Sdrh     for(i=0; i<n; i++){
556389a1adbSdrh       sqlite3ExprCode(pParse, pEList->a[i].pExpr, iMem+i+1);
55782c3d636Sdrh     }
558a2a49dc9Sdrh   }
559a2a49dc9Sdrh   nColumn = n;
5602282792aSdrh 
561daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
562daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
563daffd0e5Sdrh   ** part of the result.
5642282792aSdrh   */
565ea48eb2eSdrh   if( hasDistinct ){
566f8875400Sdrh     assert( pEList!=0 );
567f8875400Sdrh     assert( pEList->nExpr==nColumn );
568a2a49dc9Sdrh     codeDistinct(v, distinct, iContinue, iMem);
569ea48eb2eSdrh     if( pOrderBy==0 ){
570ec7429aeSdrh       codeOffset(v, p, iContinue, nColumn);
571ea48eb2eSdrh     }
5722282792aSdrh   }
57382c3d636Sdrh 
5746c8c8ce0Sdanielk1977   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
575e305f43fSdrh     return 0;
576e305f43fSdrh   }
577e305f43fSdrh 
578c926afbcSdrh   switch( eDest ){
57982c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
58082c3d636Sdrh     ** table iParm.
5812282792aSdrh     */
58213449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
583c926afbcSdrh     case SRT_Union: {
58466a5167bSdrh       sqlite3VdbeAddOp2(v, OP_RegMakeRec, iMem, 0);
58513449892Sdrh       if( aff ){
58666a5167bSdrh         sqlite3VdbeChangeP4(v, -1, aff, P4_STATIC);
58713449892Sdrh       }
58866a5167bSdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, 0);
589c926afbcSdrh       break;
590c926afbcSdrh     }
59182c3d636Sdrh 
59282c3d636Sdrh     /* Construct a record from the query result, but instead of
59382c3d636Sdrh     ** saving that record, use it as a key to delete elements from
59482c3d636Sdrh     ** the temporary table iParm.
59582c3d636Sdrh     */
596c926afbcSdrh     case SRT_Except: {
5970bd1f4eaSdrh       int addr;
59866a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_RegMakeRec, iMem, 0);
59966a5167bSdrh       sqlite3VdbeChangeP4(v, -1, aff, P4_STATIC);
60066a5167bSdrh       sqlite3VdbeAddOp2(v, OP_NotFound, iParm, addr+3);
60166a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Delete, iParm, 0);
602c926afbcSdrh       break;
603c926afbcSdrh     }
6045338a5f7Sdanielk1977 #endif
6055338a5f7Sdanielk1977 
6065338a5f7Sdanielk1977     /* Store the result as data using a unique key.
6075338a5f7Sdanielk1977     */
6085338a5f7Sdanielk1977     case SRT_Table:
609b9bb7c18Sdrh     case SRT_EphemTab: {
61066a5167bSdrh       sqlite3VdbeAddOp2(v, OP_RegMakeRec, iMem, 0);
6115338a5f7Sdanielk1977       if( pOrderBy ){
612d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
6135338a5f7Sdanielk1977       }else{
6144c583128Sdrh         sqlite3VdbeAddOp1(v, OP_NewRowid, iParm);
61566a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Pull, 1, 0);
6161f4aa337Sdanielk1977         sqlite3CodeInsert(pParse, iParm, OPFLAG_APPEND);
6175338a5f7Sdanielk1977       }
6185338a5f7Sdanielk1977       break;
6195338a5f7Sdanielk1977     }
6202282792aSdrh 
62193758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
6222282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
6232282792aSdrh     ** then there should be a single item on the stack.  Write this
6242282792aSdrh     ** item into the set table with bogus data.
6252282792aSdrh     */
626c926afbcSdrh     case SRT_Set: {
62752b36cabSdrh       int addr2;
628e014a838Sdanielk1977 
629967e8b73Sdrh       assert( nColumn==1 );
63066a5167bSdrh       addr2 = sqlite3VdbeAddOp2(v, OP_IfMemNull, iMem+1, 0);
6316c8c8ce0Sdanielk1977       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
632c926afbcSdrh       if( pOrderBy ){
633de941c60Sdrh         /* At first glance you would think we could optimize out the
634de941c60Sdrh         ** ORDER BY in this case since the order of entries in the set
635de941c60Sdrh         ** does not matter.  But there might be a LIMIT clause, in which
636de941c60Sdrh         ** case the order does matter */
637*b1fdb2adSdrh         sqlite3VdbeAddOp2(v, OP_SCopy, iMem+1, 0);
638d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
639c926afbcSdrh       }else{
64066a5167bSdrh         sqlite3VdbeAddOp4(v, OP_RegMakeRec, iMem, 0, 0, &p->affinity, 1);
64166a5167bSdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, 0);
642c926afbcSdrh       }
643d654be80Sdrh       sqlite3VdbeJumpHere(v, addr2);
644c926afbcSdrh       break;
645c926afbcSdrh     }
64682c3d636Sdrh 
647504b6989Sdrh     /* If any row exist in the result set, record that fact and abort.
648ec7429aeSdrh     */
649ec7429aeSdrh     case SRT_Exists: {
6504c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
651ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
652ec7429aeSdrh       break;
653ec7429aeSdrh     }
654ec7429aeSdrh 
6552282792aSdrh     /* If this is a scalar select that is part of an expression, then
6562282792aSdrh     ** store the results in the appropriate memory cell and break out
6572282792aSdrh     ** of the scan loop.
6582282792aSdrh     */
659c926afbcSdrh     case SRT_Mem: {
660967e8b73Sdrh       assert( nColumn==1 );
661*b1fdb2adSdrh       sqlite3VdbeAddOp2(v, OP_SCopy, iMem+1, 0);
662c926afbcSdrh       if( pOrderBy ){
663d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
664c926afbcSdrh       }else{
665*b1fdb2adSdrh         sqlite3VdbeAddOp2(v, OP_Move, 0, iParm);
666ec7429aeSdrh         /* The LIMIT clause will jump out of the loop for us */
667c926afbcSdrh       }
668c926afbcSdrh       break;
669c926afbcSdrh     }
67093758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
6712282792aSdrh 
672c182d163Sdrh     /* Send the data to the callback function or to a subroutine.  In the
673c182d163Sdrh     ** case of a subroutine, the subroutine itself is responsible for
674c182d163Sdrh     ** popping the data from the stack.
675f46f905aSdrh     */
676c182d163Sdrh     case SRT_Subroutine:
6779d2985c7Sdrh     case SRT_Callback: {
678f46f905aSdrh       if( pOrderBy ){
67966a5167bSdrh         sqlite3VdbeAddOp2(v, OP_RegMakeRec, iMem, 0);
680d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
681c182d163Sdrh       }else if( eDest==SRT_Subroutine ){
682*b1fdb2adSdrh         for(i=0; i<nColumn; i++) sqlite3VdbeAddOp2(v, OP_SCopy, iMem+i+1, 0);
68366a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Gosub, 0, iParm);
684c182d163Sdrh       }else{
68566a5167bSdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, iMem+1, nColumn);
686ac82fcf5Sdrh       }
687142e30dfSdrh       break;
688142e30dfSdrh     }
689142e30dfSdrh 
6906a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER)
691d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
692d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
693d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
694d7489c39Sdrh     ** about the actual results of the select.
695d7489c39Sdrh     */
696c926afbcSdrh     default: {
697f46f905aSdrh       assert( eDest==SRT_Discard );
698c926afbcSdrh       break;
699c926afbcSdrh     }
70093758c8dSdanielk1977 #endif
701c926afbcSdrh   }
702ec7429aeSdrh 
703ec7429aeSdrh   /* Jump to the end of the loop if the LIMIT is reached.
704ec7429aeSdrh   */
705ec7429aeSdrh   if( p->iLimit>=0 && pOrderBy==0 ){
70666a5167bSdrh     sqlite3VdbeAddOp2(v, OP_MemIncr, -1, p->iLimit);
70766a5167bSdrh     sqlite3VdbeAddOp2(v, OP_IfMemZero, p->iLimit, iBreak);
708ec7429aeSdrh   }
70982c3d636Sdrh   return 0;
71082c3d636Sdrh }
71182c3d636Sdrh 
71282c3d636Sdrh /*
713dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records
714dece1a84Sdrh ** the collating sequence for each expression in that expression list.
715dece1a84Sdrh **
7160342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
7170342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to
7180342b1f5Sdrh ** implement that clause.  If the ExprList is the result set of a SELECT
7190342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual
7200342b1f5Sdrh ** index to implement a DISTINCT test.
7210342b1f5Sdrh **
722dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
723dece1a84Sdrh ** function is responsible for seeing that this structure is eventually
72466a5167bSdrh ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
72566a5167bSdrh ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
726dece1a84Sdrh */
727dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
728dece1a84Sdrh   sqlite3 *db = pParse->db;
729dece1a84Sdrh   int nExpr;
730dece1a84Sdrh   KeyInfo *pInfo;
731dece1a84Sdrh   struct ExprList_item *pItem;
732dece1a84Sdrh   int i;
733dece1a84Sdrh 
734dece1a84Sdrh   nExpr = pList->nExpr;
73517435752Sdrh   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
736dece1a84Sdrh   if( pInfo ){
7372646da7eSdrh     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
738dece1a84Sdrh     pInfo->nField = nExpr;
73914db2665Sdanielk1977     pInfo->enc = ENC(db);
740dece1a84Sdrh     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
741dece1a84Sdrh       CollSeq *pColl;
742dece1a84Sdrh       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
743dece1a84Sdrh       if( !pColl ){
744dece1a84Sdrh         pColl = db->pDfltColl;
745dece1a84Sdrh       }
746dece1a84Sdrh       pInfo->aColl[i] = pColl;
747dece1a84Sdrh       pInfo->aSortOrder[i] = pItem->sortOrder;
748dece1a84Sdrh     }
749dece1a84Sdrh   }
750dece1a84Sdrh   return pInfo;
751dece1a84Sdrh }
752dece1a84Sdrh 
753dece1a84Sdrh 
754dece1a84Sdrh /*
755d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
756d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
757d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
758d8bc7086Sdrh ** routine generates the code needed to do that.
759d8bc7086Sdrh */
760c926afbcSdrh static void generateSortTail(
761cdd536f0Sdrh   Parse *pParse,    /* Parsing context */
762c926afbcSdrh   Select *p,        /* The SELECT statement */
763c926afbcSdrh   Vdbe *v,          /* Generate code into this VDBE */
764c926afbcSdrh   int nColumn,      /* Number of columns of data */
7656c8c8ce0Sdanielk1977   SelectDest *pDest /* Write the sorted results here */
766c926afbcSdrh ){
7670342b1f5Sdrh   int brk = sqlite3VdbeMakeLabel(v);
7680342b1f5Sdrh   int cont = sqlite3VdbeMakeLabel(v);
769d8bc7086Sdrh   int addr;
7700342b1f5Sdrh   int iTab;
77161fc595fSdrh   int pseudoTab = 0;
7720342b1f5Sdrh   ExprList *pOrderBy = p->pOrderBy;
773ffbc3088Sdrh 
7746c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
7756c8c8ce0Sdanielk1977   int iParm = pDest->iParm;
7766c8c8ce0Sdanielk1977 
7779d2985c7Sdrh   iTab = pOrderBy->iECursor;
778cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
779cdd536f0Sdrh     pseudoTab = pParse->nTab++;
78066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, 0);
78166a5167bSdrh     sqlite3VdbeAddOp2(v, OP_SetNumColumns, pseudoTab, nColumn);
782cdd536f0Sdrh   }
78366a5167bSdrh   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, brk);
784ec7429aeSdrh   codeOffset(v, p, cont, 0);
785cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
78666a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Integer, 1, 0);
787cdd536f0Sdrh   }
78866a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Column, iTab, pOrderBy->nExpr + 1);
789c926afbcSdrh   switch( eDest ){
790c926afbcSdrh     case SRT_Table:
791b9bb7c18Sdrh     case SRT_EphemTab: {
7924c583128Sdrh       sqlite3VdbeAddOp1(v, OP_NewRowid, iParm);
79366a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Pull, 1, 0);
7941f4aa337Sdanielk1977       sqlite3CodeInsert(pParse, iParm, OPFLAG_APPEND);
795c926afbcSdrh       break;
796c926afbcSdrh     }
79793758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
798c926afbcSdrh     case SRT_Set: {
799c926afbcSdrh       assert( nColumn==1 );
80066a5167bSdrh       sqlite3VdbeAddOp2(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
80166a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Pop, 1, 0);
80266a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
80366a5167bSdrh       sqlite3VdbeAddOp4(v, OP_MakeRecord, 1, 0, 0, &p->affinity, 1);
80466a5167bSdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, 0);
805c926afbcSdrh       break;
806c926afbcSdrh     }
807c926afbcSdrh     case SRT_Mem: {
808c926afbcSdrh       assert( nColumn==1 );
809*b1fdb2adSdrh       sqlite3VdbeAddOp2(v, OP_Move, 0, iParm);
810ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
811c926afbcSdrh       break;
812c926afbcSdrh     }
81393758c8dSdanielk1977 #endif
814ce665cf6Sdrh     case SRT_Callback:
815ac82fcf5Sdrh     case SRT_Subroutine: {
816ac82fcf5Sdrh       int i;
8171f4aa337Sdanielk1977       sqlite3CodeInsert(pParse, pseudoTab, 0);
818ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
81966a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Column, pseudoTab, i);
820ac82fcf5Sdrh       }
821ce665cf6Sdrh       if( eDest==SRT_Callback ){
82266a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Callback, nColumn, 0);
823ce665cf6Sdrh       }else{
82466a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Gosub, 0, iParm);
825ce665cf6Sdrh       }
826ac82fcf5Sdrh       break;
827ac82fcf5Sdrh     }
828c926afbcSdrh     default: {
829f46f905aSdrh       /* Do nothing */
830c926afbcSdrh       break;
831c926afbcSdrh     }
832c926afbcSdrh   }
833ec7429aeSdrh 
834ec7429aeSdrh   /* Jump to the end of the loop when the LIMIT is reached
835ec7429aeSdrh   */
836ec7429aeSdrh   if( p->iLimit>=0 ){
83766a5167bSdrh     sqlite3VdbeAddOp2(v, OP_MemIncr, -1, p->iLimit);
83866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_IfMemZero, p->iLimit, brk);
839ec7429aeSdrh   }
840ec7429aeSdrh 
841ec7429aeSdrh   /* The bottom of the loop
842ec7429aeSdrh   */
8430342b1f5Sdrh   sqlite3VdbeResolveLabel(v, cont);
84466a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
8450342b1f5Sdrh   sqlite3VdbeResolveLabel(v, brk);
846cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
84766a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
848cdd536f0Sdrh   }
849cdd536f0Sdrh 
850d8bc7086Sdrh }
851d8bc7086Sdrh 
852d8bc7086Sdrh /*
853517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
854517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
855e78e8284Sdrh **
856955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the
857955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The
858955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
859955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The
860955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is
861955de52cSdanielk1977 ** considered a column by this function.
862e78e8284Sdrh **
863955de52cSdanielk1977 **   SELECT col FROM tbl;
864955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl;
865955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl);
866955de52cSdanielk1977 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
867955de52cSdanielk1977 **
868955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL.
869fcb78a49Sdrh */
870955de52cSdanielk1977 static const char *columnType(
871955de52cSdanielk1977   NameContext *pNC,
872955de52cSdanielk1977   Expr *pExpr,
873955de52cSdanielk1977   const char **pzOriginDb,
874955de52cSdanielk1977   const char **pzOriginTab,
875955de52cSdanielk1977   const char **pzOriginCol
876955de52cSdanielk1977 ){
877955de52cSdanielk1977   char const *zType = 0;
878955de52cSdanielk1977   char const *zOriginDb = 0;
879955de52cSdanielk1977   char const *zOriginTab = 0;
880955de52cSdanielk1977   char const *zOriginCol = 0;
881517eb646Sdanielk1977   int j;
882b3bce662Sdanielk1977   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
8835338a5f7Sdanielk1977 
88400e279d9Sdanielk1977   switch( pExpr->op ){
88530bcf5dbSdrh     case TK_AGG_COLUMN:
88600e279d9Sdanielk1977     case TK_COLUMN: {
887955de52cSdanielk1977       /* The expression is a column. Locate the table the column is being
888955de52cSdanielk1977       ** extracted from in NameContext.pSrcList. This table may be real
889955de52cSdanielk1977       ** database table or a subquery.
890955de52cSdanielk1977       */
891955de52cSdanielk1977       Table *pTab = 0;            /* Table structure column is extracted from */
892955de52cSdanielk1977       Select *pS = 0;             /* Select the column is extracted from */
893955de52cSdanielk1977       int iCol = pExpr->iColumn;  /* Index of column in pTab */
894b3bce662Sdanielk1977       while( pNC && !pTab ){
895b3bce662Sdanielk1977         SrcList *pTabList = pNC->pSrcList;
896b3bce662Sdanielk1977         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
897b3bce662Sdanielk1977         if( j<pTabList->nSrc ){
8986a3ea0e6Sdrh           pTab = pTabList->a[j].pTab;
899955de52cSdanielk1977           pS = pTabList->a[j].pSelect;
900b3bce662Sdanielk1977         }else{
901b3bce662Sdanielk1977           pNC = pNC->pNext;
902b3bce662Sdanielk1977         }
903b3bce662Sdanielk1977       }
904955de52cSdanielk1977 
9057e62779aSdrh       if( pTab==0 ){
9067e62779aSdrh         /* FIX ME:
9077e62779aSdrh         ** This can occurs if you have something like "SELECT new.x;" inside
9087e62779aSdrh         ** a trigger.  In other words, if you reference the special "new"
9097e62779aSdrh         ** table in the result set of a select.  We do not have a good way
9107e62779aSdrh         ** to find the actual table type, so call it "TEXT".  This is really
9117e62779aSdrh         ** something of a bug, but I do not know how to fix it.
9127e62779aSdrh         **
9137e62779aSdrh         ** This code does not produce the correct answer - it just prevents
9147e62779aSdrh         ** a segfault.  See ticket #1229.
9157e62779aSdrh         */
9167e62779aSdrh         zType = "TEXT";
9177e62779aSdrh         break;
9187e62779aSdrh       }
919955de52cSdanielk1977 
920b3bce662Sdanielk1977       assert( pTab );
921955de52cSdanielk1977       if( pS ){
922955de52cSdanielk1977         /* The "table" is actually a sub-select or a view in the FROM clause
923955de52cSdanielk1977         ** of the SELECT statement. Return the declaration type and origin
924955de52cSdanielk1977         ** data for the result-set column of the sub-select.
925955de52cSdanielk1977         */
926955de52cSdanielk1977         if( iCol>=0 && iCol<pS->pEList->nExpr ){
927955de52cSdanielk1977           /* If iCol is less than zero, then the expression requests the
928955de52cSdanielk1977           ** rowid of the sub-select or view. This expression is legal (see
929955de52cSdanielk1977           ** test case misc2.2.2) - it always evaluates to NULL.
930955de52cSdanielk1977           */
931955de52cSdanielk1977           NameContext sNC;
932955de52cSdanielk1977           Expr *p = pS->pEList->a[iCol].pExpr;
933955de52cSdanielk1977           sNC.pSrcList = pS->pSrc;
934955de52cSdanielk1977           sNC.pNext = 0;
935955de52cSdanielk1977           sNC.pParse = pNC->pParse;
936955de52cSdanielk1977           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
937955de52cSdanielk1977         }
9384b2688abSdanielk1977       }else if( pTab->pSchema ){
939955de52cSdanielk1977         /* A real table */
940955de52cSdanielk1977         assert( !pS );
941fcb78a49Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
942fcb78a49Sdrh         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
943fcb78a49Sdrh         if( iCol<0 ){
944fcb78a49Sdrh           zType = "INTEGER";
945955de52cSdanielk1977           zOriginCol = "rowid";
946fcb78a49Sdrh         }else{
947fcb78a49Sdrh           zType = pTab->aCol[iCol].zType;
948955de52cSdanielk1977           zOriginCol = pTab->aCol[iCol].zName;
949955de52cSdanielk1977         }
950955de52cSdanielk1977         zOriginTab = pTab->zName;
951955de52cSdanielk1977         if( pNC->pParse ){
952955de52cSdanielk1977           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
953955de52cSdanielk1977           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
954955de52cSdanielk1977         }
955fcb78a49Sdrh       }
95600e279d9Sdanielk1977       break;
957736c22b8Sdrh     }
95893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
95900e279d9Sdanielk1977     case TK_SELECT: {
960955de52cSdanielk1977       /* The expression is a sub-select. Return the declaration type and
961955de52cSdanielk1977       ** origin info for the single column in the result set of the SELECT
962955de52cSdanielk1977       ** statement.
963955de52cSdanielk1977       */
964b3bce662Sdanielk1977       NameContext sNC;
96500e279d9Sdanielk1977       Select *pS = pExpr->pSelect;
966955de52cSdanielk1977       Expr *p = pS->pEList->a[0].pExpr;
967955de52cSdanielk1977       sNC.pSrcList = pS->pSrc;
968b3bce662Sdanielk1977       sNC.pNext = pNC;
969955de52cSdanielk1977       sNC.pParse = pNC->pParse;
970955de52cSdanielk1977       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
97100e279d9Sdanielk1977       break;
972fcb78a49Sdrh     }
97393758c8dSdanielk1977 #endif
97400e279d9Sdanielk1977   }
97500e279d9Sdanielk1977 
976955de52cSdanielk1977   if( pzOriginDb ){
977955de52cSdanielk1977     assert( pzOriginTab && pzOriginCol );
978955de52cSdanielk1977     *pzOriginDb = zOriginDb;
979955de52cSdanielk1977     *pzOriginTab = zOriginTab;
980955de52cSdanielk1977     *pzOriginCol = zOriginCol;
981955de52cSdanielk1977   }
982517eb646Sdanielk1977   return zType;
983517eb646Sdanielk1977 }
984517eb646Sdanielk1977 
985517eb646Sdanielk1977 /*
986517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
987517eb646Sdanielk1977 ** in the result set.
988517eb646Sdanielk1977 */
989517eb646Sdanielk1977 static void generateColumnTypes(
990517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
991517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
992517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
993517eb646Sdanielk1977 ){
994517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
995517eb646Sdanielk1977   int i;
996b3bce662Sdanielk1977   NameContext sNC;
997b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
998955de52cSdanielk1977   sNC.pParse = pParse;
999517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
1000517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
1001955de52cSdanielk1977     const char *zOrigDb = 0;
1002955de52cSdanielk1977     const char *zOrigTab = 0;
1003955de52cSdanielk1977     const char *zOrigCol = 0;
1004955de52cSdanielk1977     const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
1005955de52cSdanielk1977 
100685b623f2Sdrh     /* The vdbe must make its own copy of the column-type and other
10074b1ae99dSdanielk1977     ** column specific strings, in case the schema is reset before this
10084b1ae99dSdanielk1977     ** virtual machine is deleted.
1009fbcd585fSdanielk1977     */
101066a5167bSdrh     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P4_TRANSIENT);
101166a5167bSdrh     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P4_TRANSIENT);
101266a5167bSdrh     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P4_TRANSIENT);
101366a5167bSdrh     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P4_TRANSIENT);
1014fcb78a49Sdrh   }
1015fcb78a49Sdrh }
1016fcb78a49Sdrh 
1017fcb78a49Sdrh /*
1018fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
1019fcb78a49Sdrh ** in the result set.  This information is used to provide the
1020fcabd464Sdrh ** azCol[] values in the callback.
102182c3d636Sdrh */
1022832508b7Sdrh static void generateColumnNames(
1023832508b7Sdrh   Parse *pParse,      /* Parser context */
1024ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
1025832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
1026832508b7Sdrh ){
1027d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
10286a3ea0e6Sdrh   int i, j;
10299bb575fdSdrh   sqlite3 *db = pParse->db;
1030fcabd464Sdrh   int fullNames, shortNames;
1031fcabd464Sdrh 
1032fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN
10333cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
10343cf86063Sdanielk1977   if( pParse->explain ){
103561de0d1bSdanielk1977     return;
10363cf86063Sdanielk1977   }
10375338a5f7Sdanielk1977 #endif
10383cf86063Sdanielk1977 
1039d6502758Sdrh   assert( v!=0 );
104017435752Sdrh   if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
1041d8bc7086Sdrh   pParse->colNamesSet = 1;
1042fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
1043fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
104422322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
104582c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
104682c3d636Sdrh     Expr *p;
10475a38705eSdrh     p = pEList->a[i].pExpr;
10485a38705eSdrh     if( p==0 ) continue;
104982c3d636Sdrh     if( pEList->a[i].zName ){
105082c3d636Sdrh       char *zName = pEList->a[i].zName;
1051955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
105282c3d636Sdrh       continue;
105382c3d636Sdrh     }
1054fa173a76Sdrh     if( p->op==TK_COLUMN && pTabList ){
10556a3ea0e6Sdrh       Table *pTab;
105697665873Sdrh       char *zCol;
10578aff1015Sdrh       int iCol = p->iColumn;
10586a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
10596a3ea0e6Sdrh       assert( j<pTabList->nSrc );
10606a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
10618aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
106297665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1063b1363206Sdrh       if( iCol<0 ){
106447a6db2bSdrh         zCol = "rowid";
1065b1363206Sdrh       }else{
1066b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
1067b1363206Sdrh       }
1068fcabd464Sdrh       if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
1069955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
1070fcabd464Sdrh       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
107182c3d636Sdrh         char *zName = 0;
107282c3d636Sdrh         char *zTab;
107382c3d636Sdrh 
10746a3ea0e6Sdrh         zTab = pTabList->a[j].zAlias;
1075fcabd464Sdrh         if( fullNames || zTab==0 ) zTab = pTab->zName;
1076f93339deSdrh         sqlite3SetString(&zName, zTab, ".", zCol, (char*)0);
107766a5167bSdrh         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P4_DYNAMIC);
107882c3d636Sdrh       }else{
1079955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
108082c3d636Sdrh       }
10816977fea8Sdrh     }else if( p->span.z && p->span.z[0] ){
1082955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
10833cf86063Sdanielk1977       /* sqlite3VdbeCompressSpace(v, addr); */
10841bee3d7bSdrh     }else{
10851bee3d7bSdrh       char zName[30];
10861bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
10875bb3eb9bSdrh       sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1);
1088955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0);
108982c3d636Sdrh     }
109082c3d636Sdrh   }
109176d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
10925080aaa7Sdrh }
109382c3d636Sdrh 
109493758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
109582c3d636Sdrh /*
1096d8bc7086Sdrh ** Name of the connection operator, used for error messages.
1097d8bc7086Sdrh */
1098d8bc7086Sdrh static const char *selectOpName(int id){
1099d8bc7086Sdrh   char *z;
1100d8bc7086Sdrh   switch( id ){
1101d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
1102d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
1103d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
1104d8bc7086Sdrh     default:           z = "UNION";       break;
1105d8bc7086Sdrh   }
1106d8bc7086Sdrh   return z;
1107d8bc7086Sdrh }
110893758c8dSdanielk1977 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1109d8bc7086Sdrh 
1110d8bc7086Sdrh /*
1111315555caSdrh ** Forward declaration
1112315555caSdrh */
11139b3187e1Sdrh static int prepSelectStmt(Parse*, Select*);
1114315555caSdrh 
1115315555caSdrh /*
111622f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
111722f70c32Sdrh ** the result set of that SELECT.
111822f70c32Sdrh */
11194adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
112022f70c32Sdrh   Table *pTab;
1121b733d037Sdrh   int i, j;
112222f70c32Sdrh   ExprList *pEList;
1123290c1948Sdrh   Column *aCol, *pCol;
112417435752Sdrh   sqlite3 *db = pParse->db;
112522f70c32Sdrh 
112692378253Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
11279b3187e1Sdrh   if( prepSelectStmt(pParse, pSelect) ){
112822f70c32Sdrh     return 0;
112922f70c32Sdrh   }
1130142bdf40Sdanielk1977   if( sqlite3SelectResolve(pParse, pSelect, 0) ){
1131142bdf40Sdanielk1977     return 0;
1132142bdf40Sdanielk1977   }
113317435752Sdrh   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
113422f70c32Sdrh   if( pTab==0 ){
113522f70c32Sdrh     return 0;
113622f70c32Sdrh   }
1137ed8a3bb1Sdrh   pTab->nRef = 1;
113817435752Sdrh   pTab->zName = zTabName ? sqlite3DbStrDup(db, zTabName) : 0;
113922f70c32Sdrh   pEList = pSelect->pEList;
114022f70c32Sdrh   pTab->nCol = pEList->nExpr;
1141417be79cSdrh   assert( pTab->nCol>0 );
114217435752Sdrh   pTab->aCol = aCol = sqlite3DbMallocZero(db, sizeof(pTab->aCol[0])*pTab->nCol);
1143290c1948Sdrh   for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
114479d5f63fSdrh     Expr *p, *pR;
1145517eb646Sdanielk1977     char *zType;
114691bb0eedSdrh     char *zName;
11472564ef97Sdrh     int nName;
1148b3bf556eSdanielk1977     CollSeq *pColl;
114979d5f63fSdrh     int cnt;
1150b3bce662Sdanielk1977     NameContext sNC;
115179d5f63fSdrh 
115279d5f63fSdrh     /* Get an appropriate name for the column
115379d5f63fSdrh     */
115479d5f63fSdrh     p = pEList->a[i].pExpr;
1155290c1948Sdrh     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
115691bb0eedSdrh     if( (zName = pEList->a[i].zName)!=0 ){
115779d5f63fSdrh       /* If the column contains an "AS <name>" phrase, use <name> as the name */
115817435752Sdrh       zName = sqlite3DbStrDup(db, zName);
1159517eb646Sdanielk1977     }else if( p->op==TK_DOT
1160b733d037Sdrh               && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
116179d5f63fSdrh       /* For columns of the from A.B use B as the name */
116217435752Sdrh       zName = sqlite3MPrintf(db, "%T", &pR->token);
1163b733d037Sdrh     }else if( p->span.z && p->span.z[0] ){
116479d5f63fSdrh       /* Use the original text of the column expression as its name */
116517435752Sdrh       zName = sqlite3MPrintf(db, "%T", &p->span);
116622f70c32Sdrh     }else{
116779d5f63fSdrh       /* If all else fails, make up a name */
116817435752Sdrh       zName = sqlite3MPrintf(db, "column%d", i+1);
116922f70c32Sdrh     }
11707751940dSdanielk1977     if( !zName || db->mallocFailed ){
11717751940dSdanielk1977       db->mallocFailed = 1;
117217435752Sdrh       sqlite3_free(zName);
1173a04a34ffSdanielk1977       sqlite3DeleteTable(pTab);
1174dd5b2fa5Sdrh       return 0;
1175dd5b2fa5Sdrh     }
11767751940dSdanielk1977     sqlite3Dequote(zName);
117779d5f63fSdrh 
117879d5f63fSdrh     /* Make sure the column name is unique.  If the name is not unique,
117979d5f63fSdrh     ** append a integer to the name so that it becomes unique.
118079d5f63fSdrh     */
11812564ef97Sdrh     nName = strlen(zName);
118279d5f63fSdrh     for(j=cnt=0; j<i; j++){
118379d5f63fSdrh       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
11842564ef97Sdrh         zName[nName] = 0;
11851e536953Sdanielk1977         zName = sqlite3MPrintf(db, "%z:%d", zName, ++cnt);
118679d5f63fSdrh         j = -1;
1187dd5b2fa5Sdrh         if( zName==0 ) break;
118879d5f63fSdrh       }
118979d5f63fSdrh     }
119091bb0eedSdrh     pCol->zName = zName;
1191e014a838Sdanielk1977 
119279d5f63fSdrh     /* Get the typename, type affinity, and collating sequence for the
119379d5f63fSdrh     ** column.
119479d5f63fSdrh     */
1195c43e8be8Sdrh     memset(&sNC, 0, sizeof(sNC));
1196b3bce662Sdanielk1977     sNC.pSrcList = pSelect->pSrc;
119717435752Sdrh     zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
1198290c1948Sdrh     pCol->zType = zType;
1199c60e9b82Sdanielk1977     pCol->affinity = sqlite3ExprAffinity(p);
1200b3bf556eSdanielk1977     pColl = sqlite3ExprCollSeq(pParse, p);
1201b3bf556eSdanielk1977     if( pColl ){
120217435752Sdrh       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
12030202b29eSdanielk1977     }
120422f70c32Sdrh   }
120522f70c32Sdrh   pTab->iPKey = -1;
120622f70c32Sdrh   return pTab;
120722f70c32Sdrh }
120822f70c32Sdrh 
120922f70c32Sdrh /*
12109b3187e1Sdrh ** Prepare a SELECT statement for processing by doing the following
12119b3187e1Sdrh ** things:
1212d8bc7086Sdrh **
12139b3187e1Sdrh **    (1)  Make sure VDBE cursor numbers have been assigned to every
12149b3187e1Sdrh **         element of the FROM clause.
12159b3187e1Sdrh **
12169b3187e1Sdrh **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
12179b3187e1Sdrh **         defines FROM clause.  When views appear in the FROM clause,
121863eb5f29Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
121963eb5f29Sdrh **         that implements the view.  A copy is made of the view's SELECT
122063eb5f29Sdrh **         statement so that we can freely modify or delete that statement
122163eb5f29Sdrh **         without worrying about messing up the presistent representation
122263eb5f29Sdrh **         of the view.
1223d8bc7086Sdrh **
12249b3187e1Sdrh **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
1225ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
1226ad2d8307Sdrh **
12279b3187e1Sdrh **    (4)  Scan the list of columns in the result set (pEList) looking
122854473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
122954473229Sdrh **         If found, expand each "*" to be every column in every table
123054473229Sdrh **         and TABLE.* to be every column in TABLE.
1231d8bc7086Sdrh **
1232d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
1233d8bc7086Sdrh ** in pParse and return non-zero.
1234d8bc7086Sdrh */
12359b3187e1Sdrh static int prepSelectStmt(Parse *pParse, Select *p){
123654473229Sdrh   int i, j, k, rc;
1237ad3cab52Sdrh   SrcList *pTabList;
1238daffd0e5Sdrh   ExprList *pEList;
1239290c1948Sdrh   struct SrcList_item *pFrom;
124017435752Sdrh   sqlite3 *db = pParse->db;
1241daffd0e5Sdrh 
124217435752Sdrh   if( p==0 || p->pSrc==0 || db->mallocFailed ){
12436f7adc8aSdrh     return 1;
12446f7adc8aSdrh   }
1245daffd0e5Sdrh   pTabList = p->pSrc;
1246daffd0e5Sdrh   pEList = p->pEList;
1247d8bc7086Sdrh 
12489b3187e1Sdrh   /* Make sure cursor numbers have been assigned to all entries in
12499b3187e1Sdrh   ** the FROM clause of the SELECT statement.
12509b3187e1Sdrh   */
12519b3187e1Sdrh   sqlite3SrcListAssignCursors(pParse, p->pSrc);
12529b3187e1Sdrh 
12539b3187e1Sdrh   /* Look up every table named in the FROM clause of the select.  If
12549b3187e1Sdrh   ** an entry of the FROM clause is a subquery instead of a table or view,
12559b3187e1Sdrh   ** then create a transient table structure to describe the subquery.
1256d8bc7086Sdrh   */
1257290c1948Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1258f0113000Sdanielk1977     Table *pTab;
12599b3187e1Sdrh     if( pFrom->pTab!=0 ){
12609b3187e1Sdrh       /* This statement has already been prepared.  There is no need
12619b3187e1Sdrh       ** to go further. */
12629b3187e1Sdrh       assert( i==0 );
1263d8bc7086Sdrh       return 0;
1264d8bc7086Sdrh     }
1265290c1948Sdrh     if( pFrom->zName==0 ){
126693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
126722f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
1268290c1948Sdrh       assert( pFrom->pSelect!=0 );
1269290c1948Sdrh       if( pFrom->zAlias==0 ){
127091bb0eedSdrh         pFrom->zAlias =
12711e536953Sdanielk1977           sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pFrom->pSelect);
1272ad2d8307Sdrh       }
1273ed8a3bb1Sdrh       assert( pFrom->pTab==0 );
1274290c1948Sdrh       pFrom->pTab = pTab =
1275290c1948Sdrh         sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
127622f70c32Sdrh       if( pTab==0 ){
1277daffd0e5Sdrh         return 1;
1278daffd0e5Sdrh       }
1279b9bb7c18Sdrh       /* The isEphem flag indicates that the Table structure has been
12805cf590c1Sdrh       ** dynamically allocated and may be freed at any time.  In other words,
12815cf590c1Sdrh       ** pTab is not pointing to a persistent table structure that defines
12825cf590c1Sdrh       ** part of the schema. */
1283b9bb7c18Sdrh       pTab->isEphem = 1;
128493758c8dSdanielk1977 #endif
128522f70c32Sdrh     }else{
1286a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
1287ed8a3bb1Sdrh       assert( pFrom->pTab==0 );
1288290c1948Sdrh       pFrom->pTab = pTab =
1289290c1948Sdrh         sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
1290a76b5dfcSdrh       if( pTab==0 ){
1291d8bc7086Sdrh         return 1;
1292d8bc7086Sdrh       }
1293ed8a3bb1Sdrh       pTab->nRef++;
129493626f48Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
129593626f48Sdanielk1977       if( pTab->pSelect || IsVirtual(pTab) ){
129663eb5f29Sdrh         /* We reach here if the named table is a really a view */
12974adee20fSdanielk1977         if( sqlite3ViewGetColumnNames(pParse, pTab) ){
1298417be79cSdrh           return 1;
1299417be79cSdrh         }
1300290c1948Sdrh         /* If pFrom->pSelect!=0 it means we are dealing with a
130163eb5f29Sdrh         ** view within a view.  The SELECT structure has already been
130263eb5f29Sdrh         ** copied by the outer view so we can skip the copy step here
130363eb5f29Sdrh         ** in the inner view.
130463eb5f29Sdrh         */
1305290c1948Sdrh         if( pFrom->pSelect==0 ){
130617435752Sdrh           pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
1307a76b5dfcSdrh         }
1308d8bc7086Sdrh       }
130993758c8dSdanielk1977 #endif
131022f70c32Sdrh     }
131163eb5f29Sdrh   }
1312d8bc7086Sdrh 
1313ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
1314ad2d8307Sdrh   */
1315ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
1316ad2d8307Sdrh 
13177c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
131854473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
131954473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
13207c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
13217c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
13227c917d19Sdrh   ** each one to the list of all columns in all tables.
132354473229Sdrh   **
132454473229Sdrh   ** The first loop just checks to see if there are any "*" operators
132554473229Sdrh   ** that need expanding.
1326d8bc7086Sdrh   */
13277c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
132854473229Sdrh     Expr *pE = pEList->a[k].pExpr;
132954473229Sdrh     if( pE->op==TK_ALL ) break;
133054473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
133154473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
13327c917d19Sdrh   }
133354473229Sdrh   rc = 0;
13347c917d19Sdrh   if( k<pEList->nExpr ){
133554473229Sdrh     /*
133654473229Sdrh     ** If we get here it means the result set contains one or more "*"
133754473229Sdrh     ** operators that need to be expanded.  Loop through each expression
133854473229Sdrh     ** in the result set and expand them one by one.
133954473229Sdrh     */
13407c917d19Sdrh     struct ExprList_item *a = pEList->a;
13417c917d19Sdrh     ExprList *pNew = 0;
1342d70dc52dSdrh     int flags = pParse->db->flags;
1343d70dc52dSdrh     int longNames = (flags & SQLITE_FullColNames)!=0 &&
1344d70dc52dSdrh                       (flags & SQLITE_ShortColNames)==0;
1345d70dc52dSdrh 
13467c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
134754473229Sdrh       Expr *pE = a[k].pExpr;
134854473229Sdrh       if( pE->op!=TK_ALL &&
134954473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
135054473229Sdrh         /* This particular expression does not need to be expanded.
135154473229Sdrh         */
135217435752Sdrh         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
1353261919ccSdanielk1977         if( pNew ){
13547c917d19Sdrh           pNew->a[pNew->nExpr-1].zName = a[k].zName;
1355261919ccSdanielk1977         }else{
1356261919ccSdanielk1977           rc = 1;
1357261919ccSdanielk1977         }
13587c917d19Sdrh         a[k].pExpr = 0;
13597c917d19Sdrh         a[k].zName = 0;
13607c917d19Sdrh       }else{
136154473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
136254473229Sdrh         ** expanded. */
136354473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
1364cf55b7aeSdrh         char *zTName;            /* text of name of TABLE */
136554473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
136617435752Sdrh           zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
136754473229Sdrh         }else{
1368cf55b7aeSdrh           zTName = 0;
136954473229Sdrh         }
1370290c1948Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1371290c1948Sdrh           Table *pTab = pFrom->pTab;
1372290c1948Sdrh           char *zTabName = pFrom->zAlias;
137354473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
137454473229Sdrh             zTabName = pTab->zName;
137554473229Sdrh           }
1376cf55b7aeSdrh           if( zTName && (zTabName==0 || zTabName[0]==0 ||
1377cf55b7aeSdrh                  sqlite3StrICmp(zTName, zTabName)!=0) ){
137854473229Sdrh             continue;
137954473229Sdrh           }
138054473229Sdrh           tableSeen = 1;
1381d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
1382f0113000Sdanielk1977             Expr *pExpr, *pRight;
1383ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
1384ad2d8307Sdrh 
1385034ca14fSdanielk1977             /* If a column is marked as 'hidden' (currently only possible
1386034ca14fSdanielk1977             ** for virtual tables), do not include it in the expanded
1387034ca14fSdanielk1977             ** result-set list.
1388034ca14fSdanielk1977             */
1389034ca14fSdanielk1977             if( IsHiddenColumn(&pTab->aCol[j]) ){
1390034ca14fSdanielk1977               assert(IsVirtual(pTab));
1391034ca14fSdanielk1977               continue;
1392034ca14fSdanielk1977             }
1393034ca14fSdanielk1977 
139491bb0eedSdrh             if( i>0 ){
139591bb0eedSdrh               struct SrcList_item *pLeft = &pTabList->a[i-1];
139661dfc31dSdrh               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
139791bb0eedSdrh                         columnIndex(pLeft->pTab, zName)>=0 ){
1398ad2d8307Sdrh                 /* In a NATURAL join, omit the join columns from the
1399ad2d8307Sdrh                 ** table on the right */
1400ad2d8307Sdrh                 continue;
1401ad2d8307Sdrh               }
140261dfc31dSdrh               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
1403ad2d8307Sdrh                 /* In a join with a USING clause, omit columns in the
1404ad2d8307Sdrh                 ** using clause from the table on the right. */
1405ad2d8307Sdrh                 continue;
1406ad2d8307Sdrh               }
140791bb0eedSdrh             }
1408a1644fd8Sdanielk1977             pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
140922f70c32Sdrh             if( pRight==0 ) break;
14101e536953Sdanielk1977             setQuotedToken(pParse, &pRight->token, zName);
1411d70dc52dSdrh             if( zTabName && (longNames || pTabList->nSrc>1) ){
1412a1644fd8Sdanielk1977               Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
1413a1644fd8Sdanielk1977               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
141422f70c32Sdrh               if( pExpr==0 ) break;
14151e536953Sdanielk1977               setQuotedToken(pParse, &pLeft->token, zTabName);
14161e536953Sdanielk1977               setToken(&pExpr->span,
14171e536953Sdanielk1977                   sqlite3MPrintf(db, "%s.%s", zTabName, zName));
14186977fea8Sdrh               pExpr->span.dyn = 1;
14196977fea8Sdrh               pExpr->token.z = 0;
14206977fea8Sdrh               pExpr->token.n = 0;
14216977fea8Sdrh               pExpr->token.dyn = 0;
142222f70c32Sdrh             }else{
142322f70c32Sdrh               pExpr = pRight;
14246977fea8Sdrh               pExpr->span = pExpr->token;
1425f3b863edSdanielk1977               pExpr->span.dyn = 0;
142622f70c32Sdrh             }
1427d70dc52dSdrh             if( longNames ){
142817435752Sdrh               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
1429d70dc52dSdrh             }else{
143017435752Sdrh               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
1431d8bc7086Sdrh             }
1432d8bc7086Sdrh           }
1433d70dc52dSdrh         }
143454473229Sdrh         if( !tableSeen ){
1435cf55b7aeSdrh           if( zTName ){
1436cf55b7aeSdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
1437f5db2d3eSdrh           }else{
14384adee20fSdanielk1977             sqlite3ErrorMsg(pParse, "no tables specified");
1439f5db2d3eSdrh           }
144054473229Sdrh           rc = 1;
144154473229Sdrh         }
144217435752Sdrh         sqlite3_free(zTName);
14437c917d19Sdrh       }
14447c917d19Sdrh     }
14454adee20fSdanielk1977     sqlite3ExprListDelete(pEList);
14467c917d19Sdrh     p->pEList = pNew;
1447d8bc7086Sdrh   }
1448e5c941b8Sdrh   if( p->pEList && p->pEList->nExpr>SQLITE_MAX_COLUMN ){
1449e5c941b8Sdrh     sqlite3ErrorMsg(pParse, "too many columns in result set");
1450e5c941b8Sdrh     rc = SQLITE_ERROR;
1451e5c941b8Sdrh   }
145217435752Sdrh   if( db->mallocFailed ){
1453f3b863edSdanielk1977     rc = SQLITE_NOMEM;
1454f3b863edSdanielk1977   }
145554473229Sdrh   return rc;
1456d8bc7086Sdrh }
1457d8bc7086Sdrh 
1458ff78bd2fSdrh /*
14599a99334dSdrh ** pE is a pointer to an expression which is a single term in
14609a99334dSdrh ** ORDER BY or GROUP BY clause.
1461d8bc7086Sdrh **
14629a99334dSdrh ** If pE evaluates to an integer constant i, then return i.
14639a99334dSdrh ** This is an indication to the caller that it should sort
14649a99334dSdrh ** by the i-th column of the result set.
14659a99334dSdrh **
14669a99334dSdrh ** If pE is a well-formed expression and the SELECT statement
14679a99334dSdrh ** is not compound, then return 0.  This indicates to the
14689a99334dSdrh ** caller that it should sort by the value of the ORDER BY
14699a99334dSdrh ** expression.
14709a99334dSdrh **
14719a99334dSdrh ** If the SELECT is compound, then attempt to match pE against
14729a99334dSdrh ** result set columns in the left-most SELECT statement.  Return
14739a99334dSdrh ** the index i of the matching column, as an indication to the
14749a99334dSdrh ** caller that it should sort by the i-th column.  If there is
14759a99334dSdrh ** no match, return -1 and leave an error message in pParse.
1476d8bc7086Sdrh */
14779a99334dSdrh static int matchOrderByTermToExprList(
14789a99334dSdrh   Parse *pParse,     /* Parsing context for error messages */
14799a99334dSdrh   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
14809a99334dSdrh   Expr *pE,          /* The specific ORDER BY term */
14819a99334dSdrh   int idx,           /* When ORDER BY term is this */
14829a99334dSdrh   int isCompound,    /* True if this is a compound SELECT */
14839a99334dSdrh   u8 *pHasAgg        /* True if expression contains aggregate functions */
1484d8bc7086Sdrh ){
14859a99334dSdrh   int i;             /* Loop counter */
14869a99334dSdrh   ExprList *pEList;  /* The columns of the result set */
14879a99334dSdrh   NameContext nc;    /* Name context for resolving pE */
14889a99334dSdrh 
14899a99334dSdrh 
14909a99334dSdrh   /* If the term is an integer constant, return the value of that
14919a99334dSdrh   ** constant */
14929a99334dSdrh   pEList = pSelect->pEList;
14939a99334dSdrh   if( sqlite3ExprIsInteger(pE, &i) ){
14949a99334dSdrh     if( i<=0 ){
14959a99334dSdrh       /* If i is too small, make it too big.  That way the calling
14969a99334dSdrh       ** function still sees a value that is out of range, but does
14979a99334dSdrh       ** not confuse the column number with 0 or -1 result code.
14989a99334dSdrh       */
14999a99334dSdrh       i = pEList->nExpr+1;
15009a99334dSdrh     }
15019a99334dSdrh     return i;
15029a99334dSdrh   }
15039a99334dSdrh 
15049a99334dSdrh   /* If the term is a simple identifier that try to match that identifier
15059a99334dSdrh   ** against a column name in the result set.
15069a99334dSdrh   */
15079a99334dSdrh   if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){
150817435752Sdrh     sqlite3 *db = pParse->db;
15099a99334dSdrh     char *zCol = sqlite3NameFromToken(db, &pE->token);
1510ef0bea92Sdrh     if( zCol==0 ){
15119a99334dSdrh       return -1;
15129a99334dSdrh     }
15139a99334dSdrh     for(i=0; i<pEList->nExpr; i++){
15149a99334dSdrh       char *zAs = pEList->a[i].zName;
15159a99334dSdrh       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
15169a99334dSdrh         sqlite3_free(zCol);
15179a99334dSdrh         return i+1;
15189a99334dSdrh       }
15199a99334dSdrh     }
15209a99334dSdrh     sqlite3_free(zCol);
15214c774314Sdrh   }
152270517ab9Sdanielk1977 
15239a99334dSdrh   /* Resolve all names in the ORDER BY term expression
15249a99334dSdrh   */
152570517ab9Sdanielk1977   memset(&nc, 0, sizeof(nc));
152670517ab9Sdanielk1977   nc.pParse = pParse;
15279a99334dSdrh   nc.pSrcList = pSelect->pSrc;
152870517ab9Sdanielk1977   nc.pEList = pEList;
152970517ab9Sdanielk1977   nc.allowAgg = 1;
15304c774314Sdrh   nc.nErr = 0;
15319a99334dSdrh   if( sqlite3ExprResolveNames(&nc, pE) ){
15321e281291Sdrh     if( isCompound ){
15331e281291Sdrh       sqlite3ErrorClear(pParse);
15341e281291Sdrh       return 0;
15351e281291Sdrh     }else{
15369a99334dSdrh       return -1;
15379a99334dSdrh     }
15381e281291Sdrh   }
15399a99334dSdrh   if( nc.hasAgg && pHasAgg ){
15409a99334dSdrh     *pHasAgg = 1;
15419a99334dSdrh   }
15429a99334dSdrh 
15439a99334dSdrh   /* For a compound SELECT, we need to try to match the ORDER BY
15449a99334dSdrh   ** expression against an expression in the result set
15459a99334dSdrh   */
15469a99334dSdrh   if( isCompound ){
15479a99334dSdrh     for(i=0; i<pEList->nExpr; i++){
15489a99334dSdrh       if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
15499a99334dSdrh         return i+1;
15509a99334dSdrh       }
15519a99334dSdrh     }
15524c774314Sdrh   }
15531e281291Sdrh   return 0;
155470517ab9Sdanielk1977 }
155570517ab9Sdanielk1977 
15569a99334dSdrh 
15579a99334dSdrh /*
15589a99334dSdrh ** Analyze and ORDER BY or GROUP BY clause in a simple SELECT statement.
15599a99334dSdrh ** Return the number of errors seen.
15609a99334dSdrh **
15619a99334dSdrh ** Every term of the ORDER BY or GROUP BY clause needs to be an
15629a99334dSdrh ** expression.  If any expression is an integer constant, then
15639a99334dSdrh ** that expression is replaced by the corresponding
15649a99334dSdrh ** expression from the result set.
15659a99334dSdrh */
15669a99334dSdrh static int processOrderGroupBy(
15679a99334dSdrh   Parse *pParse,        /* Parsing context.  Leave error messages here */
15689a99334dSdrh   Select *pSelect,      /* The SELECT statement containing the clause */
15699a99334dSdrh   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
15709a99334dSdrh   int isOrder,          /* 1 for ORDER BY.  0 for GROUP BY */
15719a99334dSdrh   u8 *pHasAgg           /* Set to TRUE if any term contains an aggregate */
15729a99334dSdrh ){
15739a99334dSdrh   int i;
15749a99334dSdrh   sqlite3 *db = pParse->db;
15759a99334dSdrh   ExprList *pEList;
15769a99334dSdrh 
15779a99334dSdrh   if( pOrderBy==0 ) return 0;
15789a99334dSdrh   if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){
15799a99334dSdrh     const char *zType = isOrder ? "ORDER" : "GROUP";
15809a99334dSdrh     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
15819a99334dSdrh     return 1;
15829a99334dSdrh   }
15839a99334dSdrh   pEList = pSelect->pEList;
15849a99334dSdrh   if( pEList==0 ){
15859a99334dSdrh     return 0;
15869a99334dSdrh   }
15879a99334dSdrh   for(i=0; i<pOrderBy->nExpr; i++){
15889a99334dSdrh     int iCol;
15899a99334dSdrh     Expr *pE = pOrderBy->a[i].pExpr;
15909a99334dSdrh     iCol = matchOrderByTermToExprList(pParse, pSelect, pE, i+1, 0, pHasAgg);
159170517ab9Sdanielk1977     if( iCol<0 ){
15929a99334dSdrh       return 1;
15939a99334dSdrh     }
15949a99334dSdrh     if( iCol>pEList->nExpr ){
15959a99334dSdrh       const char *zType = isOrder ? "ORDER" : "GROUP";
159670517ab9Sdanielk1977       sqlite3ErrorMsg(pParse,
15979a99334dSdrh          "%r %s BY term out of range - should be "
15989a99334dSdrh          "between 1 and %d", i+1, zType, pEList->nExpr);
15999a99334dSdrh       return 1;
16009a99334dSdrh     }
16019a99334dSdrh     if( iCol>0 ){
16029a99334dSdrh       CollSeq *pColl = pE->pColl;
16039a99334dSdrh       int flags = pE->flags & EP_ExpCollate;
16049a99334dSdrh       sqlite3ExprDelete(pE);
16059a99334dSdrh       pE = sqlite3ExprDup(db, pEList->a[iCol-1].pExpr);
16069a99334dSdrh       pOrderBy->a[i].pExpr = pE;
16079a99334dSdrh       if( pColl && flags ){
16089a99334dSdrh         pE->pColl = pColl;
16099a99334dSdrh         pE->flags |= flags;
16109a99334dSdrh       }
16119a99334dSdrh     }
16129a99334dSdrh   }
16139a99334dSdrh   return 0;
16149a99334dSdrh }
16159a99334dSdrh 
16169a99334dSdrh /*
16179a99334dSdrh ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement.  Return
16189a99334dSdrh ** the number of errors seen.
16199a99334dSdrh **
16209a99334dSdrh ** The processing depends on whether the SELECT is simple or compound.
16219a99334dSdrh ** For a simple SELECT statement, evry term of the ORDER BY or GROUP BY
16229a99334dSdrh ** clause needs to be an expression.  If any expression is an integer
16239a99334dSdrh ** constant, then that expression is replaced by the corresponding
16249a99334dSdrh ** expression from the result set.
16259a99334dSdrh **
16269a99334dSdrh ** For compound SELECT statements, every expression needs to be of
16279a99334dSdrh ** type TK_COLUMN with a iTable value as given in the 4th parameter.
16289a99334dSdrh ** If any expression is an integer, that becomes the column number.
16299a99334dSdrh ** Otherwise, match the expression against result set columns from
16309a99334dSdrh ** the left-most SELECT.
16319a99334dSdrh */
16329a99334dSdrh static int processCompoundOrderBy(
16339a99334dSdrh   Parse *pParse,        /* Parsing context.  Leave error messages here */
16349a99334dSdrh   Select *pSelect,      /* The SELECT statement containing the ORDER BY */
16359a99334dSdrh   int iTable            /* Output table for compound SELECT statements */
16369a99334dSdrh ){
16379a99334dSdrh   int i;
16389a99334dSdrh   ExprList *pOrderBy;
16399a99334dSdrh   ExprList *pEList;
16401e281291Sdrh   sqlite3 *db;
16411e281291Sdrh   int moreToDo = 1;
16429a99334dSdrh 
16439a99334dSdrh   pOrderBy = pSelect->pOrderBy;
16449a99334dSdrh   if( pOrderBy==0 ) return 0;
16459a99334dSdrh   if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){
16469a99334dSdrh     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
16479a99334dSdrh     return 1;
16489a99334dSdrh   }
16491e281291Sdrh   db = pParse->db;
16501e281291Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
16511e281291Sdrh     pOrderBy->a[i].done = 0;
16521e281291Sdrh   }
16539a99334dSdrh   while( pSelect->pPrior ){
16549a99334dSdrh     pSelect = pSelect->pPrior;
16559a99334dSdrh   }
16561e281291Sdrh   while( pSelect && moreToDo ){
16571e281291Sdrh     moreToDo = 0;
16589a99334dSdrh     for(i=0; i<pOrderBy->nExpr; i++){
16599a99334dSdrh       int iCol;
16608f0ecaaeSdrh       Expr *pE, *pDup;
16611e281291Sdrh       if( pOrderBy->a[i].done ) continue;
16621e281291Sdrh       pE = pOrderBy->a[i].pExpr;
16638f0ecaaeSdrh       pDup = sqlite3ExprDup(db, pE);
16641e281291Sdrh       if( pDup==0 ){
16651e281291Sdrh         return 1;
16661e281291Sdrh       }
16671e281291Sdrh       iCol = matchOrderByTermToExprList(pParse, pSelect, pDup, i+1, 1, 0);
16681e281291Sdrh       sqlite3ExprDelete(pDup);
16699a99334dSdrh       if( iCol<0 ){
16709a99334dSdrh         return 1;
16719a99334dSdrh       }
16721e281291Sdrh       pEList = pSelect->pEList;
16731e281291Sdrh       if( pEList==0 ){
16741e281291Sdrh         return 1;
16751e281291Sdrh       }
16769a99334dSdrh       if( iCol>pEList->nExpr ){
16779a99334dSdrh         sqlite3ErrorMsg(pParse,
16789a99334dSdrh            "%r ORDER BY term out of range - should be "
16799a99334dSdrh            "between 1 and %d", i+1, pEList->nExpr);
16809a99334dSdrh         return 1;
16819a99334dSdrh       }
16821e281291Sdrh       if( iCol>0 ){
1683967e8b73Sdrh         pE->op = TK_COLUMN;
1684d8bc7086Sdrh         pE->iTable = iTable;
1685a58fdfb1Sdanielk1977         pE->iAgg = -1;
16869a99334dSdrh         pE->iColumn = iCol-1;
16879a99334dSdrh         pE->pTab = 0;
16881e281291Sdrh         pOrderBy->a[i].done = 1;
16891e281291Sdrh       }else{
16901e281291Sdrh         moreToDo = 1;
16911e281291Sdrh       }
16921e281291Sdrh     }
16931e281291Sdrh     pSelect = pSelect->pNext;
16941e281291Sdrh   }
16951e281291Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
16961e281291Sdrh     if( pOrderBy->a[i].done==0 ){
16971e281291Sdrh       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
16981e281291Sdrh             "column in the result set", i+1);
16991e281291Sdrh       return 1;
17001e281291Sdrh     }
170170517ab9Sdanielk1977   }
17029a99334dSdrh   return 0;
1703d8bc7086Sdrh }
1704d8bc7086Sdrh 
1705d8bc7086Sdrh /*
1706d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1707d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1708d8bc7086Sdrh */
17094adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1710d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1711d8bc7086Sdrh   if( v==0 ){
17124adee20fSdanielk1977     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1713d8bc7086Sdrh   }
1714d8bc7086Sdrh   return v;
1715d8bc7086Sdrh }
1716d8bc7086Sdrh 
171715007a99Sdrh 
1718d8bc7086Sdrh /*
17197b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
1720ec7429aeSdrh ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
17217b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
1722a2dc3b1aSdanielk1977 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1723a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute
1724a2dc3b1aSdanielk1977 ** the limit and offset.  If there is no limit and/or offset, then
1725a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative.
17267b58daeaSdrh **
1727d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if
1728ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset.  iLimit and
17297b58daeaSdrh ** iOffset should have been preset to appropriate default values
17307b58daeaSdrh ** (usually but not always -1) prior to calling this routine.
1731ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
17327b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
17337b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
17347b58daeaSdrh ** SELECT statements.
17357b58daeaSdrh */
1736ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
173702afc861Sdrh   Vdbe *v = 0;
173802afc861Sdrh   int iLimit = 0;
173915007a99Sdrh   int iOffset;
174015007a99Sdrh   int addr1, addr2;
174115007a99Sdrh 
17427b58daeaSdrh   /*
17437b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
17447b58daeaSdrh   ** contraversy about what the correct behavior should be.
17457b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
17467b58daeaSdrh   ** no rows.
17477b58daeaSdrh   */
1748a2dc3b1aSdanielk1977   if( p->pLimit ){
17490a07c107Sdrh     p->iLimit = iLimit = ++pParse->nMem;
17500a07c107Sdrh     pParse->nMem++;
175115007a99Sdrh     v = sqlite3GetVdbe(pParse);
17527b58daeaSdrh     if( v==0 ) return;
1753389a1adbSdrh     sqlite3ExprCode(pParse, p->pLimit, 0);
175466a5167bSdrh     sqlite3VdbeAddOp2(v, OP_MustBeInt, 0, 0);
1755*b1fdb2adSdrh     sqlite3VdbeAddOp2(v, OP_Move, 0, iLimit);
1756d4e70ebdSdrh     VdbeComment((v, "LIMIT counter"));
175766a5167bSdrh     sqlite3VdbeAddOp2(v, OP_IfMemZero, iLimit, iBreak);
1758*b1fdb2adSdrh     sqlite3VdbeAddOp2(v, OP_SCopy, iLimit, 0);
17597b58daeaSdrh   }
1760a2dc3b1aSdanielk1977   if( p->pOffset ){
17610a07c107Sdrh     p->iOffset = iOffset = ++pParse->nMem;
176215007a99Sdrh     v = sqlite3GetVdbe(pParse);
17637b58daeaSdrh     if( v==0 ) return;
1764389a1adbSdrh     sqlite3ExprCode(pParse, p->pOffset, 0);
176566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_MustBeInt, 0, 0);
1766*b1fdb2adSdrh     sqlite3VdbeAddOp2(v, p->pLimit==0 ? OP_Move : OP_Copy, 0, iOffset);
1767d4e70ebdSdrh     VdbeComment((v, "OFFSET counter"));
176866a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_IfMemPos, iOffset, 0);
176966a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Pop, 1, 0);
177066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
177115007a99Sdrh     sqlite3VdbeJumpHere(v, addr1);
1772d59ba6ceSdrh     if( p->pLimit ){
177366a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Add, 0, 0);
1774d59ba6ceSdrh     }
17757b58daeaSdrh   }
1776d59ba6ceSdrh   if( p->pLimit ){
177766a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_IfMemPos, iLimit, 0);
177866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Pop, 1, 0);
17794c583128Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, -1, iLimit+1);
178066a5167bSdrh     addr2 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
178115007a99Sdrh     sqlite3VdbeJumpHere(v, addr1);
1782*b1fdb2adSdrh     sqlite3VdbeAddOp2(v, OP_Move, 0, iLimit+1);
1783d4e70ebdSdrh     VdbeComment((v, "LIMIT+OFFSET"));
178415007a99Sdrh     sqlite3VdbeJumpHere(v, addr2);
1785d59ba6ceSdrh   }
17867b58daeaSdrh }
17877b58daeaSdrh 
17887b58daeaSdrh /*
17890342b1f5Sdrh ** Allocate a virtual index to use for sorting.
1790d3d39e93Sdrh */
17914db38a70Sdrh static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
17920342b1f5Sdrh   if( pOrderBy ){
1793dc1bdc4fSdanielk1977     int addr;
17949d2985c7Sdrh     assert( pOrderBy->iECursor==0 );
17959d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
179666a5167bSdrh     addr = sqlite3VdbeAddOp2(pParse->pVdbe, OP_OpenEphemeral,
17979d2985c7Sdrh                             pOrderBy->iECursor, pOrderBy->nExpr+1);
1798b9bb7c18Sdrh     assert( p->addrOpenEphm[2] == -1 );
1799b9bb7c18Sdrh     p->addrOpenEphm[2] = addr;
1800736c22b8Sdrh   }
1801dc1bdc4fSdanielk1977 }
1802dc1bdc4fSdanielk1977 
1803b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1804fbc4ee7bSdrh /*
1805fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
1806fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
1807fbc4ee7bSdrh ** the column has no default collating sequence.
1808fbc4ee7bSdrh **
1809fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
1810fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
1811fbc4ee7bSdrh */
1812dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1813fbc4ee7bSdrh   CollSeq *pRet;
1814dc1bdc4fSdanielk1977   if( p->pPrior ){
1815dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1816fbc4ee7bSdrh   }else{
1817fbc4ee7bSdrh     pRet = 0;
1818dc1bdc4fSdanielk1977   }
1819fbc4ee7bSdrh   if( pRet==0 ){
1820dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1821dc1bdc4fSdanielk1977   }
1822dc1bdc4fSdanielk1977   return pRet;
1823d3d39e93Sdrh }
1824b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1825d3d39e93Sdrh 
1826b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1827d3d39e93Sdrh /*
182882c3d636Sdrh ** This routine is called to process a query that is really the union
182982c3d636Sdrh ** or intersection of two or more separate queries.
1830c926afbcSdrh **
1831e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1832e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1833e78e8284Sdrh ** in which case this routine will be called recursively.
1834e78e8284Sdrh **
1835e78e8284Sdrh ** The results of the total query are to be written into a destination
1836e78e8284Sdrh ** of type eDest with parameter iParm.
1837e78e8284Sdrh **
1838e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1839e78e8284Sdrh **
1840e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1841e78e8284Sdrh **
1842e78e8284Sdrh ** This statement is parsed up as follows:
1843e78e8284Sdrh **
1844e78e8284Sdrh **     SELECT c FROM t3
1845e78e8284Sdrh **      |
1846e78e8284Sdrh **      `----->  SELECT b FROM t2
1847e78e8284Sdrh **                |
18484b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1849e78e8284Sdrh **
1850e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1851e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1852e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1853e78e8284Sdrh **
1854e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1855e78e8284Sdrh ** individual selects always group from left to right.
185682c3d636Sdrh */
185784ac9d02Sdanielk1977 static int multiSelect(
1858fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
1859fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
18606c8c8ce0Sdanielk1977   SelectDest *pDest,    /* What to do with query results */
186184ac9d02Sdanielk1977   char *aff             /* If eDest is SRT_Union, the affinity string */
186284ac9d02Sdanielk1977 ){
186384ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
186410e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
186510e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
18668cdbf836Sdrh   int nCol;             /* Number of columns in the result set */
18670342b1f5Sdrh   ExprList *pOrderBy;   /* The ORDER BY clause on p */
18680342b1f5Sdrh   int aSetP2[2];        /* Set P2 value of these op to number of columns */
18690342b1f5Sdrh   int nSetP2 = 0;       /* Number of slots in aSetP2[] used */
187082c3d636Sdrh 
18716c8c8ce0Sdanielk1977   SelectDest dest;
18726c8c8ce0Sdanielk1977   dest.eDest = pDest->eDest;
18736c8c8ce0Sdanielk1977   dest.iParm = pDest->iParm;
18746c8c8ce0Sdanielk1977   dest.affinity = pDest->affinity;
18756c8c8ce0Sdanielk1977 
18767b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1877fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
187882c3d636Sdrh   */
187984ac9d02Sdanielk1977   if( p==0 || p->pPrior==0 ){
188084ac9d02Sdanielk1977     rc = 1;
188184ac9d02Sdanielk1977     goto multi_select_end;
188284ac9d02Sdanielk1977   }
1883d8bc7086Sdrh   pPrior = p->pPrior;
18840342b1f5Sdrh   assert( pPrior->pRightmost!=pPrior );
18850342b1f5Sdrh   assert( pPrior->pRightmost==p->pRightmost );
1886d8bc7086Sdrh   if( pPrior->pOrderBy ){
18874adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1888da93d238Sdrh       selectOpName(p->op));
188984ac9d02Sdanielk1977     rc = 1;
189084ac9d02Sdanielk1977     goto multi_select_end;
189182c3d636Sdrh   }
1892a2dc3b1aSdanielk1977   if( pPrior->pLimit ){
18934adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
18947b58daeaSdrh       selectOpName(p->op));
189584ac9d02Sdanielk1977     rc = 1;
189684ac9d02Sdanielk1977     goto multi_select_end;
18977b58daeaSdrh   }
189882c3d636Sdrh 
1899d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
1900d8bc7086Sdrh   */
19014adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
190284ac9d02Sdanielk1977   if( v==0 ){
190384ac9d02Sdanielk1977     rc = 1;
190484ac9d02Sdanielk1977     goto multi_select_end;
190584ac9d02Sdanielk1977   }
1906d8bc7086Sdrh 
19071cc3d75fSdrh   /* Create the destination temporary table if necessary
19081cc3d75fSdrh   */
19096c8c8ce0Sdanielk1977   if( dest.eDest==SRT_EphemTab ){
1910b4964b72Sdanielk1977     assert( p->pEList );
19110342b1f5Sdrh     assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
191266a5167bSdrh     aSetP2[nSetP2++] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, 0);
19136c8c8ce0Sdanielk1977     dest.eDest = SRT_Table;
19141cc3d75fSdrh   }
19151cc3d75fSdrh 
1916f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1917d8bc7086Sdrh   */
19180342b1f5Sdrh   pOrderBy = p->pOrderBy;
191982c3d636Sdrh   switch( p->op ){
1920f46f905aSdrh     case TK_ALL: {
19210342b1f5Sdrh       if( pOrderBy==0 ){
1922ec7429aeSdrh         int addr = 0;
1923a2dc3b1aSdanielk1977         assert( !pPrior->pLimit );
1924a2dc3b1aSdanielk1977         pPrior->pLimit = p->pLimit;
1925a2dc3b1aSdanielk1977         pPrior->pOffset = p->pOffset;
19266c8c8ce0Sdanielk1977         rc = sqlite3Select(pParse, pPrior, &dest, 0, 0, 0, aff);
1927ad68cb6bSdanielk1977         p->pLimit = 0;
1928ad68cb6bSdanielk1977         p->pOffset = 0;
192984ac9d02Sdanielk1977         if( rc ){
193084ac9d02Sdanielk1977           goto multi_select_end;
193184ac9d02Sdanielk1977         }
1932f46f905aSdrh         p->pPrior = 0;
19337b58daeaSdrh         p->iLimit = pPrior->iLimit;
19347b58daeaSdrh         p->iOffset = pPrior->iOffset;
1935ec7429aeSdrh         if( p->iLimit>=0 ){
193666a5167bSdrh           addr = sqlite3VdbeAddOp2(v, OP_IfMemZero, p->iLimit, 0);
1937d4e70ebdSdrh           VdbeComment((v, "Jump ahead if LIMIT reached"));
1938ec7429aeSdrh         }
19396c8c8ce0Sdanielk1977         rc = sqlite3Select(pParse, p, &dest, 0, 0, 0, aff);
1940f46f905aSdrh         p->pPrior = pPrior;
194184ac9d02Sdanielk1977         if( rc ){
194284ac9d02Sdanielk1977           goto multi_select_end;
194384ac9d02Sdanielk1977         }
1944ec7429aeSdrh         if( addr ){
1945ec7429aeSdrh           sqlite3VdbeJumpHere(v, addr);
1946ec7429aeSdrh         }
1947f46f905aSdrh         break;
1948f46f905aSdrh       }
1949f46f905aSdrh       /* For UNION ALL ... ORDER BY fall through to the next case */
1950f46f905aSdrh     }
195182c3d636Sdrh     case TK_EXCEPT:
195282c3d636Sdrh     case TK_UNION: {
1953d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1954742f947bSdanielk1977       int op = 0;      /* One of the SRT_ operations to apply to self */
1955d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
1956a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
1957dc1bdc4fSdanielk1977       int addr;
19586c8c8ce0Sdanielk1977       SelectDest uniondest;
195982c3d636Sdrh 
1960d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
19616c8c8ce0Sdanielk1977       if( dest.eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
1962d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1963c926afbcSdrh         ** right.
1964d8bc7086Sdrh         */
19656c8c8ce0Sdanielk1977         unionTab = dest.iParm;
196682c3d636Sdrh       }else{
1967d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1968d8bc7086Sdrh         ** intermediate results.
1969d8bc7086Sdrh         */
197082c3d636Sdrh         unionTab = pParse->nTab++;
19719a99334dSdrh         if( processCompoundOrderBy(pParse, p, unionTab) ){
197284ac9d02Sdanielk1977           rc = 1;
197384ac9d02Sdanielk1977           goto multi_select_end;
1974d8bc7086Sdrh         }
197566a5167bSdrh         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
19760342b1f5Sdrh         if( priorOp==SRT_Table ){
19770342b1f5Sdrh           assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
19780342b1f5Sdrh           aSetP2[nSetP2++] = addr;
19790342b1f5Sdrh         }else{
1980b9bb7c18Sdrh           assert( p->addrOpenEphm[0] == -1 );
1981b9bb7c18Sdrh           p->addrOpenEphm[0] = addr;
1982b9bb7c18Sdrh           p->pRightmost->usesEphm = 1;
1983dc1bdc4fSdanielk1977         }
19840342b1f5Sdrh         createSortingIndex(pParse, p, pOrderBy);
198584ac9d02Sdanielk1977         assert( p->pEList );
1986d8bc7086Sdrh       }
1987d8bc7086Sdrh 
1988d8bc7086Sdrh       /* Code the SELECT statements to our left
1989d8bc7086Sdrh       */
1990b3bce662Sdanielk1977       assert( !pPrior->pOrderBy );
19916c8c8ce0Sdanielk1977       uniondest.eDest = priorOp;
19926c8c8ce0Sdanielk1977       uniondest.iParm = unionTab;
19936c8c8ce0Sdanielk1977       rc = sqlite3Select(pParse, pPrior, &uniondest, 0, 0, 0, aff);
199484ac9d02Sdanielk1977       if( rc ){
199584ac9d02Sdanielk1977         goto multi_select_end;
199684ac9d02Sdanielk1977       }
1997d8bc7086Sdrh 
1998d8bc7086Sdrh       /* Code the current SELECT statement
1999d8bc7086Sdrh       */
2000d8bc7086Sdrh       switch( p->op ){
2001d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
2002d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
2003d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
2004d8bc7086Sdrh       }
200582c3d636Sdrh       p->pPrior = 0;
2006c926afbcSdrh       p->pOrderBy = 0;
20074b14b4d7Sdrh       p->disallowOrderBy = pOrderBy!=0;
2008a2dc3b1aSdanielk1977       pLimit = p->pLimit;
2009a2dc3b1aSdanielk1977       p->pLimit = 0;
2010a2dc3b1aSdanielk1977       pOffset = p->pOffset;
2011a2dc3b1aSdanielk1977       p->pOffset = 0;
20126c8c8ce0Sdanielk1977       uniondest.eDest = op;
20136c8c8ce0Sdanielk1977       rc = sqlite3Select(pParse, p, &uniondest, 0, 0, 0, aff);
20145bd1bf2eSdrh       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
20155bd1bf2eSdrh       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
20165bd1bf2eSdrh       sqlite3ExprListDelete(p->pOrderBy);
201782c3d636Sdrh       p->pPrior = pPrior;
2018c926afbcSdrh       p->pOrderBy = pOrderBy;
2019a2dc3b1aSdanielk1977       sqlite3ExprDelete(p->pLimit);
2020a2dc3b1aSdanielk1977       p->pLimit = pLimit;
2021a2dc3b1aSdanielk1977       p->pOffset = pOffset;
2022be5fd490Sdrh       p->iLimit = -1;
2023be5fd490Sdrh       p->iOffset = -1;
202484ac9d02Sdanielk1977       if( rc ){
202584ac9d02Sdanielk1977         goto multi_select_end;
202684ac9d02Sdanielk1977       }
202784ac9d02Sdanielk1977 
2028d8bc7086Sdrh 
2029d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
2030d8bc7086Sdrh       ** it is that we currently need.
2031d8bc7086Sdrh       */
20326c8c8ce0Sdanielk1977       if( dest.eDest!=priorOp || unionTab!=dest.iParm ){
20336b56344dSdrh         int iCont, iBreak, iStart;
203482c3d636Sdrh         assert( p->pEList );
20356c8c8ce0Sdanielk1977         if( dest.eDest==SRT_Callback ){
203692378253Sdrh           Select *pFirst = p;
203792378253Sdrh           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
203892378253Sdrh           generateColumnNames(pParse, 0, pFirst->pEList);
203941202ccaSdrh         }
20404adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
20414adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
2042ec7429aeSdrh         computeLimitRegisters(pParse, p, iBreak);
204366a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
20444adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
204538640e15Sdrh         rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
20466c8c8ce0Sdanielk1977                              pOrderBy, -1, &dest, iCont, iBreak, 0);
204784ac9d02Sdanielk1977         if( rc ){
204884ac9d02Sdanielk1977           rc = 1;
204984ac9d02Sdanielk1977           goto multi_select_end;
205084ac9d02Sdanielk1977         }
20514adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
205266a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
20534adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
205466a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
205582c3d636Sdrh       }
205682c3d636Sdrh       break;
205782c3d636Sdrh     }
205882c3d636Sdrh     case TK_INTERSECT: {
205982c3d636Sdrh       int tab1, tab2;
20606b56344dSdrh       int iCont, iBreak, iStart;
2061a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset;
2062dc1bdc4fSdanielk1977       int addr;
20636c8c8ce0Sdanielk1977       SelectDest intersectdest = {SRT_Union, 0, 0};
206482c3d636Sdrh 
2065d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
20666206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
2067d8bc7086Sdrh       ** by allocating the tables we will need.
2068d8bc7086Sdrh       */
206982c3d636Sdrh       tab1 = pParse->nTab++;
207082c3d636Sdrh       tab2 = pParse->nTab++;
20719a99334dSdrh       if( processCompoundOrderBy(pParse, p, tab1) ){
207284ac9d02Sdanielk1977         rc = 1;
207384ac9d02Sdanielk1977         goto multi_select_end;
2074d8bc7086Sdrh       }
20750342b1f5Sdrh       createSortingIndex(pParse, p, pOrderBy);
2076dc1bdc4fSdanielk1977 
207766a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
2078b9bb7c18Sdrh       assert( p->addrOpenEphm[0] == -1 );
2079b9bb7c18Sdrh       p->addrOpenEphm[0] = addr;
2080b9bb7c18Sdrh       p->pRightmost->usesEphm = 1;
208184ac9d02Sdanielk1977       assert( p->pEList );
2082d8bc7086Sdrh 
2083d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
2084d8bc7086Sdrh       */
20856c8c8ce0Sdanielk1977       intersectdest.iParm = tab1;
20866c8c8ce0Sdanielk1977       rc = sqlite3Select(pParse, pPrior, &intersectdest, 0, 0, 0, aff);
208784ac9d02Sdanielk1977       if( rc ){
208884ac9d02Sdanielk1977         goto multi_select_end;
208984ac9d02Sdanielk1977       }
2090d8bc7086Sdrh 
2091d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
2092d8bc7086Sdrh       */
209366a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
2094b9bb7c18Sdrh       assert( p->addrOpenEphm[1] == -1 );
2095b9bb7c18Sdrh       p->addrOpenEphm[1] = addr;
209682c3d636Sdrh       p->pPrior = 0;
2097a2dc3b1aSdanielk1977       pLimit = p->pLimit;
2098a2dc3b1aSdanielk1977       p->pLimit = 0;
2099a2dc3b1aSdanielk1977       pOffset = p->pOffset;
2100a2dc3b1aSdanielk1977       p->pOffset = 0;
21016c8c8ce0Sdanielk1977       intersectdest.iParm = tab2;
21026c8c8ce0Sdanielk1977       rc = sqlite3Select(pParse, p, &intersectdest, 0, 0, 0, aff);
210382c3d636Sdrh       p->pPrior = pPrior;
2104a2dc3b1aSdanielk1977       sqlite3ExprDelete(p->pLimit);
2105a2dc3b1aSdanielk1977       p->pLimit = pLimit;
2106a2dc3b1aSdanielk1977       p->pOffset = pOffset;
210784ac9d02Sdanielk1977       if( rc ){
210884ac9d02Sdanielk1977         goto multi_select_end;
210984ac9d02Sdanielk1977       }
2110d8bc7086Sdrh 
2111d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
2112d8bc7086Sdrh       ** tables.
2113d8bc7086Sdrh       */
211482c3d636Sdrh       assert( p->pEList );
21156c8c8ce0Sdanielk1977       if( dest.eDest==SRT_Callback ){
211692378253Sdrh         Select *pFirst = p;
211792378253Sdrh         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
211892378253Sdrh         generateColumnNames(pParse, 0, pFirst->pEList);
211941202ccaSdrh       }
21204adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
21214adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
2122ec7429aeSdrh       computeLimitRegisters(pParse, p, iBreak);
212366a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
212466a5167bSdrh       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, 0);
212566a5167bSdrh       sqlite3VdbeAddOp2(v, OP_NotFound, tab2, iCont);
212638640e15Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
21276c8c8ce0Sdanielk1977                              pOrderBy, -1, &dest, iCont, iBreak, 0);
212884ac9d02Sdanielk1977       if( rc ){
212984ac9d02Sdanielk1977         rc = 1;
213084ac9d02Sdanielk1977         goto multi_select_end;
213184ac9d02Sdanielk1977       }
21324adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
213366a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
21344adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
213566a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
213666a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
213782c3d636Sdrh       break;
213882c3d636Sdrh     }
213982c3d636Sdrh   }
21408cdbf836Sdrh 
21418cdbf836Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
21428cdbf836Sdrh   ** in their result sets.
21438cdbf836Sdrh   */
214482c3d636Sdrh   assert( p->pEList && pPrior->pEList );
214582c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
21464adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
2147da93d238Sdrh       " do not have the same number of result columns", selectOpName(p->op));
214884ac9d02Sdanielk1977     rc = 1;
214984ac9d02Sdanielk1977     goto multi_select_end;
21502282792aSdrh   }
215184ac9d02Sdanielk1977 
21528cdbf836Sdrh   /* Set the number of columns in temporary tables
21538cdbf836Sdrh   */
21548cdbf836Sdrh   nCol = p->pEList->nExpr;
21550342b1f5Sdrh   while( nSetP2 ){
21560342b1f5Sdrh     sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
21578cdbf836Sdrh   }
21588cdbf836Sdrh 
2159fbc4ee7bSdrh   /* Compute collating sequences used by either the ORDER BY clause or
2160fbc4ee7bSdrh   ** by any temporary tables needed to implement the compound select.
2161fbc4ee7bSdrh   ** Attach the KeyInfo structure to all temporary tables.  Invoke the
2162fbc4ee7bSdrh   ** ORDER BY processing if there is an ORDER BY clause.
21638cdbf836Sdrh   **
21648cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
21658cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
21668cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
21678cdbf836Sdrh   ** no temp tables are required.
2168fbc4ee7bSdrh   */
2169b9bb7c18Sdrh   if( pOrderBy || p->usesEphm ){
2170fbc4ee7bSdrh     int i;                        /* Loop counter */
2171fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
21720342b1f5Sdrh     Select *pLoop;                /* For looping through SELECT statements */
21731e31e0b2Sdrh     int nKeyCol;                  /* Number of entries in pKeyInfo->aCol[] */
2174f68d7d17Sdrh     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
2175f68d7d17Sdrh     CollSeq **aCopy;              /* A copy of pKeyInfo->aColl[] */
2176fbc4ee7bSdrh 
21770342b1f5Sdrh     assert( p->pRightmost==p );
21781e31e0b2Sdrh     nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0);
217917435752Sdrh     pKeyInfo = sqlite3DbMallocZero(pParse->db,
218017435752Sdrh                        sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1));
2181dc1bdc4fSdanielk1977     if( !pKeyInfo ){
2182dc1bdc4fSdanielk1977       rc = SQLITE_NOMEM;
2183dc1bdc4fSdanielk1977       goto multi_select_end;
2184dc1bdc4fSdanielk1977     }
2185dc1bdc4fSdanielk1977 
218614db2665Sdanielk1977     pKeyInfo->enc = ENC(pParse->db);
2187dc1bdc4fSdanielk1977     pKeyInfo->nField = nCol;
2188dc1bdc4fSdanielk1977 
21890342b1f5Sdrh     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
21900342b1f5Sdrh       *apColl = multiSelectCollSeq(pParse, p, i);
21910342b1f5Sdrh       if( 0==*apColl ){
21920342b1f5Sdrh         *apColl = pParse->db->pDfltColl;
2193dc1bdc4fSdanielk1977       }
2194dc1bdc4fSdanielk1977     }
2195dc1bdc4fSdanielk1977 
21960342b1f5Sdrh     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
21970342b1f5Sdrh       for(i=0; i<2; i++){
2198b9bb7c18Sdrh         int addr = pLoop->addrOpenEphm[i];
21990342b1f5Sdrh         if( addr<0 ){
22000342b1f5Sdrh           /* If [0] is unused then [1] is also unused.  So we can
22010342b1f5Sdrh           ** always safely abort as soon as the first unused slot is found */
2202b9bb7c18Sdrh           assert( pLoop->addrOpenEphm[1]<0 );
22030342b1f5Sdrh           break;
22040342b1f5Sdrh         }
22050342b1f5Sdrh         sqlite3VdbeChangeP2(v, addr, nCol);
220666a5167bSdrh         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
22070ee5a1e7Sdrh         pLoop->addrOpenEphm[i] = -1;
22080342b1f5Sdrh       }
2209dc1bdc4fSdanielk1977     }
2210dc1bdc4fSdanielk1977 
22110342b1f5Sdrh     if( pOrderBy ){
22120342b1f5Sdrh       struct ExprList_item *pOTerm = pOrderBy->a;
22134efc083fSdrh       int nOrderByExpr = pOrderBy->nExpr;
22140342b1f5Sdrh       int addr;
22154db38a70Sdrh       u8 *pSortOrder;
22160342b1f5Sdrh 
2217f68d7d17Sdrh       /* Reuse the same pKeyInfo for the ORDER BY as was used above for
2218f68d7d17Sdrh       ** the compound select statements.  Except we have to change out the
2219f68d7d17Sdrh       ** pKeyInfo->aColl[] values.  Some of the aColl[] values will be
2220f68d7d17Sdrh       ** reused when constructing the pKeyInfo for the ORDER BY, so make
2221f68d7d17Sdrh       ** a copy.  Sufficient space to hold both the nCol entries for
2222f68d7d17Sdrh       ** the compound select and the nOrderbyExpr entries for the ORDER BY
2223f68d7d17Sdrh       ** was allocated above.  But we need to move the compound select
2224f68d7d17Sdrh       ** entries out of the way before constructing the ORDER BY entries.
2225f68d7d17Sdrh       ** Move the compound select entries into aCopy[] where they can be
2226f68d7d17Sdrh       ** accessed and reused when constructing the ORDER BY entries.
2227f68d7d17Sdrh       ** Because nCol might be greater than or less than nOrderByExpr
2228f68d7d17Sdrh       ** we have to use memmove() when doing the copy.
2229f68d7d17Sdrh       */
22301e31e0b2Sdrh       aCopy = &pKeyInfo->aColl[nOrderByExpr];
22314efc083fSdrh       pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
2232f68d7d17Sdrh       memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
2233f68d7d17Sdrh 
22340342b1f5Sdrh       apColl = pKeyInfo->aColl;
22354efc083fSdrh       for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
22360342b1f5Sdrh         Expr *pExpr = pOTerm->pExpr;
22378b4c40d8Sdrh         if( (pExpr->flags & EP_ExpCollate) ){
22388b4c40d8Sdrh           assert( pExpr->pColl!=0 );
22398b4c40d8Sdrh           *apColl = pExpr->pColl;
224084ac9d02Sdanielk1977         }else{
22410342b1f5Sdrh           *apColl = aCopy[pExpr->iColumn];
224284ac9d02Sdanielk1977         }
22434db38a70Sdrh         *pSortOrder = pOTerm->sortOrder;
224484ac9d02Sdanielk1977       }
22450342b1f5Sdrh       assert( p->pRightmost==p );
2246b9bb7c18Sdrh       assert( p->addrOpenEphm[2]>=0 );
2247b9bb7c18Sdrh       addr = p->addrOpenEphm[2];
2248a670b226Sdanielk1977       sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2);
22494efc083fSdrh       pKeyInfo->nField = nOrderByExpr;
225066a5167bSdrh       sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
22514db38a70Sdrh       pKeyInfo = 0;
22526c8c8ce0Sdanielk1977       generateSortTail(pParse, p, v, p->pEList->nExpr, &dest);
2253dc1bdc4fSdanielk1977     }
2254dc1bdc4fSdanielk1977 
225517435752Sdrh     sqlite3_free(pKeyInfo);
2256dc1bdc4fSdanielk1977   }
2257dc1bdc4fSdanielk1977 
2258dc1bdc4fSdanielk1977 multi_select_end:
225984ac9d02Sdanielk1977   return rc;
22602282792aSdrh }
2261b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
22622282792aSdrh 
2263b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
226417435752Sdrh /* Forward Declarations */
226517435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*);
226617435752Sdrh static void substSelect(sqlite3*, Select *, int, ExprList *);
226717435752Sdrh 
22682282792aSdrh /*
2269832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
22706a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
227184e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
22726a3ea0e6Sdrh ** unchanged.)
2273832508b7Sdrh **
2274832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
2275832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
2276832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
2277832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
2278832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
2279832508b7Sdrh ** of the subquery rather the result set of the subquery.
2280832508b7Sdrh */
228117435752Sdrh static void substExpr(
228217435752Sdrh   sqlite3 *db,        /* Report malloc errors to this connection */
228317435752Sdrh   Expr *pExpr,        /* Expr in which substitution occurs */
228417435752Sdrh   int iTable,         /* Table to be substituted */
228517435752Sdrh   ExprList *pEList    /* Substitute expressions */
228617435752Sdrh ){
2287832508b7Sdrh   if( pExpr==0 ) return;
228850350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
228950350a15Sdrh     if( pExpr->iColumn<0 ){
229050350a15Sdrh       pExpr->op = TK_NULL;
229150350a15Sdrh     }else{
2292832508b7Sdrh       Expr *pNew;
229384e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
2294832508b7Sdrh       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
2295832508b7Sdrh       pNew = pEList->a[pExpr->iColumn].pExpr;
2296832508b7Sdrh       assert( pNew!=0 );
2297832508b7Sdrh       pExpr->op = pNew->op;
2298d94a6698Sdrh       assert( pExpr->pLeft==0 );
229917435752Sdrh       pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
2300d94a6698Sdrh       assert( pExpr->pRight==0 );
230117435752Sdrh       pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
2302d94a6698Sdrh       assert( pExpr->pList==0 );
230317435752Sdrh       pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
2304832508b7Sdrh       pExpr->iTable = pNew->iTable;
2305fbbe005aSdanielk1977       pExpr->pTab = pNew->pTab;
2306832508b7Sdrh       pExpr->iColumn = pNew->iColumn;
2307832508b7Sdrh       pExpr->iAgg = pNew->iAgg;
230817435752Sdrh       sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
230917435752Sdrh       sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
231017435752Sdrh       pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
2311a1cb183dSdanielk1977       pExpr->flags = pNew->flags;
231250350a15Sdrh     }
2313832508b7Sdrh   }else{
231417435752Sdrh     substExpr(db, pExpr->pLeft, iTable, pEList);
231517435752Sdrh     substExpr(db, pExpr->pRight, iTable, pEList);
231617435752Sdrh     substSelect(db, pExpr->pSelect, iTable, pEList);
231717435752Sdrh     substExprList(db, pExpr->pList, iTable, pEList);
2318832508b7Sdrh   }
2319832508b7Sdrh }
232017435752Sdrh static void substExprList(
232117435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
232217435752Sdrh   ExprList *pList,     /* List to scan and in which to make substitutes */
232317435752Sdrh   int iTable,          /* Table to be substituted */
232417435752Sdrh   ExprList *pEList     /* Substitute values */
232517435752Sdrh ){
2326832508b7Sdrh   int i;
2327832508b7Sdrh   if( pList==0 ) return;
2328832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
232917435752Sdrh     substExpr(db, pList->a[i].pExpr, iTable, pEList);
2330832508b7Sdrh   }
2331832508b7Sdrh }
233217435752Sdrh static void substSelect(
233317435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
233417435752Sdrh   Select *p,           /* SELECT statement in which to make substitutions */
233517435752Sdrh   int iTable,          /* Table to be replaced */
233617435752Sdrh   ExprList *pEList     /* Substitute values */
233717435752Sdrh ){
2338b3bce662Sdanielk1977   if( !p ) return;
233917435752Sdrh   substExprList(db, p->pEList, iTable, pEList);
234017435752Sdrh   substExprList(db, p->pGroupBy, iTable, pEList);
234117435752Sdrh   substExprList(db, p->pOrderBy, iTable, pEList);
234217435752Sdrh   substExpr(db, p->pHaving, iTable, pEList);
234317435752Sdrh   substExpr(db, p->pWhere, iTable, pEList);
234417435752Sdrh   substSelect(db, p->pPrior, iTable, pEList);
2345b3bce662Sdanielk1977 }
2346b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_VIEW) */
2347832508b7Sdrh 
2348b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
2349832508b7Sdrh /*
23501350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
23511350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
23521350b030Sdrh ** occurs.
23531350b030Sdrh **
23541350b030Sdrh ** To understand the concept of flattening, consider the following
23551350b030Sdrh ** query:
23561350b030Sdrh **
23571350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
23581350b030Sdrh **
23591350b030Sdrh ** The default way of implementing this query is to execute the
23601350b030Sdrh ** subquery first and store the results in a temporary table, then
23611350b030Sdrh ** run the outer query on that temporary table.  This requires two
23621350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
23631350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
2364832508b7Sdrh ** optimized.
23651350b030Sdrh **
2366832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
23671350b030Sdrh ** a single flat select, like this:
23681350b030Sdrh **
23691350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
23701350b030Sdrh **
23711350b030Sdrh ** The code generated for this simpification gives the same result
2372832508b7Sdrh ** but only has to scan the data once.  And because indices might
2373832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
2374832508b7Sdrh ** avoided.
23751350b030Sdrh **
2376832508b7Sdrh ** Flattening is only attempted if all of the following are true:
23771350b030Sdrh **
2378832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
23791350b030Sdrh **
2380832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
2381832508b7Sdrh **
23828af4d3acSdrh **   (3)  The subquery is not the right operand of a left outer join, or
23838af4d3acSdrh **        the subquery is not itself a join.  (Ticket #306)
2384832508b7Sdrh **
2385832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
2386832508b7Sdrh **
2387832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
2388832508b7Sdrh **        aggregates.
2389832508b7Sdrh **
2390832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
2391832508b7Sdrh **        DISTINCT.
2392832508b7Sdrh **
239308192d5fSdrh **   (7)  The subquery has a FROM clause.
239408192d5fSdrh **
2395df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
2396df199a25Sdrh **
2397df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
2398df199a25Sdrh **        aggregates.
2399df199a25Sdrh **
2400df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
2401df199a25Sdrh **        use LIMIT.
2402df199a25Sdrh **
2403174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
2404174b6195Sdrh **
24053fc673e6Sdrh **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
24063fc673e6Sdrh **        subquery has no WHERE clause.  (added by ticket #350)
24073fc673e6Sdrh **
2408ac83963aSdrh **  (13)  The subquery and outer query do not both use LIMIT
2409ac83963aSdrh **
2410ac83963aSdrh **  (14)  The subquery does not use OFFSET
2411ac83963aSdrh **
2412ad91c6cdSdrh **  (15)  The outer query is not part of a compound select or the
2413ad91c6cdSdrh **        subquery does not have both an ORDER BY and a LIMIT clause.
2414ad91c6cdSdrh **        (See ticket #2339)
2415ad91c6cdSdrh **
2416832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
2417832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
2418832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
2419832508b7Sdrh **
2420665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
2421832508b7Sdrh ** If flattening is attempted this routine returns 1.
2422832508b7Sdrh **
2423832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
2424832508b7Sdrh ** the subquery before this routine runs.
24251350b030Sdrh */
24268c74a8caSdrh static int flattenSubquery(
242717435752Sdrh   sqlite3 *db,         /* Database connection */
24288c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
24298c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
24308c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
24318c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
24328c74a8caSdrh ){
24330bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
2434ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
2435ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
24360bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
24376a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
243891bb0eedSdrh   int i;              /* Loop counter */
243991bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
244091bb0eedSdrh   struct SrcList_item *pSubitem;   /* The subquery */
24411350b030Sdrh 
2442832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
2443832508b7Sdrh   */
2444832508b7Sdrh   if( p==0 ) return 0;
2445832508b7Sdrh   pSrc = p->pSrc;
2446ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
244791bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
244891bb0eedSdrh   pSub = pSubitem->pSelect;
2449832508b7Sdrh   assert( pSub!=0 );
2450ac83963aSdrh   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
2451ac83963aSdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
2452832508b7Sdrh   pSubSrc = pSub->pSrc;
2453832508b7Sdrh   assert( pSubSrc );
2454ac83963aSdrh   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
2455ac83963aSdrh   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
2456ac83963aSdrh   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
2457ac83963aSdrh   ** became arbitrary expressions, we were forced to add restrictions (13)
2458ac83963aSdrh   ** and (14). */
2459ac83963aSdrh   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
2460ac83963aSdrh   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
2461ad91c6cdSdrh   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
2462ad91c6cdSdrh     return 0;                                            /* Restriction (15) */
2463ad91c6cdSdrh   }
2464ac83963aSdrh   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
2465ac83963aSdrh   if( (pSub->isDistinct || pSub->pLimit)
2466ac83963aSdrh          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
2467df199a25Sdrh      return 0;
2468df199a25Sdrh   }
2469ac83963aSdrh   if( p->isDistinct && subqueryIsAgg ) return 0;         /* Restriction (6)  */
2470ac83963aSdrh   if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){
2471ac83963aSdrh      return 0;                                           /* Restriction (11) */
2472ac83963aSdrh   }
2473832508b7Sdrh 
24748af4d3acSdrh   /* Restriction 3:  If the subquery is a join, make sure the subquery is
24758af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
24768af4d3acSdrh   ** is not allowed:
24778af4d3acSdrh   **
24788af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
24798af4d3acSdrh   **
24808af4d3acSdrh   ** If we flatten the above, we would get
24818af4d3acSdrh   **
24828af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
24838af4d3acSdrh   **
24848af4d3acSdrh   ** which is not at all the same thing.
24858af4d3acSdrh   */
248661dfc31dSdrh   if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){
24878af4d3acSdrh     return 0;
24888af4d3acSdrh   }
24898af4d3acSdrh 
24903fc673e6Sdrh   /* Restriction 12:  If the subquery is the right operand of a left outer
24913fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
24923fc673e6Sdrh   ** An examples of why this is not allowed:
24933fc673e6Sdrh   **
24943fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
24953fc673e6Sdrh   **
24963fc673e6Sdrh   ** If we flatten the above, we would get
24973fc673e6Sdrh   **
24983fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
24993fc673e6Sdrh   **
25003fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
25013fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
25023fc673e6Sdrh   */
250361dfc31dSdrh   if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){
25043fc673e6Sdrh     return 0;
25053fc673e6Sdrh   }
25063fc673e6Sdrh 
25070bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
250863eb5f29Sdrh   ** iFrom-th entry of the FROM clause in the outer query.
2509832508b7Sdrh   */
2510c31c2eb8Sdrh 
2511c31c2eb8Sdrh   /* Move all of the FROM elements of the subquery into the
2512c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
2513c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
2514c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
2515c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
2516c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
2517c31c2eb8Sdrh   ** elements we are now copying in.
2518c31c2eb8Sdrh   */
251991bb0eedSdrh   iParent = pSubitem->iCursor;
2520c31c2eb8Sdrh   {
2521c31c2eb8Sdrh     int nSubSrc = pSubSrc->nSrc;
252291bb0eedSdrh     int jointype = pSubitem->jointype;
2523c31c2eb8Sdrh 
2524a04a34ffSdanielk1977     sqlite3DeleteTable(pSubitem->pTab);
252517435752Sdrh     sqlite3_free(pSubitem->zDatabase);
252617435752Sdrh     sqlite3_free(pSubitem->zName);
252717435752Sdrh     sqlite3_free(pSubitem->zAlias);
2528cfa063b3Sdrh     pSubitem->pTab = 0;
2529cfa063b3Sdrh     pSubitem->zDatabase = 0;
2530cfa063b3Sdrh     pSubitem->zName = 0;
2531cfa063b3Sdrh     pSubitem->zAlias = 0;
2532c31c2eb8Sdrh     if( nSubSrc>1 ){
2533c31c2eb8Sdrh       int extra = nSubSrc - 1;
2534c31c2eb8Sdrh       for(i=1; i<nSubSrc; i++){
253517435752Sdrh         pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0);
2536cfa063b3Sdrh         if( pSrc==0 ){
2537cfa063b3Sdrh           p->pSrc = 0;
2538cfa063b3Sdrh           return 1;
2539cfa063b3Sdrh         }
2540c31c2eb8Sdrh       }
2541c31c2eb8Sdrh       p->pSrc = pSrc;
2542c31c2eb8Sdrh       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2543c31c2eb8Sdrh         pSrc->a[i] = pSrc->a[i-extra];
2544c31c2eb8Sdrh       }
2545c31c2eb8Sdrh     }
2546c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
2547c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
2548c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2549c31c2eb8Sdrh     }
255061dfc31dSdrh     pSrc->a[iFrom].jointype = jointype;
2551c31c2eb8Sdrh   }
2552c31c2eb8Sdrh 
2553c31c2eb8Sdrh   /* Now begin substituting subquery result set expressions for
2554c31c2eb8Sdrh   ** references to the iParent in the outer query.
2555c31c2eb8Sdrh   **
2556c31c2eb8Sdrh   ** Example:
2557c31c2eb8Sdrh   **
2558c31c2eb8Sdrh   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2559c31c2eb8Sdrh   **   \                     \_____________ subquery __________/          /
2560c31c2eb8Sdrh   **    \_____________________ outer query ______________________________/
2561c31c2eb8Sdrh   **
2562c31c2eb8Sdrh   ** We look at every expression in the outer query and every place we see
2563c31c2eb8Sdrh   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2564c31c2eb8Sdrh   */
2565832508b7Sdrh   pList = p->pEList;
2566832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
25676977fea8Sdrh     Expr *pExpr;
25686977fea8Sdrh     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
256917435752Sdrh       pList->a[i].zName =
257017435752Sdrh              sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
2571832508b7Sdrh     }
2572832508b7Sdrh   }
25731e536953Sdanielk1977   substExprList(db, p->pEList, iParent, pSub->pEList);
25741b2e0329Sdrh   if( isAgg ){
25751e536953Sdanielk1977     substExprList(db, p->pGroupBy, iParent, pSub->pEList);
25761e536953Sdanielk1977     substExpr(db, p->pHaving, iParent, pSub->pEList);
25771b2e0329Sdrh   }
2578174b6195Sdrh   if( pSub->pOrderBy ){
2579174b6195Sdrh     assert( p->pOrderBy==0 );
2580174b6195Sdrh     p->pOrderBy = pSub->pOrderBy;
2581174b6195Sdrh     pSub->pOrderBy = 0;
2582174b6195Sdrh   }else if( p->pOrderBy ){
25831e536953Sdanielk1977     substExprList(db, p->pOrderBy, iParent, pSub->pEList);
2584174b6195Sdrh   }
2585832508b7Sdrh   if( pSub->pWhere ){
258617435752Sdrh     pWhere = sqlite3ExprDup(db, pSub->pWhere);
2587832508b7Sdrh   }else{
2588832508b7Sdrh     pWhere = 0;
2589832508b7Sdrh   }
2590832508b7Sdrh   if( subqueryIsAgg ){
2591832508b7Sdrh     assert( p->pHaving==0 );
25921b2e0329Sdrh     p->pHaving = p->pWhere;
25931b2e0329Sdrh     p->pWhere = pWhere;
25941e536953Sdanielk1977     substExpr(db, p->pHaving, iParent, pSub->pEList);
259517435752Sdrh     p->pHaving = sqlite3ExprAnd(db, p->pHaving,
259617435752Sdrh                                 sqlite3ExprDup(db, pSub->pHaving));
25971b2e0329Sdrh     assert( p->pGroupBy==0 );
259817435752Sdrh     p->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
2599832508b7Sdrh   }else{
26001e536953Sdanielk1977     substExpr(db, p->pWhere, iParent, pSub->pEList);
260117435752Sdrh     p->pWhere = sqlite3ExprAnd(db, p->pWhere, pWhere);
2602832508b7Sdrh   }
2603c31c2eb8Sdrh 
2604c31c2eb8Sdrh   /* The flattened query is distinct if either the inner or the
2605c31c2eb8Sdrh   ** outer query is distinct.
2606c31c2eb8Sdrh   */
2607832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
26088c74a8caSdrh 
2609a58fdfb1Sdanielk1977   /*
2610a58fdfb1Sdanielk1977   ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2611ac83963aSdrh   **
2612ac83963aSdrh   ** One is tempted to try to add a and b to combine the limits.  But this
2613ac83963aSdrh   ** does not work if either limit is negative.
2614a58fdfb1Sdanielk1977   */
2615a2dc3b1aSdanielk1977   if( pSub->pLimit ){
2616a2dc3b1aSdanielk1977     p->pLimit = pSub->pLimit;
2617a2dc3b1aSdanielk1977     pSub->pLimit = 0;
2618df199a25Sdrh   }
26198c74a8caSdrh 
2620c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
2621c31c2eb8Sdrh   ** success.
2622c31c2eb8Sdrh   */
26234adee20fSdanielk1977   sqlite3SelectDelete(pSub);
2624832508b7Sdrh   return 1;
26251350b030Sdrh }
2626b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */
26271350b030Sdrh 
26281350b030Sdrh /*
26299562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it
26309562b551Sdrh ** is a simple min() or max() query.  If it is and this query can be
26319562b551Sdrh ** satisfied using a single seek to the beginning or end of an index,
2632e78e8284Sdrh ** then generate the code for this SELECT and return 1.  If this is not a
26339562b551Sdrh ** simple min() or max() query, then return 0;
26349562b551Sdrh **
26359562b551Sdrh ** A simply min() or max() query looks like this:
26369562b551Sdrh **
26379562b551Sdrh **    SELECT min(a) FROM table;
26389562b551Sdrh **    SELECT max(a) FROM table;
26399562b551Sdrh **
26409562b551Sdrh ** The query may have only a single table in its FROM argument.  There
26419562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
26429562b551Sdrh ** be the min() or max() of a single column of the table.  The column
26439562b551Sdrh ** in the min() or max() function must be indexed.
26449562b551Sdrh **
26454adee20fSdanielk1977 ** The parameters to this routine are the same as for sqlite3Select().
26469562b551Sdrh ** See the header comment on that routine for additional information.
26479562b551Sdrh */
26486c8c8ce0Sdanielk1977 static int simpleMinMaxQuery(Parse *pParse, Select *p, SelectDest *pDest){
26499562b551Sdrh   Expr *pExpr;
26509562b551Sdrh   int iCol;
26519562b551Sdrh   Table *pTab;
26529562b551Sdrh   Index *pIdx;
26539562b551Sdrh   int base;
26549562b551Sdrh   Vdbe *v;
26559562b551Sdrh   int seekOp;
26566e17529eSdrh   ExprList *pEList, *pList, eList;
26579562b551Sdrh   struct ExprList_item eListItem;
26586e17529eSdrh   SrcList *pSrc;
2659ec7429aeSdrh   int brk;
2660da184236Sdanielk1977   int iDb;
26616e17529eSdrh 
26629562b551Sdrh   /* Check to see if this query is a simple min() or max() query.  Return
26639562b551Sdrh   ** zero if it is  not.
26649562b551Sdrh   */
26659562b551Sdrh   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
26666e17529eSdrh   pSrc = p->pSrc;
26676e17529eSdrh   if( pSrc->nSrc!=1 ) return 0;
26686e17529eSdrh   pEList = p->pEList;
26696e17529eSdrh   if( pEList->nExpr!=1 ) return 0;
26706e17529eSdrh   pExpr = pEList->a[0].pExpr;
26719562b551Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
26726e17529eSdrh   pList = pExpr->pList;
26736e17529eSdrh   if( pList==0 || pList->nExpr!=1 ) return 0;
26746977fea8Sdrh   if( pExpr->token.n!=3 ) return 0;
26752646da7eSdrh   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
26760bce8354Sdrh     seekOp = OP_Rewind;
26772646da7eSdrh   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
26780bce8354Sdrh     seekOp = OP_Last;
26790bce8354Sdrh   }else{
26800bce8354Sdrh     return 0;
26810bce8354Sdrh   }
26826e17529eSdrh   pExpr = pList->a[0].pExpr;
26839562b551Sdrh   if( pExpr->op!=TK_COLUMN ) return 0;
26849562b551Sdrh   iCol = pExpr->iColumn;
26856e17529eSdrh   pTab = pSrc->a[0].pTab;
26869562b551Sdrh 
2687a41c7497Sdanielk1977   /* This optimization cannot be used with virtual tables. */
2688a41c7497Sdanielk1977   if( IsVirtual(pTab) ) return 0;
2689c00da105Sdanielk1977 
26909562b551Sdrh   /* If we get to here, it means the query is of the correct form.
269117f71934Sdrh   ** Check to make sure we have an index and make pIdx point to the
269217f71934Sdrh   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
269317f71934Sdrh   ** key column, no index is necessary so set pIdx to NULL.  If no
269417f71934Sdrh   ** usable index is found, return 0.
26959562b551Sdrh   */
26969562b551Sdrh   if( iCol<0 ){
26979562b551Sdrh     pIdx = 0;
26989562b551Sdrh   }else{
2699dc1bdc4fSdanielk1977     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
2700206f3d96Sdrh     if( pColl==0 ) return 0;
27019562b551Sdrh     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
27029562b551Sdrh       assert( pIdx->nColumn>=1 );
2703b3bf556eSdanielk1977       if( pIdx->aiColumn[0]==iCol &&
2704b3bf556eSdanielk1977           0==sqlite3StrICmp(pIdx->azColl[0], pColl->zName) ){
2705b3bf556eSdanielk1977         break;
2706b3bf556eSdanielk1977       }
27079562b551Sdrh     }
27089562b551Sdrh     if( pIdx==0 ) return 0;
27099562b551Sdrh   }
27109562b551Sdrh 
2711e5f50722Sdrh   /* Identify column types if we will be using the callback.  This
27129562b551Sdrh   ** step is skipped if the output is going to a table or a memory cell.
2713e5f50722Sdrh   ** The column names have already been generated in the calling function.
27149562b551Sdrh   */
27154adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
27169562b551Sdrh   if( v==0 ) return 0;
27179562b551Sdrh 
27180c37e630Sdrh   /* If the output is destined for a temporary table, open that table.
27190c37e630Sdrh   */
27206c8c8ce0Sdanielk1977   if( pDest->eDest==SRT_EphemTab ){
272166a5167bSdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, 1);
27220c37e630Sdrh   }
27230c37e630Sdrh 
272417f71934Sdrh   /* Generating code to find the min or the max.  Basically all we have
272517f71934Sdrh   ** to do is find the first or the last entry in the chosen index.  If
272617f71934Sdrh   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
272717f71934Sdrh   ** or last entry in the main table.
27289562b551Sdrh   */
2729da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2730b9bb7c18Sdrh   assert( iDb>=0 || pTab->isEphem );
2731da184236Sdanielk1977   sqlite3CodeVerifySchema(pParse, iDb);
2732c00da105Sdanielk1977   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
27336e17529eSdrh   base = pSrc->a[0].iCursor;
2734ec7429aeSdrh   brk = sqlite3VdbeMakeLabel(v);
2735ec7429aeSdrh   computeLimitRegisters(pParse, p, brk);
27366e17529eSdrh   if( pSrc->a[0].pSelect==0 ){
2737c00da105Sdanielk1977     sqlite3OpenTable(pParse, base, iDb, pTab, OP_OpenRead);
27386e17529eSdrh   }
27399562b551Sdrh   if( pIdx==0 ){
274066a5167bSdrh     sqlite3VdbeAddOp2(v, seekOp, base, 0);
27419562b551Sdrh   }else{
27423719d7f9Sdanielk1977     /* Even though the cursor used to open the index here is closed
27433719d7f9Sdanielk1977     ** as soon as a single value has been read from it, allocate it
27443719d7f9Sdanielk1977     ** using (pParse->nTab++) to prevent the cursor id from being
27453719d7f9Sdanielk1977     ** reused. This is important for statements of the form
27463719d7f9Sdanielk1977     ** "INSERT INTO x SELECT max() FROM x".
27473719d7f9Sdanielk1977     */
27483719d7f9Sdanielk1977     int iIdx;
2749b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
27503719d7f9Sdanielk1977     iIdx = pParse->nTab++;
2751da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
2752207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdx, pIdx->tnum, iDb,
275366a5167bSdrh         (char*)pKey, P4_KEYINFO_HANDOFF);
27549eb516c0Sdrh     if( seekOp==OP_Rewind ){
275566a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, 0);
275666a5167bSdrh       sqlite3VdbeAddOp2(v, OP_MakeRecord, 1, 0);
27571af3fdb4Sdrh       seekOp = OP_MoveGt;
27589eb516c0Sdrh     }
2759309be024Sdrh     if( pIdx->aSortOrder[0]==SQLITE_SO_DESC ){
2760309be024Sdrh       /* Ticket #2514: invert the seek operator if we are using
2761309be024Sdrh       ** a descending index. */
2762309be024Sdrh       if( seekOp==OP_Last ){
2763309be024Sdrh         seekOp = OP_Rewind;
2764309be024Sdrh       }else{
2765309be024Sdrh         assert( seekOp==OP_MoveGt );
2766309be024Sdrh         seekOp = OP_MoveLt;
2767309be024Sdrh       }
2768309be024Sdrh     }
276966a5167bSdrh     sqlite3VdbeAddOp2(v, seekOp, iIdx, 0);
277066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdx, 0);
277166a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iIdx, 0);
277266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_MoveGe, base, 0);
27739562b551Sdrh   }
27745cf8e8c7Sdrh   eList.nExpr = 1;
27755cf8e8c7Sdrh   memset(&eListItem, 0, sizeof(eListItem));
27765cf8e8c7Sdrh   eList.a = &eListItem;
27775cf8e8c7Sdrh   eList.a[0].pExpr = pExpr;
27786c8c8ce0Sdanielk1977   selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, pDest, brk, brk, 0);
2779ec7429aeSdrh   sqlite3VdbeResolveLabel(v, brk);
278066a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Close, base, 0);
27816e17529eSdrh 
27829562b551Sdrh   return 1;
27839562b551Sdrh }
27849562b551Sdrh 
27859562b551Sdrh /*
2786b3bce662Sdanielk1977 ** This routine resolves any names used in the result set of the
2787b3bce662Sdanielk1977 ** supplied SELECT statement. If the SELECT statement being resolved
2788b3bce662Sdanielk1977 ** is a sub-select, then pOuterNC is a pointer to the NameContext
2789b3bce662Sdanielk1977 ** of the parent SELECT.
2790b3bce662Sdanielk1977 */
2791b3bce662Sdanielk1977 int sqlite3SelectResolve(
2792b3bce662Sdanielk1977   Parse *pParse,         /* The parser context */
2793b3bce662Sdanielk1977   Select *p,             /* The SELECT statement being coded. */
2794b3bce662Sdanielk1977   NameContext *pOuterNC  /* The outer name context. May be NULL. */
2795b3bce662Sdanielk1977 ){
2796b3bce662Sdanielk1977   ExprList *pEList;          /* Result set. */
2797b3bce662Sdanielk1977   int i;                     /* For-loop variable used in multiple places */
2798b3bce662Sdanielk1977   NameContext sNC;           /* Local name-context */
279913449892Sdrh   ExprList *pGroupBy;        /* The group by clause */
2800b3bce662Sdanielk1977 
2801b3bce662Sdanielk1977   /* If this routine has run before, return immediately. */
2802b3bce662Sdanielk1977   if( p->isResolved ){
2803b3bce662Sdanielk1977     assert( !pOuterNC );
2804b3bce662Sdanielk1977     return SQLITE_OK;
2805b3bce662Sdanielk1977   }
2806b3bce662Sdanielk1977   p->isResolved = 1;
2807b3bce662Sdanielk1977 
2808b3bce662Sdanielk1977   /* If there have already been errors, do nothing. */
2809b3bce662Sdanielk1977   if( pParse->nErr>0 ){
2810b3bce662Sdanielk1977     return SQLITE_ERROR;
2811b3bce662Sdanielk1977   }
2812b3bce662Sdanielk1977 
2813b3bce662Sdanielk1977   /* Prepare the select statement. This call will allocate all cursors
2814b3bce662Sdanielk1977   ** required to handle the tables and subqueries in the FROM clause.
2815b3bce662Sdanielk1977   */
2816b3bce662Sdanielk1977   if( prepSelectStmt(pParse, p) ){
2817b3bce662Sdanielk1977     return SQLITE_ERROR;
2818b3bce662Sdanielk1977   }
2819b3bce662Sdanielk1977 
2820a2dc3b1aSdanielk1977   /* Resolve the expressions in the LIMIT and OFFSET clauses. These
2821a2dc3b1aSdanielk1977   ** are not allowed to refer to any names, so pass an empty NameContext.
2822a2dc3b1aSdanielk1977   */
2823ffe07b2dSdrh   memset(&sNC, 0, sizeof(sNC));
2824b3bce662Sdanielk1977   sNC.pParse = pParse;
2825a2dc3b1aSdanielk1977   if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2826a2dc3b1aSdanielk1977       sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2827a2dc3b1aSdanielk1977     return SQLITE_ERROR;
2828a2dc3b1aSdanielk1977   }
2829a2dc3b1aSdanielk1977 
2830a2dc3b1aSdanielk1977   /* Set up the local name-context to pass to ExprResolveNames() to
2831a2dc3b1aSdanielk1977   ** resolve the expression-list.
2832a2dc3b1aSdanielk1977   */
2833a2dc3b1aSdanielk1977   sNC.allowAgg = 1;
2834a2dc3b1aSdanielk1977   sNC.pSrcList = p->pSrc;
2835a2dc3b1aSdanielk1977   sNC.pNext = pOuterNC;
2836b3bce662Sdanielk1977 
2837b3bce662Sdanielk1977   /* Resolve names in the result set. */
2838b3bce662Sdanielk1977   pEList = p->pEList;
2839b3bce662Sdanielk1977   if( !pEList ) return SQLITE_ERROR;
2840b3bce662Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
2841b3bce662Sdanielk1977     Expr *pX = pEList->a[i].pExpr;
2842b3bce662Sdanielk1977     if( sqlite3ExprResolveNames(&sNC, pX) ){
2843b3bce662Sdanielk1977       return SQLITE_ERROR;
2844b3bce662Sdanielk1977     }
2845b3bce662Sdanielk1977   }
2846b3bce662Sdanielk1977 
2847b3bce662Sdanielk1977   /* If there are no aggregate functions in the result-set, and no GROUP BY
2848b3bce662Sdanielk1977   ** expression, do not allow aggregates in any of the other expressions.
2849b3bce662Sdanielk1977   */
2850b3bce662Sdanielk1977   assert( !p->isAgg );
285113449892Sdrh   pGroupBy = p->pGroupBy;
285213449892Sdrh   if( pGroupBy || sNC.hasAgg ){
2853b3bce662Sdanielk1977     p->isAgg = 1;
2854b3bce662Sdanielk1977   }else{
2855b3bce662Sdanielk1977     sNC.allowAgg = 0;
2856b3bce662Sdanielk1977   }
2857b3bce662Sdanielk1977 
2858b3bce662Sdanielk1977   /* If a HAVING clause is present, then there must be a GROUP BY clause.
2859b3bce662Sdanielk1977   */
286013449892Sdrh   if( p->pHaving && !pGroupBy ){
2861b3bce662Sdanielk1977     sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2862b3bce662Sdanielk1977     return SQLITE_ERROR;
2863b3bce662Sdanielk1977   }
2864b3bce662Sdanielk1977 
2865b3bce662Sdanielk1977   /* Add the expression list to the name-context before parsing the
2866b3bce662Sdanielk1977   ** other expressions in the SELECT statement. This is so that
2867b3bce662Sdanielk1977   ** expressions in the WHERE clause (etc.) can refer to expressions by
2868b3bce662Sdanielk1977   ** aliases in the result set.
2869b3bce662Sdanielk1977   **
2870b3bce662Sdanielk1977   ** Minor point: If this is the case, then the expression will be
2871b3bce662Sdanielk1977   ** re-evaluated for each reference to it.
2872b3bce662Sdanielk1977   */
2873b3bce662Sdanielk1977   sNC.pEList = p->pEList;
2874b3bce662Sdanielk1977   if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2875994c80afSdrh      sqlite3ExprResolveNames(&sNC, p->pHaving) ){
2876b3bce662Sdanielk1977     return SQLITE_ERROR;
2877b3bce662Sdanielk1977   }
28789a99334dSdrh   if( p->pPrior==0 ){
287901874bfcSdanielk1977     if( processOrderGroupBy(pParse, p, p->pOrderBy, 1, &sNC.hasAgg) ){
2880994c80afSdrh       return SQLITE_ERROR;
2881994c80afSdrh     }
28829a99334dSdrh   }
28839a99334dSdrh   if( processOrderGroupBy(pParse, p, pGroupBy, 0, &sNC.hasAgg) ){
28844c774314Sdrh     return SQLITE_ERROR;
2885994c80afSdrh   }
2886b3bce662Sdanielk1977 
28871e536953Sdanielk1977   if( pParse->db->mallocFailed ){
28889afe689eSdanielk1977     return SQLITE_NOMEM;
28899afe689eSdanielk1977   }
28909afe689eSdanielk1977 
289113449892Sdrh   /* Make sure the GROUP BY clause does not contain aggregate functions.
289213449892Sdrh   */
289313449892Sdrh   if( pGroupBy ){
289413449892Sdrh     struct ExprList_item *pItem;
289513449892Sdrh 
289613449892Sdrh     for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
289713449892Sdrh       if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
289813449892Sdrh         sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
289913449892Sdrh             "the GROUP BY clause");
290013449892Sdrh         return SQLITE_ERROR;
290113449892Sdrh       }
290213449892Sdrh     }
290313449892Sdrh   }
290413449892Sdrh 
2905f6bbe022Sdrh   /* If this is one SELECT of a compound, be sure to resolve names
2906f6bbe022Sdrh   ** in the other SELECTs.
2907f6bbe022Sdrh   */
2908f6bbe022Sdrh   if( p->pPrior ){
2909f6bbe022Sdrh     return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC);
2910f6bbe022Sdrh   }else{
2911b3bce662Sdanielk1977     return SQLITE_OK;
2912b3bce662Sdanielk1977   }
2913f6bbe022Sdrh }
2914b3bce662Sdanielk1977 
2915b3bce662Sdanielk1977 /*
291613449892Sdrh ** Reset the aggregate accumulator.
291713449892Sdrh **
291813449892Sdrh ** The aggregate accumulator is a set of memory cells that hold
291913449892Sdrh ** intermediate results while calculating an aggregate.  This
292013449892Sdrh ** routine simply stores NULLs in all of those memory cells.
2921b3bce662Sdanielk1977 */
292213449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
292313449892Sdrh   Vdbe *v = pParse->pVdbe;
292413449892Sdrh   int i;
2925c99130fdSdrh   struct AggInfo_func *pFunc;
292613449892Sdrh   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
292713449892Sdrh     return;
292813449892Sdrh   }
292913449892Sdrh   for(i=0; i<pAggInfo->nColumn; i++){
29304c583128Sdrh     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
293113449892Sdrh   }
2932c99130fdSdrh   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
29334c583128Sdrh     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
2934c99130fdSdrh     if( pFunc->iDistinct>=0 ){
2935c99130fdSdrh       Expr *pE = pFunc->pExpr;
2936c99130fdSdrh       if( pE->pList==0 || pE->pList->nExpr!=1 ){
2937c99130fdSdrh         sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
2938c99130fdSdrh            "by an expression");
2939c99130fdSdrh         pFunc->iDistinct = -1;
2940c99130fdSdrh       }else{
2941c99130fdSdrh         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
294266a5167bSdrh         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
294366a5167bSdrh                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
2944c99130fdSdrh       }
2945c99130fdSdrh     }
294613449892Sdrh   }
2947b3bce662Sdanielk1977 }
2948b3bce662Sdanielk1977 
2949b3bce662Sdanielk1977 /*
295013449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function
295113449892Sdrh ** in the AggInfo structure.
2952b3bce662Sdanielk1977 */
295313449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
295413449892Sdrh   Vdbe *v = pParse->pVdbe;
295513449892Sdrh   int i;
295613449892Sdrh   struct AggInfo_func *pF;
295713449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
2958a10a34b8Sdrh     ExprList *pList = pF->pExpr->pList;
295966a5167bSdrh     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
296066a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
2961b3bce662Sdanielk1977   }
296213449892Sdrh }
296313449892Sdrh 
296413449892Sdrh /*
296513449892Sdrh ** Update the accumulator memory cells for an aggregate based on
296613449892Sdrh ** the current cursor position.
296713449892Sdrh */
296813449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
296913449892Sdrh   Vdbe *v = pParse->pVdbe;
297013449892Sdrh   int i;
297113449892Sdrh   struct AggInfo_func *pF;
297213449892Sdrh   struct AggInfo_col *pC;
297313449892Sdrh 
297413449892Sdrh   pAggInfo->directMode = 1;
297513449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
297613449892Sdrh     int nArg;
2977c99130fdSdrh     int addrNext = 0;
297813449892Sdrh     ExprList *pList = pF->pExpr->pList;
297913449892Sdrh     if( pList ){
298013449892Sdrh       nArg = pList->nExpr;
2981389a1adbSdrh       sqlite3ExprCodeExprList(pParse, pList, 0);
298213449892Sdrh     }else{
298313449892Sdrh       nArg = 0;
298413449892Sdrh     }
2985c99130fdSdrh     if( pF->iDistinct>=0 ){
2986c99130fdSdrh       addrNext = sqlite3VdbeMakeLabel(v);
2987c99130fdSdrh       assert( nArg==1 );
2988a2a49dc9Sdrh       codeDistinct_OLD(v, pF->iDistinct, addrNext, 1);
2989c99130fdSdrh     }
299013449892Sdrh     if( pF->pFunc->needCollSeq ){
299113449892Sdrh       CollSeq *pColl = 0;
299213449892Sdrh       struct ExprList_item *pItem;
299313449892Sdrh       int j;
299443617e9aSdrh       assert( pList!=0 );  /* pList!=0 if pF->pFunc->needCollSeq is true */
299543617e9aSdrh       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
299613449892Sdrh         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
299713449892Sdrh       }
299813449892Sdrh       if( !pColl ){
299913449892Sdrh         pColl = pParse->db->pDfltColl;
300013449892Sdrh       }
300166a5167bSdrh       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
300213449892Sdrh     }
300366a5167bSdrh     sqlite3VdbeAddOp4(v, OP_AggStep, pF->iMem, nArg, 0,
300466a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
3005c99130fdSdrh     if( addrNext ){
3006c99130fdSdrh       sqlite3VdbeResolveLabel(v, addrNext);
3007c99130fdSdrh     }
300813449892Sdrh   }
300913449892Sdrh   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
3010389a1adbSdrh     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
301113449892Sdrh   }
301213449892Sdrh   pAggInfo->directMode = 0;
301313449892Sdrh }
301413449892Sdrh 
30158f2c54e6Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
30168f2c54e6Sdanielk1977 /*
30178f2c54e6Sdanielk1977 ** This function is used when a SELECT statement is used to create a
30188f2c54e6Sdanielk1977 ** temporary table for iterating through when running an INSTEAD OF
30198f2c54e6Sdanielk1977 ** UPDATE or INSTEAD OF DELETE trigger.
30208f2c54e6Sdanielk1977 **
30218f2c54e6Sdanielk1977 ** If possible, the SELECT statement is modified so that NULL values
30228f2c54e6Sdanielk1977 ** are stored in the temporary table for all columns for which the
30238f2c54e6Sdanielk1977 ** corresponding bit in argument mask is not set. If mask takes the
30248f2c54e6Sdanielk1977 ** special value 0xffffffff, then all columns are populated.
30258f2c54e6Sdanielk1977 */
30268f2c54e6Sdanielk1977 int sqlite3SelectMask(Parse *pParse, Select *p, u32 mask){
30278f2c54e6Sdanielk1977   if( !p->pPrior && !p->isDistinct && mask!=0xffffffff ){
30288f2c54e6Sdanielk1977     ExprList *pEList;
30298f2c54e6Sdanielk1977     int i;
30308f2c54e6Sdanielk1977     if( sqlite3SelectResolve(pParse, p, 0) ){
30318f2c54e6Sdanielk1977       return SQLITE_ERROR;
30328f2c54e6Sdanielk1977     }
30338f2c54e6Sdanielk1977     pEList = p->pEList;
30348f2c54e6Sdanielk1977     for(i=0; i<pEList->nExpr && i<32; i++){
30358f2c54e6Sdanielk1977       if( !(mask&((u32)1<<i)) ){
30368f2c54e6Sdanielk1977         sqlite3ExprDelete(pEList->a[i].pExpr);
30378f2c54e6Sdanielk1977         pEList->a[i].pExpr = sqlite3Expr(pParse->db, TK_NULL, 0, 0, 0);
30388f2c54e6Sdanielk1977       }
30398f2c54e6Sdanielk1977     }
30408f2c54e6Sdanielk1977   }
30418f2c54e6Sdanielk1977   return SQLITE_OK;
30428f2c54e6Sdanielk1977 }
30438f2c54e6Sdanielk1977 #endif
3044b3bce662Sdanielk1977 
3045b3bce662Sdanielk1977 /*
30469bb61fe7Sdrh ** Generate code for the given SELECT statement.
30479bb61fe7Sdrh **
3048fef5208cSdrh ** The results are distributed in various ways depending on the
30496c8c8ce0Sdanielk1977 ** contents of the SelectDest structure pointed to by argument pDest
30506c8c8ce0Sdanielk1977 ** as follows:
3051fef5208cSdrh **
30526c8c8ce0Sdanielk1977 **     pDest->eDest    Result
3053fef5208cSdrh **     ------------    -------------------------------------------
3054fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
3055fef5208cSdrh **
30566c8c8ce0Sdanielk1977 **     SRT_Mem         Store first result in memory cell pDest->iParm
3057fef5208cSdrh **
30586c8c8ce0Sdanielk1977 **     SRT_Set         Store non-null results as keys of table pDest->iParm.
30596c8c8ce0Sdanielk1977 **                     Apply the affinity pDest->affinity before storing them.
3060fef5208cSdrh **
30616c8c8ce0Sdanielk1977 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
306282c3d636Sdrh **
30636c8c8ce0Sdanielk1977 **     SRT_Except      Remove results from the temporary table pDest->iParm.
3064c4a3c779Sdrh **
30656c8c8ce0Sdanielk1977 **     SRT_Table       Store results in temporary table pDest->iParm
30669bb61fe7Sdrh **
30676c8c8ce0Sdanielk1977 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
30686c8c8ce0Sdanielk1977 **                     the result there. The cursor is left open after
30696c8c8ce0Sdanielk1977 **                     returning.
30706c8c8ce0Sdanielk1977 **
30716c8c8ce0Sdanielk1977 **     SRT_Subroutine  For each row returned, push the results onto the
30726c8c8ce0Sdanielk1977 **                     vdbe stack and call the subroutine (via OP_Gosub)
30736c8c8ce0Sdanielk1977 **                     at address pDest->iParm.
30746c8c8ce0Sdanielk1977 **
30756c8c8ce0Sdanielk1977 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
30766c8c8ce0Sdanielk1977 **                     set is not empty.
30776c8c8ce0Sdanielk1977 **
30786c8c8ce0Sdanielk1977 **     SRT_Discard     Throw the results away.
30796c8c8ce0Sdanielk1977 **
30806c8c8ce0Sdanielk1977 ** See the selectInnerLoop() function for a canonical listing of the
30816c8c8ce0Sdanielk1977 ** allowed values of eDest and their meanings.
3082e78e8284Sdrh **
30839bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
30849bb61fe7Sdrh ** encountered, then an appropriate error message is left in
30859bb61fe7Sdrh ** pParse->zErrMsg.
30869bb61fe7Sdrh **
30879bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
30889bb61fe7Sdrh ** calling function needs to do that.
30891b2e0329Sdrh **
30901b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
30911b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
30921b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
30931b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
30941b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
30951b2e0329Sdrh ** can be changed.
3096e78e8284Sdrh **
3097e78e8284Sdrh ** Example 1:   The meaning of the pParent parameter.
3098e78e8284Sdrh **
3099e78e8284Sdrh **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
3100e78e8284Sdrh **    \                      \_______ subquery _______/        /
3101e78e8284Sdrh **     \                                                      /
3102e78e8284Sdrh **      \____________________ outer query ___________________/
3103e78e8284Sdrh **
3104e78e8284Sdrh ** This routine is called for the outer query first.   For that call,
3105e78e8284Sdrh ** pParent will be NULL.  During the processing of the outer query, this
3106e78e8284Sdrh ** routine is called recursively to handle the subquery.  For the recursive
3107e78e8284Sdrh ** call, pParent will point to the outer query.  Because the subquery is
3108e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will
3109e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.)
31109bb61fe7Sdrh */
31114adee20fSdanielk1977 int sqlite3Select(
3112cce7d176Sdrh   Parse *pParse,         /* The parser context */
31139bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
31146c8c8ce0Sdanielk1977   SelectDest *pDest,     /* What to do with the query results */
3115832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
3116832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
311784ac9d02Sdanielk1977   int *pParentAgg,       /* True if pParent uses aggregate functions */
3118b3bce662Sdanielk1977   char *aff              /* If eDest is SRT_Union, the affinity string */
3119cce7d176Sdrh ){
312013449892Sdrh   int i, j;              /* Loop counters */
312113449892Sdrh   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
312213449892Sdrh   Vdbe *v;               /* The virtual machine under construction */
3123b3bce662Sdanielk1977   int isAgg;             /* True for select lists like "count(*)" */
3124a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
3125ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
31269bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
31279bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
31282282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
31292282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
313019a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
313119a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
31321d83f052Sdrh   int rc = 1;            /* Value to return from this function */
3133b9bb7c18Sdrh   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
313413449892Sdrh   AggInfo sAggInfo;      /* Information used by aggregate queries */
3135ec7429aeSdrh   int iEnd;              /* Address of the end of the query */
313617435752Sdrh   sqlite3 *db;           /* The database connection */
31379bb61fe7Sdrh 
313817435752Sdrh   db = pParse->db;
313917435752Sdrh   if( p==0 || db->mallocFailed || pParse->nErr ){
31406f7adc8aSdrh     return 1;
31416f7adc8aSdrh   }
31424adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
314313449892Sdrh   memset(&sAggInfo, 0, sizeof(sAggInfo));
3144daffd0e5Sdrh 
31459a99334dSdrh   pOrderBy = p->pOrderBy;
31466c8c8ce0Sdanielk1977   if( IgnorableOrderby(pDest) ){
31479a99334dSdrh     p->pOrderBy = 0;
31489ed1dfa8Sdanielk1977 
31499ed1dfa8Sdanielk1977     /* In these cases the DISTINCT operator makes no difference to the
31509ed1dfa8Sdanielk1977     ** results, so remove it if it were specified.
31519ed1dfa8Sdanielk1977     */
31529ed1dfa8Sdanielk1977     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
31539ed1dfa8Sdanielk1977            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
31549ed1dfa8Sdanielk1977     p->isDistinct = 0;
31559a99334dSdrh   }
31569a99334dSdrh   if( sqlite3SelectResolve(pParse, p, 0) ){
31579a99334dSdrh     goto select_end;
31589a99334dSdrh   }
31599a99334dSdrh   p->pOrderBy = pOrderBy;
31609a99334dSdrh 
3161b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
316282c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
316382c3d636Sdrh   */
316482c3d636Sdrh   if( p->pPrior ){
31650342b1f5Sdrh     if( p->pRightmost==0 ){
31661e281291Sdrh       Select *pLoop, *pRight = 0;
31670325d873Sdrh       int cnt = 0;
31680325d873Sdrh       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
31690342b1f5Sdrh         pLoop->pRightmost = p;
31701e281291Sdrh         pLoop->pNext = pRight;
31711e281291Sdrh         pRight = pLoop;
31720342b1f5Sdrh       }
31730325d873Sdrh       if( SQLITE_MAX_COMPOUND_SELECT>0 && cnt>SQLITE_MAX_COMPOUND_SELECT ){
31740325d873Sdrh         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
31750325d873Sdrh         return 1;
31760325d873Sdrh       }
31770342b1f5Sdrh     }
31786c8c8ce0Sdanielk1977     return multiSelect(pParse, p, pDest, aff);
317982c3d636Sdrh   }
3180b7f9164eSdrh #endif
318182c3d636Sdrh 
318282c3d636Sdrh   /* Make local copies of the parameters for this query.
318382c3d636Sdrh   */
31849bb61fe7Sdrh   pTabList = p->pSrc;
31859bb61fe7Sdrh   pWhere = p->pWhere;
31862282792aSdrh   pGroupBy = p->pGroupBy;
31872282792aSdrh   pHaving = p->pHaving;
3188b3bce662Sdanielk1977   isAgg = p->isAgg;
318919a775c2Sdrh   isDistinct = p->isDistinct;
3190b3bce662Sdanielk1977   pEList = p->pEList;
3191b3bce662Sdanielk1977   if( pEList==0 ) goto select_end;
31929bb61fe7Sdrh 
31939bb61fe7Sdrh   /*
31949bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
31959bb61fe7Sdrh   ** errors before this routine starts.
31969bb61fe7Sdrh   */
31971d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
3198cce7d176Sdrh 
31992282792aSdrh   /* If writing to memory or generating a set
32002282792aSdrh   ** only a single column may be output.
320119a775c2Sdrh   */
320293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
32036c8c8ce0Sdanielk1977   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
32041d83f052Sdrh     goto select_end;
320519a775c2Sdrh   }
320693758c8dSdanielk1977 #endif
320719a775c2Sdrh 
3208c926afbcSdrh   /* ORDER BY is ignored for some destinations.
32092282792aSdrh   */
32106c8c8ce0Sdanielk1977   if( IgnorableOrderby(pDest) ){
3211acd4c695Sdrh     pOrderBy = 0;
32122282792aSdrh   }
32132282792aSdrh 
3214d820cb1bSdrh   /* Begin generating code.
3215d820cb1bSdrh   */
32164adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
3217d820cb1bSdrh   if( v==0 ) goto select_end;
3218d820cb1bSdrh 
3219d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
3220d820cb1bSdrh   */
322151522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3222ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
3223742f947bSdanielk1977     const char *zSavedAuthContext = 0;
3224c31c2eb8Sdrh     int needRestoreContext;
322513449892Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
32266c8c8ce0Sdanielk1977     SelectDest dest = {SRT_EphemTab, 0, 0};
3227c31c2eb8Sdrh 
32281787ccabSdanielk1977     if( pItem->pSelect==0 || pItem->isPopulated ) continue;
322913449892Sdrh     if( pItem->zName!=0 ){
32305cf590c1Sdrh       zSavedAuthContext = pParse->zAuthContext;
323113449892Sdrh       pParse->zAuthContext = pItem->zName;
3232c31c2eb8Sdrh       needRestoreContext = 1;
3233c31c2eb8Sdrh     }else{
3234c31c2eb8Sdrh       needRestoreContext = 0;
32355cf590c1Sdrh     }
3236e6a58a4eSdanielk1977 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
3237fc976065Sdanielk1977     /* Increment Parse.nHeight by the height of the largest expression
3238fc976065Sdanielk1977     ** tree refered to by this, the parent select. The child select
3239fc976065Sdanielk1977     ** may contain expression trees of at most
3240fc976065Sdanielk1977     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
3241fc976065Sdanielk1977     ** more conservative than necessary, but much easier than enforcing
3242fc976065Sdanielk1977     ** an exact limit.
3243fc976065Sdanielk1977     */
3244fc976065Sdanielk1977     pParse->nHeight += sqlite3SelectExprHeight(p);
3245fc976065Sdanielk1977 #endif
32466c8c8ce0Sdanielk1977     dest.iParm = pItem->iCursor;
32476c8c8ce0Sdanielk1977     sqlite3Select(pParse, pItem->pSelect, &dest, p, i, &isAgg, 0);
3248cfa063b3Sdrh     if( db->mallocFailed ){
3249cfa063b3Sdrh       goto select_end;
3250cfa063b3Sdrh     }
3251e6a58a4eSdanielk1977 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
3252fc976065Sdanielk1977     pParse->nHeight -= sqlite3SelectExprHeight(p);
3253fc976065Sdanielk1977 #endif
3254c31c2eb8Sdrh     if( needRestoreContext ){
32555cf590c1Sdrh       pParse->zAuthContext = zSavedAuthContext;
32565cf590c1Sdrh     }
3257832508b7Sdrh     pTabList = p->pSrc;
3258832508b7Sdrh     pWhere = p->pWhere;
32596c8c8ce0Sdanielk1977     if( !IgnorableOrderby(pDest) ){
3260832508b7Sdrh       pOrderBy = p->pOrderBy;
3261acd4c695Sdrh     }
3262832508b7Sdrh     pGroupBy = p->pGroupBy;
3263832508b7Sdrh     pHaving = p->pHaving;
3264832508b7Sdrh     isDistinct = p->isDistinct;
32651b2e0329Sdrh   }
326651522cd3Sdrh #endif
32671b2e0329Sdrh 
32686e17529eSdrh   /* Check for the special case of a min() or max() function by itself
32696e17529eSdrh   ** in the result set.
32706e17529eSdrh   */
32716c8c8ce0Sdanielk1977   if( simpleMinMaxQuery(pParse, p, pDest) ){
32726e17529eSdrh     rc = 0;
32736e17529eSdrh     goto select_end;
32746e17529eSdrh   }
32756e17529eSdrh 
32761b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
32771b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
32781b2e0329Sdrh   */
3279b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
32801b2e0329Sdrh   if( pParent && pParentAgg &&
328117435752Sdrh       flattenSubquery(db, pParent, parentTab, *pParentAgg, isAgg) ){
32821b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
3283b3bce662Sdanielk1977     goto select_end;
32841b2e0329Sdrh   }
3285b7f9164eSdrh #endif
3286832508b7Sdrh 
32870318d441Sdanielk1977   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
32880318d441Sdanielk1977   ** GROUP BY may use an index, DISTINCT never does.
32893c4809a2Sdanielk1977   */
32903c4809a2Sdanielk1977   if( p->isDistinct && !p->isAgg && !p->pGroupBy ){
32913c4809a2Sdanielk1977     p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
32923c4809a2Sdanielk1977     pGroupBy = p->pGroupBy;
32933c4809a2Sdanielk1977     p->isDistinct = 0;
32943c4809a2Sdanielk1977     isDistinct = 0;
32953c4809a2Sdanielk1977   }
32963c4809a2Sdanielk1977 
32978b4c40d8Sdrh   /* If there is an ORDER BY clause, then this sorting
32988b4c40d8Sdrh   ** index might end up being unused if the data can be
32999d2985c7Sdrh   ** extracted in pre-sorted order.  If that is the case, then the
3300b9bb7c18Sdrh   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
33019d2985c7Sdrh   ** we figure out that the sorting index is not needed.  The addrSortIndex
33029d2985c7Sdrh   ** variable is used to facilitate that change.
33037cedc8d4Sdanielk1977   */
33047cedc8d4Sdanielk1977   if( pOrderBy ){
33050342b1f5Sdrh     KeyInfo *pKeyInfo;
33067cedc8d4Sdanielk1977     if( pParse->nErr ){
33077cedc8d4Sdanielk1977       goto select_end;
33087cedc8d4Sdanielk1977     }
33090342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
33109d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
3311b9bb7c18Sdrh     p->addrOpenEphm[2] = addrSortIndex =
331266a5167bSdrh       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
331366a5167bSdrh                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
331466a5167bSdrh                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
33159d2985c7Sdrh   }else{
33169d2985c7Sdrh     addrSortIndex = -1;
33177cedc8d4Sdanielk1977   }
33187cedc8d4Sdanielk1977 
33192d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
33202d0794e3Sdrh   */
33216c8c8ce0Sdanielk1977   if( pDest->eDest==SRT_EphemTab ){
332266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
33232d0794e3Sdrh   }
33242d0794e3Sdrh 
3325f42bacc2Sdrh   /* Set the limiter.
3326f42bacc2Sdrh   */
3327f42bacc2Sdrh   iEnd = sqlite3VdbeMakeLabel(v);
3328f42bacc2Sdrh   computeLimitRegisters(pParse, p, iEnd);
3329f42bacc2Sdrh 
3330dece1a84Sdrh   /* Open a virtual index to use for the distinct set.
3331cce7d176Sdrh   */
333219a775c2Sdrh   if( isDistinct ){
33330342b1f5Sdrh     KeyInfo *pKeyInfo;
33343c4809a2Sdanielk1977     assert( isAgg || pGroupBy );
3335832508b7Sdrh     distinct = pParse->nTab++;
33360342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
333766a5167bSdrh     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
333866a5167bSdrh                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
3339832508b7Sdrh   }else{
3340832508b7Sdrh     distinct = -1;
3341efb7251dSdrh   }
3342832508b7Sdrh 
334313449892Sdrh   /* Aggregate and non-aggregate queries are handled differently */
334413449892Sdrh   if( !isAgg && pGroupBy==0 ){
334513449892Sdrh     /* This case is for non-aggregate queries
334613449892Sdrh     ** Begin the database scan
3347832508b7Sdrh     */
334813449892Sdrh     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy);
33491d83f052Sdrh     if( pWInfo==0 ) goto select_end;
3350cce7d176Sdrh 
3351b9bb7c18Sdrh     /* If sorting index that was created by a prior OP_OpenEphemeral
3352b9bb7c18Sdrh     ** instruction ended up not being needed, then change the OP_OpenEphemeral
33539d2985c7Sdrh     ** into an OP_Noop.
33549d2985c7Sdrh     */
33559d2985c7Sdrh     if( addrSortIndex>=0 && pOrderBy==0 ){
3356f8875400Sdrh       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
3357b9bb7c18Sdrh       p->addrOpenEphm[2] = -1;
33589d2985c7Sdrh     }
33599d2985c7Sdrh 
336013449892Sdrh     /* Use the standard inner loop
3361cce7d176Sdrh     */
33623c4809a2Sdanielk1977     assert(!isDistinct);
33636c8c8ce0Sdanielk1977     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
33646c8c8ce0Sdanielk1977                     pWInfo->iContinue, pWInfo->iBreak, aff) ){
33651d83f052Sdrh        goto select_end;
3366cce7d176Sdrh     }
33672282792aSdrh 
3368cce7d176Sdrh     /* End the database scan loop.
3369cce7d176Sdrh     */
33704adee20fSdanielk1977     sqlite3WhereEnd(pWInfo);
337113449892Sdrh   }else{
337213449892Sdrh     /* This is the processing for aggregate queries */
337313449892Sdrh     NameContext sNC;    /* Name context for processing aggregate information */
337413449892Sdrh     int iAMem;          /* First Mem address for storing current GROUP BY */
337513449892Sdrh     int iBMem;          /* First Mem address for previous GROUP BY */
337613449892Sdrh     int iUseFlag;       /* Mem address holding flag indicating that at least
337713449892Sdrh                         ** one row of the input to the aggregator has been
337813449892Sdrh                         ** processed */
337913449892Sdrh     int iAbortFlag;     /* Mem address which causes query abort if positive */
338013449892Sdrh     int groupBySort;    /* Rows come from source in GROUP BY order */
3381cce7d176Sdrh 
338213449892Sdrh 
338313449892Sdrh     /* The following variables hold addresses or labels for parts of the
338413449892Sdrh     ** virtual machine program we are putting together */
338513449892Sdrh     int addrOutputRow;      /* Start of subroutine that outputs a result row */
338613449892Sdrh     int addrSetAbort;       /* Set the abort flag and return */
338713449892Sdrh     int addrInitializeLoop; /* Start of code that initializes the input loop */
338813449892Sdrh     int addrTopOfLoop;      /* Top of the input loop */
338913449892Sdrh     int addrGroupByChange;  /* Code that runs when any GROUP BY term changes */
339013449892Sdrh     int addrProcessRow;     /* Code to process a single input row */
339113449892Sdrh     int addrEnd;            /* End of all processing */
3392b9bb7c18Sdrh     int addrSortingIdx;     /* The OP_OpenEphemeral for the sorting index */
3393e313382eSdrh     int addrReset;          /* Subroutine for resetting the accumulator */
339413449892Sdrh 
339513449892Sdrh     addrEnd = sqlite3VdbeMakeLabel(v);
339613449892Sdrh 
339713449892Sdrh     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
339813449892Sdrh     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
339913449892Sdrh     ** SELECT statement.
34002282792aSdrh     */
340113449892Sdrh     memset(&sNC, 0, sizeof(sNC));
340213449892Sdrh     sNC.pParse = pParse;
340313449892Sdrh     sNC.pSrcList = pTabList;
340413449892Sdrh     sNC.pAggInfo = &sAggInfo;
340513449892Sdrh     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
34069d2985c7Sdrh     sAggInfo.pGroupBy = pGroupBy;
340713449892Sdrh     if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){
34081d83f052Sdrh       goto select_end;
34092282792aSdrh     }
341013449892Sdrh     if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){
341113449892Sdrh       goto select_end;
34122282792aSdrh     }
341313449892Sdrh     if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
341413449892Sdrh       goto select_end;
341513449892Sdrh     }
341613449892Sdrh     sAggInfo.nAccumulator = sAggInfo.nColumn;
341713449892Sdrh     for(i=0; i<sAggInfo.nFunc; i++){
341813449892Sdrh       if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
341913449892Sdrh         goto select_end;
342013449892Sdrh       }
342113449892Sdrh     }
342217435752Sdrh     if( db->mallocFailed ) goto select_end;
342313449892Sdrh 
342413449892Sdrh     /* Processing for aggregates with GROUP BY is very different and
34253c4809a2Sdanielk1977     ** much more complex than aggregates without a GROUP BY.
342613449892Sdrh     */
342713449892Sdrh     if( pGroupBy ){
342813449892Sdrh       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
342913449892Sdrh 
343013449892Sdrh       /* Create labels that we will be needing
343113449892Sdrh       */
343213449892Sdrh 
343313449892Sdrh       addrInitializeLoop = sqlite3VdbeMakeLabel(v);
343413449892Sdrh       addrGroupByChange = sqlite3VdbeMakeLabel(v);
343513449892Sdrh       addrProcessRow = sqlite3VdbeMakeLabel(v);
343613449892Sdrh 
343713449892Sdrh       /* If there is a GROUP BY clause we might need a sorting index to
343813449892Sdrh       ** implement it.  Allocate that sorting index now.  If it turns out
3439b9bb7c18Sdrh       ** that we do not need it after all, the OpenEphemeral instruction
344013449892Sdrh       ** will be converted into a Noop.
344113449892Sdrh       */
344213449892Sdrh       sAggInfo.sortingIdx = pParse->nTab++;
344313449892Sdrh       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
344413449892Sdrh       addrSortingIdx =
344566a5167bSdrh           sqlite3VdbeAddOp4(v, OP_OpenEphemeral, sAggInfo.sortingIdx,
344666a5167bSdrh                          sAggInfo.nSortingColumn, 0,
344766a5167bSdrh                          (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
344813449892Sdrh 
344913449892Sdrh       /* Initialize memory locations used by GROUP BY aggregate processing
345013449892Sdrh       */
34510a07c107Sdrh       iUseFlag = ++pParse->nMem;
34520a07c107Sdrh       iAbortFlag = ++pParse->nMem;
34530a07c107Sdrh       iAMem = pParse->nMem + 1;
345413449892Sdrh       pParse->nMem += pGroupBy->nExpr;
34550a07c107Sdrh       iBMem = pParse->nMem + 1;
345613449892Sdrh       pParse->nMem += pGroupBy->nExpr;
34574c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
3458d4e70ebdSdrh       VdbeComment((v, "clear abort flag"));
34594c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
3460d4e70ebdSdrh       VdbeComment((v, "indicate accumulator empty"));
346166a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrInitializeLoop);
346213449892Sdrh 
346313449892Sdrh       /* Generate a subroutine that outputs a single row of the result
346413449892Sdrh       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
346513449892Sdrh       ** is less than or equal to zero, the subroutine is a no-op.  If
346613449892Sdrh       ** the processing calls for the query to abort, this subroutine
346713449892Sdrh       ** increments the iAbortFlag memory location before returning in
346813449892Sdrh       ** order to signal the caller to abort.
346913449892Sdrh       */
347013449892Sdrh       addrSetAbort = sqlite3VdbeCurrentAddr(v);
34714c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
3472d4e70ebdSdrh       VdbeComment((v, "set abort flag"));
347366a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
347413449892Sdrh       addrOutputRow = sqlite3VdbeCurrentAddr(v);
347566a5167bSdrh       sqlite3VdbeAddOp2(v, OP_IfMemPos, iUseFlag, addrOutputRow+2);
3476d4e70ebdSdrh       VdbeComment((v, "Groupby result generator entry point"));
347766a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
347813449892Sdrh       finalizeAggFunctions(pParse, &sAggInfo);
347913449892Sdrh       if( pHaving ){
348013449892Sdrh         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1);
348113449892Sdrh       }
348213449892Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
34836c8c8ce0Sdanielk1977                            distinct, pDest,
348413449892Sdrh                            addrOutputRow+1, addrSetAbort, aff);
348513449892Sdrh       if( rc ){
348613449892Sdrh         goto select_end;
348713449892Sdrh       }
348866a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
3489d4e70ebdSdrh       VdbeComment((v, "end groupby result generator"));
349013449892Sdrh 
3491e313382eSdrh       /* Generate a subroutine that will reset the group-by accumulator
3492e313382eSdrh       */
3493e313382eSdrh       addrReset = sqlite3VdbeCurrentAddr(v);
3494e313382eSdrh       resetAccumulator(pParse, &sAggInfo);
349566a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
3496e313382eSdrh 
349713449892Sdrh       /* Begin a loop that will extract all source rows in GROUP BY order.
349813449892Sdrh       ** This might involve two separate loops with an OP_Sort in between, or
349913449892Sdrh       ** it might be a single loop that uses an index to extract information
350013449892Sdrh       ** in the right order to begin with.
350113449892Sdrh       */
350213449892Sdrh       sqlite3VdbeResolveLabel(v, addrInitializeLoop);
350366a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset);
350413449892Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy);
35055360ad34Sdrh       if( pWInfo==0 ) goto select_end;
350613449892Sdrh       if( pGroupBy==0 ){
350713449892Sdrh         /* The optimizer is able to deliver rows in group by order so
3508b9bb7c18Sdrh         ** we do not have to sort.  The OP_OpenEphemeral table will be
350913449892Sdrh         ** cancelled later because we still need to use the pKeyInfo
351013449892Sdrh         */
351113449892Sdrh         pGroupBy = p->pGroupBy;
351213449892Sdrh         groupBySort = 0;
351313449892Sdrh       }else{
351413449892Sdrh         /* Rows are coming out in undetermined order.  We have to push
351513449892Sdrh         ** each row into a sorting index, terminate the first loop,
351613449892Sdrh         ** then loop over the sorting index in order to get the output
351713449892Sdrh         ** in sorted order
351813449892Sdrh         */
351913449892Sdrh         groupBySort = 1;
3520389a1adbSdrh         sqlite3ExprCodeExprList(pParse, pGroupBy, 0);
352166a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx, 0);
352213449892Sdrh         j = pGroupBy->nExpr+1;
352313449892Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
352413449892Sdrh           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
352513449892Sdrh           if( pCol->iSorterColumn<j ) continue;
35262133d822Sdrh           sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn,pCol->iTable,0);
352713449892Sdrh           j++;
352813449892Sdrh         }
352966a5167bSdrh         sqlite3VdbeAddOp2(v, OP_MakeRecord, j, 0);
353066a5167bSdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, 0);
353113449892Sdrh         sqlite3WhereEnd(pWInfo);
353266a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
3533d4e70ebdSdrh         VdbeComment((v, "GROUP BY sort"));
353413449892Sdrh         sAggInfo.useSortingIdx = 1;
353513449892Sdrh       }
353613449892Sdrh 
353713449892Sdrh       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
353813449892Sdrh       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
353913449892Sdrh       ** Then compare the current GROUP BY terms against the GROUP BY terms
354013449892Sdrh       ** from the previous row currently stored in a0, a1, a2...
354113449892Sdrh       */
354213449892Sdrh       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
354313449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
354413449892Sdrh         if( groupBySort ){
354566a5167bSdrh           sqlite3VdbeAddOp2(v, OP_Column, sAggInfo.sortingIdx, j);
354613449892Sdrh         }else{
354713449892Sdrh           sAggInfo.directMode = 1;
3548389a1adbSdrh           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, 0);
354913449892Sdrh         }
3550*b1fdb2adSdrh         sqlite3VdbeAddOp2(v, j<pGroupBy->nExpr-1?OP_Move:OP_Copy, 0, iBMem+j);
355113449892Sdrh       }
355213449892Sdrh       for(j=pGroupBy->nExpr-1; j>=0; j--){
355313449892Sdrh         if( j<pGroupBy->nExpr-1 ){
3554*b1fdb2adSdrh           sqlite3VdbeAddOp2(v, OP_SCopy, iBMem+j, 0);
355513449892Sdrh         }
3556*b1fdb2adSdrh         sqlite3VdbeAddOp2(v, OP_SCopy, iAMem+j, 0);
355713449892Sdrh         if( j==0 ){
355866a5167bSdrh           sqlite3VdbeAddOp2(v, OP_Eq, 0x200, addrProcessRow);
355913449892Sdrh         }else{
356066a5167bSdrh           sqlite3VdbeAddOp2(v, OP_Ne, 0x200, addrGroupByChange);
356113449892Sdrh         }
356266a5167bSdrh         sqlite3VdbeChangeP4(v, -1, (void*)pKeyInfo->aColl[j], P4_COLLSEQ);
356313449892Sdrh       }
356413449892Sdrh 
356513449892Sdrh       /* Generate code that runs whenever the GROUP BY changes.
356613449892Sdrh       ** Change in the GROUP BY are detected by the previous code
356713449892Sdrh       ** block.  If there were no changes, this block is skipped.
356813449892Sdrh       **
356913449892Sdrh       ** This code copies current group by terms in b0,b1,b2,...
357013449892Sdrh       ** over to a0,a1,a2.  It then calls the output subroutine
357113449892Sdrh       ** and resets the aggregate accumulator registers in preparation
357213449892Sdrh       ** for the next GROUP BY batch.
357313449892Sdrh       */
357413449892Sdrh       sqlite3VdbeResolveLabel(v, addrGroupByChange);
357513449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
3576*b1fdb2adSdrh         sqlite3VdbeAddOp2(v, OP_Move, iBMem+j, iAMem+j);
357713449892Sdrh       }
357866a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrOutputRow);
3579d4e70ebdSdrh       VdbeComment((v, "output one row"));
358066a5167bSdrh       sqlite3VdbeAddOp2(v, OP_IfMemPos, iAbortFlag, addrEnd);
3581d4e70ebdSdrh       VdbeComment((v, "check abort flag"));
358266a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset);
3583d4e70ebdSdrh       VdbeComment((v, "reset accumulator"));
358413449892Sdrh 
358513449892Sdrh       /* Update the aggregate accumulators based on the content of
358613449892Sdrh       ** the current row
358713449892Sdrh       */
358813449892Sdrh       sqlite3VdbeResolveLabel(v, addrProcessRow);
358913449892Sdrh       updateAccumulator(pParse, &sAggInfo);
35904c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
3591d4e70ebdSdrh       VdbeComment((v, "indicate data in accumulator"));
359213449892Sdrh 
359313449892Sdrh       /* End of the loop
359413449892Sdrh       */
359513449892Sdrh       if( groupBySort ){
359666a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
359713449892Sdrh       }else{
359813449892Sdrh         sqlite3WhereEnd(pWInfo);
3599f8875400Sdrh         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
360013449892Sdrh       }
360113449892Sdrh 
360213449892Sdrh       /* Output the final row of result
360313449892Sdrh       */
360466a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrOutputRow);
3605d4e70ebdSdrh       VdbeComment((v, "output final row"));
360613449892Sdrh 
360713449892Sdrh     } /* endif pGroupBy */
360813449892Sdrh     else {
360913449892Sdrh       /* This case runs if the aggregate has no GROUP BY clause.  The
361013449892Sdrh       ** processing is much simpler since there is only a single row
361113449892Sdrh       ** of output.
361213449892Sdrh       */
361313449892Sdrh       resetAccumulator(pParse, &sAggInfo);
361413449892Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
36155360ad34Sdrh       if( pWInfo==0 ) goto select_end;
361613449892Sdrh       updateAccumulator(pParse, &sAggInfo);
361713449892Sdrh       sqlite3WhereEnd(pWInfo);
361813449892Sdrh       finalizeAggFunctions(pParse, &sAggInfo);
361913449892Sdrh       pOrderBy = 0;
36205774b806Sdrh       if( pHaving ){
36215774b806Sdrh         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1);
36225774b806Sdrh       }
362313449892Sdrh       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
36246c8c8ce0Sdanielk1977                       pDest, addrEnd, addrEnd, aff);
362513449892Sdrh     }
362613449892Sdrh     sqlite3VdbeResolveLabel(v, addrEnd);
362713449892Sdrh 
362813449892Sdrh   } /* endif aggregate query */
36292282792aSdrh 
3630cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
3631cce7d176Sdrh   ** and send them to the callback one by one.
3632cce7d176Sdrh   */
3633cce7d176Sdrh   if( pOrderBy ){
36346c8c8ce0Sdanielk1977     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
3635cce7d176Sdrh   }
36366a535340Sdrh 
363793758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
3638f620b4e2Sdrh   /* If this was a subquery, we have now converted the subquery into a
36391787ccabSdanielk1977   ** temporary table.  So set the SrcList_item.isPopulated flag to prevent
36401787ccabSdanielk1977   ** this subquery from being evaluated again and to force the use of
36411787ccabSdanielk1977   ** the temporary table.
3642f620b4e2Sdrh   */
3643f620b4e2Sdrh   if( pParent ){
3644f620b4e2Sdrh     assert( pParent->pSrc->nSrc>parentTab );
3645f620b4e2Sdrh     assert( pParent->pSrc->a[parentTab].pSelect==p );
36461787ccabSdanielk1977     pParent->pSrc->a[parentTab].isPopulated = 1;
3647f620b4e2Sdrh   }
364893758c8dSdanielk1977 #endif
3649f620b4e2Sdrh 
3650ec7429aeSdrh   /* Jump here to skip this query
3651ec7429aeSdrh   */
3652ec7429aeSdrh   sqlite3VdbeResolveLabel(v, iEnd);
3653ec7429aeSdrh 
36541d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
36551d83f052Sdrh   ** to indicate no errors.
36561d83f052Sdrh   */
36571d83f052Sdrh   rc = 0;
36581d83f052Sdrh 
36591d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
36601d83f052Sdrh   ** successful coding of the SELECT.
36611d83f052Sdrh   */
36621d83f052Sdrh select_end:
3663955de52cSdanielk1977 
3664955de52cSdanielk1977   /* Identify column names if we will be using them in a callback.  This
3665955de52cSdanielk1977   ** step is skipped if the output is going to some other destination.
3666955de52cSdanielk1977   */
36676c8c8ce0Sdanielk1977   if( rc==SQLITE_OK && pDest->eDest==SRT_Callback ){
3668955de52cSdanielk1977     generateColumnNames(pParse, pTabList, pEList);
3669955de52cSdanielk1977   }
3670955de52cSdanielk1977 
367117435752Sdrh   sqlite3_free(sAggInfo.aCol);
367217435752Sdrh   sqlite3_free(sAggInfo.aFunc);
36731d83f052Sdrh   return rc;
3674cce7d176Sdrh }
3675485f0039Sdrh 
367677a2a5e7Sdrh #if defined(SQLITE_DEBUG)
3677485f0039Sdrh /*
3678485f0039Sdrh *******************************************************************************
3679485f0039Sdrh ** The following code is used for testing and debugging only.  The code
3680485f0039Sdrh ** that follows does not appear in normal builds.
3681485f0039Sdrh **
3682485f0039Sdrh ** These routines are used to print out the content of all or part of a
3683485f0039Sdrh ** parse structures such as Select or Expr.  Such printouts are useful
3684485f0039Sdrh ** for helping to understand what is happening inside the code generator
3685485f0039Sdrh ** during the execution of complex SELECT statements.
3686485f0039Sdrh **
3687485f0039Sdrh ** These routine are not called anywhere from within the normal
3688485f0039Sdrh ** code base.  Then are intended to be called from within the debugger
3689485f0039Sdrh ** or from temporary "printf" statements inserted for debugging.
3690485f0039Sdrh */
3691485f0039Sdrh void sqlite3PrintExpr(Expr *p){
3692485f0039Sdrh   if( p->token.z && p->token.n>0 ){
3693485f0039Sdrh     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
3694485f0039Sdrh   }else{
3695485f0039Sdrh     sqlite3DebugPrintf("(%d", p->op);
3696485f0039Sdrh   }
3697485f0039Sdrh   if( p->pLeft ){
3698485f0039Sdrh     sqlite3DebugPrintf(" ");
3699485f0039Sdrh     sqlite3PrintExpr(p->pLeft);
3700485f0039Sdrh   }
3701485f0039Sdrh   if( p->pRight ){
3702485f0039Sdrh     sqlite3DebugPrintf(" ");
3703485f0039Sdrh     sqlite3PrintExpr(p->pRight);
3704485f0039Sdrh   }
3705485f0039Sdrh   sqlite3DebugPrintf(")");
3706485f0039Sdrh }
3707485f0039Sdrh void sqlite3PrintExprList(ExprList *pList){
3708485f0039Sdrh   int i;
3709485f0039Sdrh   for(i=0; i<pList->nExpr; i++){
3710485f0039Sdrh     sqlite3PrintExpr(pList->a[i].pExpr);
3711485f0039Sdrh     if( i<pList->nExpr-1 ){
3712485f0039Sdrh       sqlite3DebugPrintf(", ");
3713485f0039Sdrh     }
3714485f0039Sdrh   }
3715485f0039Sdrh }
3716485f0039Sdrh void sqlite3PrintSelect(Select *p, int indent){
3717485f0039Sdrh   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
3718485f0039Sdrh   sqlite3PrintExprList(p->pEList);
3719485f0039Sdrh   sqlite3DebugPrintf("\n");
3720485f0039Sdrh   if( p->pSrc ){
3721485f0039Sdrh     char *zPrefix;
3722485f0039Sdrh     int i;
3723485f0039Sdrh     zPrefix = "FROM";
3724485f0039Sdrh     for(i=0; i<p->pSrc->nSrc; i++){
3725485f0039Sdrh       struct SrcList_item *pItem = &p->pSrc->a[i];
3726485f0039Sdrh       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
3727485f0039Sdrh       zPrefix = "";
3728485f0039Sdrh       if( pItem->pSelect ){
3729485f0039Sdrh         sqlite3DebugPrintf("(\n");
3730485f0039Sdrh         sqlite3PrintSelect(pItem->pSelect, indent+10);
3731485f0039Sdrh         sqlite3DebugPrintf("%*s)", indent+8, "");
3732485f0039Sdrh       }else if( pItem->zName ){
3733485f0039Sdrh         sqlite3DebugPrintf("%s", pItem->zName);
3734485f0039Sdrh       }
3735485f0039Sdrh       if( pItem->pTab ){
3736485f0039Sdrh         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
3737485f0039Sdrh       }
3738485f0039Sdrh       if( pItem->zAlias ){
3739485f0039Sdrh         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
3740485f0039Sdrh       }
3741485f0039Sdrh       if( i<p->pSrc->nSrc-1 ){
3742485f0039Sdrh         sqlite3DebugPrintf(",");
3743485f0039Sdrh       }
3744485f0039Sdrh       sqlite3DebugPrintf("\n");
3745485f0039Sdrh     }
3746485f0039Sdrh   }
3747485f0039Sdrh   if( p->pWhere ){
3748485f0039Sdrh     sqlite3DebugPrintf("%*s WHERE ", indent, "");
3749485f0039Sdrh     sqlite3PrintExpr(p->pWhere);
3750485f0039Sdrh     sqlite3DebugPrintf("\n");
3751485f0039Sdrh   }
3752485f0039Sdrh   if( p->pGroupBy ){
3753485f0039Sdrh     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
3754485f0039Sdrh     sqlite3PrintExprList(p->pGroupBy);
3755485f0039Sdrh     sqlite3DebugPrintf("\n");
3756485f0039Sdrh   }
3757485f0039Sdrh   if( p->pHaving ){
3758485f0039Sdrh     sqlite3DebugPrintf("%*s HAVING ", indent, "");
3759485f0039Sdrh     sqlite3PrintExpr(p->pHaving);
3760485f0039Sdrh     sqlite3DebugPrintf("\n");
3761485f0039Sdrh   }
3762485f0039Sdrh   if( p->pOrderBy ){
3763485f0039Sdrh     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
3764485f0039Sdrh     sqlite3PrintExprList(p->pOrderBy);
3765485f0039Sdrh     sqlite3DebugPrintf("\n");
3766485f0039Sdrh   }
3767485f0039Sdrh }
3768485f0039Sdrh /* End of the structure debug printing code
3769485f0039Sdrh *****************************************************************************/
3770485f0039Sdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
3771