xref: /sqlite-3.40.0/src/select.c (revision 8f0ecaae)
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*8f0ecaaeSdrh ** $Id: select.c,v 1.372 2007/12/14 17:24:40 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;
390c182d163Sdrh   sqlite3ExprCodeExprList(pParse, pOrderBy);
3919d2985c7Sdrh   sqlite3VdbeAddOp(v, OP_Sequence, pOrderBy->iECursor, 0);
3924db38a70Sdrh   sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr + 1, 0);
3934db38a70Sdrh   sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0);
3949d2985c7Sdrh   sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iECursor, 0);
395d59ba6ceSdrh   if( pSelect->iLimit>=0 ){
39615007a99Sdrh     int addr1, addr2;
39715007a99Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_IfMemZero, pSelect->iLimit+1, 0);
39815007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemIncr, -1, pSelect->iLimit+1);
39915007a99Sdrh     addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
400d59ba6ceSdrh     sqlite3VdbeJumpHere(v, addr1);
401d59ba6ceSdrh     sqlite3VdbeAddOp(v, OP_Last, pOrderBy->iECursor, 0);
402d59ba6ceSdrh     sqlite3VdbeAddOp(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;
41915007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iOffset);
4203a129247Sdrh     addr = sqlite3VdbeAddOp(v, OP_IfMemNeg, p->iOffset, 0);
421ea48eb2eSdrh     if( nPop>0 ){
422ea48eb2eSdrh       sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
423ea48eb2eSdrh     }
424ea48eb2eSdrh     sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
425ad6d9460Sdrh     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 */
439c99130fdSdrh static void codeDistinct(
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 ){
445c99130fdSdrh   sqlite3VdbeAddOp(v, OP_MakeRecord, -N, 0);
446c99130fdSdrh   sqlite3VdbeAddOp(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3);
447f8875400Sdrh   sqlite3VdbeAddOp(v, OP_Pop, N+1, 0);
448c99130fdSdrh   sqlite3VdbeAddOp(v, OP_Goto, 0, addrRepeat);
449c99130fdSdrh   VdbeComment((v, "# skip indistinct records"));
450c99130fdSdrh   sqlite3VdbeAddOp(v, OP_IdxInsert, iTab, 0);
451c99130fdSdrh }
452c99130fdSdrh 
453e305f43fSdrh /*
454e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression
455e305f43fSdrh ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
456e305f43fSdrh ** column.  We do this in a subroutine because the error occurs in multiple
457e305f43fSdrh ** places.
458e305f43fSdrh */
459e305f43fSdrh static int checkForMultiColumnSelectError(Parse *pParse, int eDest, int nExpr){
460e305f43fSdrh   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
461e305f43fSdrh     sqlite3ErrorMsg(pParse, "only a single result allowed for "
462e305f43fSdrh        "a SELECT that is part of an expression");
463e305f43fSdrh     return 1;
464e305f43fSdrh   }else{
465e305f43fSdrh     return 0;
466e305f43fSdrh   }
467e305f43fSdrh }
468c99130fdSdrh 
469c99130fdSdrh /*
4702282792aSdrh ** This routine generates the code for the inside of the inner loop
4712282792aSdrh ** of a SELECT.
47282c3d636Sdrh **
47338640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
47438640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
47538640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
47638640e15Sdrh ** datatypes for each column.
4772282792aSdrh */
4782282792aSdrh static int selectInnerLoop(
4792282792aSdrh   Parse *pParse,          /* The parser context */
480df199a25Sdrh   Select *p,              /* The complete select statement being coded */
4812282792aSdrh   ExprList *pEList,       /* List of values being extracted */
48282c3d636Sdrh   int srcTab,             /* Pull data from this table */
483967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
4842282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
4852282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
4862282792aSdrh   int eDest,              /* How to dispose of the results */
4872282792aSdrh   int iParm,              /* An argument to the disposal method */
4882282792aSdrh   int iContinue,          /* Jump here to continue with next row */
48984ac9d02Sdanielk1977   int iBreak,             /* Jump here to break out of the inner loop */
49084ac9d02Sdanielk1977   char *aff               /* affinity string if eDest is SRT_Union */
4912282792aSdrh ){
4922282792aSdrh   Vdbe *v = pParse->pVdbe;
4932282792aSdrh   int i;
494ea48eb2eSdrh   int hasDistinct;        /* True if the DISTINCT keyword is present */
49538640e15Sdrh 
496daffd0e5Sdrh   if( v==0 ) return 0;
49738640e15Sdrh   assert( pEList!=0 );
4982282792aSdrh 
499df199a25Sdrh   /* If there was a LIMIT clause on the SELECT statement, then do the check
500df199a25Sdrh   ** to see if this row should be output.
501df199a25Sdrh   */
502eda639e1Sdrh   hasDistinct = distinct>=0 && pEList->nExpr>0;
503ea48eb2eSdrh   if( pOrderBy==0 && !hasDistinct ){
504ec7429aeSdrh     codeOffset(v, p, iContinue, 0);
505df199a25Sdrh   }
506df199a25Sdrh 
507967e8b73Sdrh   /* Pull the requested columns.
5082282792aSdrh   */
50938640e15Sdrh   if( nColumn>0 ){
510967e8b73Sdrh     for(i=0; i<nColumn; i++){
5114adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
51282c3d636Sdrh     }
51338640e15Sdrh   }else{
51438640e15Sdrh     nColumn = pEList->nExpr;
515c182d163Sdrh     sqlite3ExprCodeExprList(pParse, pEList);
51682c3d636Sdrh   }
5172282792aSdrh 
518daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
519daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
520daffd0e5Sdrh   ** part of the result.
5212282792aSdrh   */
522ea48eb2eSdrh   if( hasDistinct ){
523f8875400Sdrh     assert( pEList!=0 );
524f8875400Sdrh     assert( pEList->nExpr==nColumn );
525f8875400Sdrh     codeDistinct(v, distinct, iContinue, nColumn);
526ea48eb2eSdrh     if( pOrderBy==0 ){
527ec7429aeSdrh       codeOffset(v, p, iContinue, nColumn);
528ea48eb2eSdrh     }
5292282792aSdrh   }
53082c3d636Sdrh 
531e305f43fSdrh   if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){
532e305f43fSdrh     return 0;
533e305f43fSdrh   }
534e305f43fSdrh 
535c926afbcSdrh   switch( eDest ){
53682c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
53782c3d636Sdrh     ** table iParm.
5382282792aSdrh     */
53913449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
540c926afbcSdrh     case SRT_Union: {
541f8875400Sdrh       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
54213449892Sdrh       if( aff ){
54384ac9d02Sdanielk1977         sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
54413449892Sdrh       }
545f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0);
546c926afbcSdrh       break;
547c926afbcSdrh     }
54882c3d636Sdrh 
54982c3d636Sdrh     /* Construct a record from the query result, but instead of
55082c3d636Sdrh     ** saving that record, use it as a key to delete elements from
55182c3d636Sdrh     ** the temporary table iParm.
55282c3d636Sdrh     */
553c926afbcSdrh     case SRT_Except: {
5540bd1f4eaSdrh       int addr;
555f8875400Sdrh       addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
55684ac9d02Sdanielk1977       sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
5574adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
5584adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
559c926afbcSdrh       break;
560c926afbcSdrh     }
5615338a5f7Sdanielk1977 #endif
5625338a5f7Sdanielk1977 
5635338a5f7Sdanielk1977     /* Store the result as data using a unique key.
5645338a5f7Sdanielk1977     */
5655338a5f7Sdanielk1977     case SRT_Table:
566b9bb7c18Sdrh     case SRT_EphemTab: {
5675338a5f7Sdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
5685338a5f7Sdanielk1977       if( pOrderBy ){
569d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
5705338a5f7Sdanielk1977       }else{
571f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
5725338a5f7Sdanielk1977         sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
573e4d90813Sdrh         sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
5745338a5f7Sdanielk1977       }
5755338a5f7Sdanielk1977       break;
5765338a5f7Sdanielk1977     }
5772282792aSdrh 
57893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
5792282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
5802282792aSdrh     ** then there should be a single item on the stack.  Write this
5812282792aSdrh     ** item into the set table with bogus data.
5822282792aSdrh     */
583c926afbcSdrh     case SRT_Set: {
5844adee20fSdanielk1977       int addr1 = sqlite3VdbeCurrentAddr(v);
58552b36cabSdrh       int addr2;
586e014a838Sdanielk1977 
587967e8b73Sdrh       assert( nColumn==1 );
5884adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
5894adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
5904adee20fSdanielk1977       addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
5916c1426fdSdrh       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr,(iParm>>16)&0xff);
592c926afbcSdrh       if( pOrderBy ){
593de941c60Sdrh         /* At first glance you would think we could optimize out the
594de941c60Sdrh         ** ORDER BY in this case since the order of entries in the set
595de941c60Sdrh         ** does not matter.  But there might be a LIMIT clause, in which
596de941c60Sdrh         ** case the order does matter */
597d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
598c926afbcSdrh       }else{
5996c1426fdSdrh         sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
600f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
601c926afbcSdrh       }
602d654be80Sdrh       sqlite3VdbeJumpHere(v, addr2);
603c926afbcSdrh       break;
604c926afbcSdrh     }
60582c3d636Sdrh 
606504b6989Sdrh     /* If any row exist in the result set, record that fact and abort.
607ec7429aeSdrh     */
608ec7429aeSdrh     case SRT_Exists: {
609ec7429aeSdrh       sqlite3VdbeAddOp(v, OP_MemInt, 1, iParm);
610ec7429aeSdrh       sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
611ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
612ec7429aeSdrh       break;
613ec7429aeSdrh     }
614ec7429aeSdrh 
6152282792aSdrh     /* If this is a scalar select that is part of an expression, then
6162282792aSdrh     ** store the results in the appropriate memory cell and break out
6172282792aSdrh     ** of the scan loop.
6182282792aSdrh     */
619c926afbcSdrh     case SRT_Mem: {
620967e8b73Sdrh       assert( nColumn==1 );
621c926afbcSdrh       if( pOrderBy ){
622d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
623c926afbcSdrh       }else{
6244adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
625ec7429aeSdrh         /* The LIMIT clause will jump out of the loop for us */
626c926afbcSdrh       }
627c926afbcSdrh       break;
628c926afbcSdrh     }
62993758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
6302282792aSdrh 
631c182d163Sdrh     /* Send the data to the callback function or to a subroutine.  In the
632c182d163Sdrh     ** case of a subroutine, the subroutine itself is responsible for
633c182d163Sdrh     ** popping the data from the stack.
634f46f905aSdrh     */
635c182d163Sdrh     case SRT_Subroutine:
6369d2985c7Sdrh     case SRT_Callback: {
637f46f905aSdrh       if( pOrderBy ){
638ce665cf6Sdrh         sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
639d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
640c182d163Sdrh       }else if( eDest==SRT_Subroutine ){
6414adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
642c182d163Sdrh       }else{
643c182d163Sdrh         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
644ac82fcf5Sdrh       }
645142e30dfSdrh       break;
646142e30dfSdrh     }
647142e30dfSdrh 
6486a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER)
649d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
650d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
651d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
652d7489c39Sdrh     ** about the actual results of the select.
653d7489c39Sdrh     */
654c926afbcSdrh     default: {
655f46f905aSdrh       assert( eDest==SRT_Discard );
6564adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
657c926afbcSdrh       break;
658c926afbcSdrh     }
65993758c8dSdanielk1977 #endif
660c926afbcSdrh   }
661ec7429aeSdrh 
662ec7429aeSdrh   /* Jump to the end of the loop if the LIMIT is reached.
663ec7429aeSdrh   */
664ec7429aeSdrh   if( p->iLimit>=0 && pOrderBy==0 ){
66515007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
666ec7429aeSdrh     sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, iBreak);
667ec7429aeSdrh   }
66882c3d636Sdrh   return 0;
66982c3d636Sdrh }
67082c3d636Sdrh 
67182c3d636Sdrh /*
672dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records
673dece1a84Sdrh ** the collating sequence for each expression in that expression list.
674dece1a84Sdrh **
6750342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
6760342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to
6770342b1f5Sdrh ** implement that clause.  If the ExprList is the result set of a SELECT
6780342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual
6790342b1f5Sdrh ** index to implement a DISTINCT test.
6800342b1f5Sdrh **
681dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
682dece1a84Sdrh ** function is responsible for seeing that this structure is eventually
683dece1a84Sdrh ** freed.  Add the KeyInfo structure to the P3 field of an opcode using
684dece1a84Sdrh ** P3_KEYINFO_HANDOFF is the usual way of dealing with this.
685dece1a84Sdrh */
686dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
687dece1a84Sdrh   sqlite3 *db = pParse->db;
688dece1a84Sdrh   int nExpr;
689dece1a84Sdrh   KeyInfo *pInfo;
690dece1a84Sdrh   struct ExprList_item *pItem;
691dece1a84Sdrh   int i;
692dece1a84Sdrh 
693dece1a84Sdrh   nExpr = pList->nExpr;
69417435752Sdrh   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
695dece1a84Sdrh   if( pInfo ){
6962646da7eSdrh     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
697dece1a84Sdrh     pInfo->nField = nExpr;
69814db2665Sdanielk1977     pInfo->enc = ENC(db);
699dece1a84Sdrh     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
700dece1a84Sdrh       CollSeq *pColl;
701dece1a84Sdrh       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
702dece1a84Sdrh       if( !pColl ){
703dece1a84Sdrh         pColl = db->pDfltColl;
704dece1a84Sdrh       }
705dece1a84Sdrh       pInfo->aColl[i] = pColl;
706dece1a84Sdrh       pInfo->aSortOrder[i] = pItem->sortOrder;
707dece1a84Sdrh     }
708dece1a84Sdrh   }
709dece1a84Sdrh   return pInfo;
710dece1a84Sdrh }
711dece1a84Sdrh 
712dece1a84Sdrh 
713dece1a84Sdrh /*
714d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
715d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
716d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
717d8bc7086Sdrh ** routine generates the code needed to do that.
718d8bc7086Sdrh */
719c926afbcSdrh static void generateSortTail(
720cdd536f0Sdrh   Parse *pParse,   /* Parsing context */
721c926afbcSdrh   Select *p,       /* The SELECT statement */
722c926afbcSdrh   Vdbe *v,         /* Generate code into this VDBE */
723c926afbcSdrh   int nColumn,     /* Number of columns of data */
724c926afbcSdrh   int eDest,       /* Write the sorted results here */
725c926afbcSdrh   int iParm        /* Optional parameter associated with eDest */
726c926afbcSdrh ){
7270342b1f5Sdrh   int brk = sqlite3VdbeMakeLabel(v);
7280342b1f5Sdrh   int cont = sqlite3VdbeMakeLabel(v);
729d8bc7086Sdrh   int addr;
7300342b1f5Sdrh   int iTab;
73161fc595fSdrh   int pseudoTab = 0;
7320342b1f5Sdrh   ExprList *pOrderBy = p->pOrderBy;
733ffbc3088Sdrh 
7349d2985c7Sdrh   iTab = pOrderBy->iECursor;
735cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
736cdd536f0Sdrh     pseudoTab = pParse->nTab++;
737cdd536f0Sdrh     sqlite3VdbeAddOp(v, OP_OpenPseudo, pseudoTab, 0);
738cdd536f0Sdrh     sqlite3VdbeAddOp(v, OP_SetNumColumns, pseudoTab, nColumn);
739cdd536f0Sdrh   }
7400342b1f5Sdrh   addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk);
741ec7429aeSdrh   codeOffset(v, p, cont, 0);
742cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
743cdd536f0Sdrh     sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
744cdd536f0Sdrh   }
7454db38a70Sdrh   sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1);
746c926afbcSdrh   switch( eDest ){
747c926afbcSdrh     case SRT_Table:
748b9bb7c18Sdrh     case SRT_EphemTab: {
749f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
7504adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
751e4d90813Sdrh       sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
752c926afbcSdrh       break;
753c926afbcSdrh     }
75493758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
755c926afbcSdrh     case SRT_Set: {
756c926afbcSdrh       assert( nColumn==1 );
7574adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
7584adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
7594adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
7606c1426fdSdrh       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
761f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
762c926afbcSdrh       break;
763c926afbcSdrh     }
764c926afbcSdrh     case SRT_Mem: {
765c926afbcSdrh       assert( nColumn==1 );
7664adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
767ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
768c926afbcSdrh       break;
769c926afbcSdrh     }
77093758c8dSdanielk1977 #endif
771ce665cf6Sdrh     case SRT_Callback:
772ac82fcf5Sdrh     case SRT_Subroutine: {
773ac82fcf5Sdrh       int i;
774cdd536f0Sdrh       sqlite3VdbeAddOp(v, OP_Insert, pseudoTab, 0);
775ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
776cdd536f0Sdrh         sqlite3VdbeAddOp(v, OP_Column, pseudoTab, i);
777ac82fcf5Sdrh       }
778ce665cf6Sdrh       if( eDest==SRT_Callback ){
779ce665cf6Sdrh         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
780ce665cf6Sdrh       }else{
7814adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
782ce665cf6Sdrh       }
783ac82fcf5Sdrh       break;
784ac82fcf5Sdrh     }
785c926afbcSdrh     default: {
786f46f905aSdrh       /* Do nothing */
787c926afbcSdrh       break;
788c926afbcSdrh     }
789c926afbcSdrh   }
790ec7429aeSdrh 
791ec7429aeSdrh   /* Jump to the end of the loop when the LIMIT is reached
792ec7429aeSdrh   */
793ec7429aeSdrh   if( p->iLimit>=0 ){
79415007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
795ec7429aeSdrh     sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, brk);
796ec7429aeSdrh   }
797ec7429aeSdrh 
798ec7429aeSdrh   /* The bottom of the loop
799ec7429aeSdrh   */
8000342b1f5Sdrh   sqlite3VdbeResolveLabel(v, cont);
8010342b1f5Sdrh   sqlite3VdbeAddOp(v, OP_Next, iTab, addr);
8020342b1f5Sdrh   sqlite3VdbeResolveLabel(v, brk);
803cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
804cdd536f0Sdrh     sqlite3VdbeAddOp(v, OP_Close, pseudoTab, 0);
805cdd536f0Sdrh   }
806cdd536f0Sdrh 
807d8bc7086Sdrh }
808d8bc7086Sdrh 
809d8bc7086Sdrh /*
810517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
811517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
812e78e8284Sdrh **
813955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the
814955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The
815955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
816955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The
817955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is
818955de52cSdanielk1977 ** considered a column by this function.
819e78e8284Sdrh **
820955de52cSdanielk1977 **   SELECT col FROM tbl;
821955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl;
822955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl);
823955de52cSdanielk1977 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
824955de52cSdanielk1977 **
825955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL.
826fcb78a49Sdrh */
827955de52cSdanielk1977 static const char *columnType(
828955de52cSdanielk1977   NameContext *pNC,
829955de52cSdanielk1977   Expr *pExpr,
830955de52cSdanielk1977   const char **pzOriginDb,
831955de52cSdanielk1977   const char **pzOriginTab,
832955de52cSdanielk1977   const char **pzOriginCol
833955de52cSdanielk1977 ){
834955de52cSdanielk1977   char const *zType = 0;
835955de52cSdanielk1977   char const *zOriginDb = 0;
836955de52cSdanielk1977   char const *zOriginTab = 0;
837955de52cSdanielk1977   char const *zOriginCol = 0;
838517eb646Sdanielk1977   int j;
839b3bce662Sdanielk1977   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
8405338a5f7Sdanielk1977 
84100e279d9Sdanielk1977   switch( pExpr->op ){
84230bcf5dbSdrh     case TK_AGG_COLUMN:
84300e279d9Sdanielk1977     case TK_COLUMN: {
844955de52cSdanielk1977       /* The expression is a column. Locate the table the column is being
845955de52cSdanielk1977       ** extracted from in NameContext.pSrcList. This table may be real
846955de52cSdanielk1977       ** database table or a subquery.
847955de52cSdanielk1977       */
848955de52cSdanielk1977       Table *pTab = 0;            /* Table structure column is extracted from */
849955de52cSdanielk1977       Select *pS = 0;             /* Select the column is extracted from */
850955de52cSdanielk1977       int iCol = pExpr->iColumn;  /* Index of column in pTab */
851b3bce662Sdanielk1977       while( pNC && !pTab ){
852b3bce662Sdanielk1977         SrcList *pTabList = pNC->pSrcList;
853b3bce662Sdanielk1977         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
854b3bce662Sdanielk1977         if( j<pTabList->nSrc ){
8556a3ea0e6Sdrh           pTab = pTabList->a[j].pTab;
856955de52cSdanielk1977           pS = pTabList->a[j].pSelect;
857b3bce662Sdanielk1977         }else{
858b3bce662Sdanielk1977           pNC = pNC->pNext;
859b3bce662Sdanielk1977         }
860b3bce662Sdanielk1977       }
861955de52cSdanielk1977 
8627e62779aSdrh       if( pTab==0 ){
8637e62779aSdrh         /* FIX ME:
8647e62779aSdrh         ** This can occurs if you have something like "SELECT new.x;" inside
8657e62779aSdrh         ** a trigger.  In other words, if you reference the special "new"
8667e62779aSdrh         ** table in the result set of a select.  We do not have a good way
8677e62779aSdrh         ** to find the actual table type, so call it "TEXT".  This is really
8687e62779aSdrh         ** something of a bug, but I do not know how to fix it.
8697e62779aSdrh         **
8707e62779aSdrh         ** This code does not produce the correct answer - it just prevents
8717e62779aSdrh         ** a segfault.  See ticket #1229.
8727e62779aSdrh         */
8737e62779aSdrh         zType = "TEXT";
8747e62779aSdrh         break;
8757e62779aSdrh       }
876955de52cSdanielk1977 
877b3bce662Sdanielk1977       assert( pTab );
878955de52cSdanielk1977       if( pS ){
879955de52cSdanielk1977         /* The "table" is actually a sub-select or a view in the FROM clause
880955de52cSdanielk1977         ** of the SELECT statement. Return the declaration type and origin
881955de52cSdanielk1977         ** data for the result-set column of the sub-select.
882955de52cSdanielk1977         */
883955de52cSdanielk1977         if( iCol>=0 && iCol<pS->pEList->nExpr ){
884955de52cSdanielk1977           /* If iCol is less than zero, then the expression requests the
885955de52cSdanielk1977           ** rowid of the sub-select or view. This expression is legal (see
886955de52cSdanielk1977           ** test case misc2.2.2) - it always evaluates to NULL.
887955de52cSdanielk1977           */
888955de52cSdanielk1977           NameContext sNC;
889955de52cSdanielk1977           Expr *p = pS->pEList->a[iCol].pExpr;
890955de52cSdanielk1977           sNC.pSrcList = pS->pSrc;
891955de52cSdanielk1977           sNC.pNext = 0;
892955de52cSdanielk1977           sNC.pParse = pNC->pParse;
893955de52cSdanielk1977           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
894955de52cSdanielk1977         }
8954b2688abSdanielk1977       }else if( pTab->pSchema ){
896955de52cSdanielk1977         /* A real table */
897955de52cSdanielk1977         assert( !pS );
898fcb78a49Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
899fcb78a49Sdrh         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
900fcb78a49Sdrh         if( iCol<0 ){
901fcb78a49Sdrh           zType = "INTEGER";
902955de52cSdanielk1977           zOriginCol = "rowid";
903fcb78a49Sdrh         }else{
904fcb78a49Sdrh           zType = pTab->aCol[iCol].zType;
905955de52cSdanielk1977           zOriginCol = pTab->aCol[iCol].zName;
906955de52cSdanielk1977         }
907955de52cSdanielk1977         zOriginTab = pTab->zName;
908955de52cSdanielk1977         if( pNC->pParse ){
909955de52cSdanielk1977           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
910955de52cSdanielk1977           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
911955de52cSdanielk1977         }
912fcb78a49Sdrh       }
91300e279d9Sdanielk1977       break;
914736c22b8Sdrh     }
91593758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
91600e279d9Sdanielk1977     case TK_SELECT: {
917955de52cSdanielk1977       /* The expression is a sub-select. Return the declaration type and
918955de52cSdanielk1977       ** origin info for the single column in the result set of the SELECT
919955de52cSdanielk1977       ** statement.
920955de52cSdanielk1977       */
921b3bce662Sdanielk1977       NameContext sNC;
92200e279d9Sdanielk1977       Select *pS = pExpr->pSelect;
923955de52cSdanielk1977       Expr *p = pS->pEList->a[0].pExpr;
924955de52cSdanielk1977       sNC.pSrcList = pS->pSrc;
925b3bce662Sdanielk1977       sNC.pNext = pNC;
926955de52cSdanielk1977       sNC.pParse = pNC->pParse;
927955de52cSdanielk1977       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
92800e279d9Sdanielk1977       break;
929fcb78a49Sdrh     }
93093758c8dSdanielk1977 #endif
93100e279d9Sdanielk1977   }
93200e279d9Sdanielk1977 
933955de52cSdanielk1977   if( pzOriginDb ){
934955de52cSdanielk1977     assert( pzOriginTab && pzOriginCol );
935955de52cSdanielk1977     *pzOriginDb = zOriginDb;
936955de52cSdanielk1977     *pzOriginTab = zOriginTab;
937955de52cSdanielk1977     *pzOriginCol = zOriginCol;
938955de52cSdanielk1977   }
939517eb646Sdanielk1977   return zType;
940517eb646Sdanielk1977 }
941517eb646Sdanielk1977 
942517eb646Sdanielk1977 /*
943517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
944517eb646Sdanielk1977 ** in the result set.
945517eb646Sdanielk1977 */
946517eb646Sdanielk1977 static void generateColumnTypes(
947517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
948517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
949517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
950517eb646Sdanielk1977 ){
951517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
952517eb646Sdanielk1977   int i;
953b3bce662Sdanielk1977   NameContext sNC;
954b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
955955de52cSdanielk1977   sNC.pParse = pParse;
956517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
957517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
958955de52cSdanielk1977     const char *zOrigDb = 0;
959955de52cSdanielk1977     const char *zOrigTab = 0;
960955de52cSdanielk1977     const char *zOrigCol = 0;
961955de52cSdanielk1977     const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
962955de52cSdanielk1977 
96385b623f2Sdrh     /* The vdbe must make its own copy of the column-type and other
9644b1ae99dSdanielk1977     ** column specific strings, in case the schema is reset before this
9654b1ae99dSdanielk1977     ** virtual machine is deleted.
966fbcd585fSdanielk1977     */
9674b1ae99dSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P3_TRANSIENT);
9684b1ae99dSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P3_TRANSIENT);
9694b1ae99dSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P3_TRANSIENT);
9704b1ae99dSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P3_TRANSIENT);
971fcb78a49Sdrh   }
972fcb78a49Sdrh }
973fcb78a49Sdrh 
974fcb78a49Sdrh /*
975fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
976fcb78a49Sdrh ** in the result set.  This information is used to provide the
977fcabd464Sdrh ** azCol[] values in the callback.
97882c3d636Sdrh */
979832508b7Sdrh static void generateColumnNames(
980832508b7Sdrh   Parse *pParse,      /* Parser context */
981ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
982832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
983832508b7Sdrh ){
984d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
9856a3ea0e6Sdrh   int i, j;
9869bb575fdSdrh   sqlite3 *db = pParse->db;
987fcabd464Sdrh   int fullNames, shortNames;
988fcabd464Sdrh 
989fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN
9903cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
9913cf86063Sdanielk1977   if( pParse->explain ){
99261de0d1bSdanielk1977     return;
9933cf86063Sdanielk1977   }
9945338a5f7Sdanielk1977 #endif
9953cf86063Sdanielk1977 
996d6502758Sdrh   assert( v!=0 );
99717435752Sdrh   if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
998d8bc7086Sdrh   pParse->colNamesSet = 1;
999fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
1000fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
100122322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
100282c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
100382c3d636Sdrh     Expr *p;
10045a38705eSdrh     p = pEList->a[i].pExpr;
10055a38705eSdrh     if( p==0 ) continue;
100682c3d636Sdrh     if( pEList->a[i].zName ){
100782c3d636Sdrh       char *zName = pEList->a[i].zName;
1008955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
100982c3d636Sdrh       continue;
101082c3d636Sdrh     }
1011fa173a76Sdrh     if( p->op==TK_COLUMN && pTabList ){
10126a3ea0e6Sdrh       Table *pTab;
101397665873Sdrh       char *zCol;
10148aff1015Sdrh       int iCol = p->iColumn;
10156a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
10166a3ea0e6Sdrh       assert( j<pTabList->nSrc );
10176a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
10188aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
101997665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1020b1363206Sdrh       if( iCol<0 ){
102147a6db2bSdrh         zCol = "rowid";
1022b1363206Sdrh       }else{
1023b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
1024b1363206Sdrh       }
1025fcabd464Sdrh       if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
1026955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
1027fcabd464Sdrh       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
102882c3d636Sdrh         char *zName = 0;
102982c3d636Sdrh         char *zTab;
103082c3d636Sdrh 
10316a3ea0e6Sdrh         zTab = pTabList->a[j].zAlias;
1032fcabd464Sdrh         if( fullNames || zTab==0 ) zTab = pTab->zName;
1033f93339deSdrh         sqlite3SetString(&zName, zTab, ".", zCol, (char*)0);
1034955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P3_DYNAMIC);
103582c3d636Sdrh       }else{
1036955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
103782c3d636Sdrh       }
10386977fea8Sdrh     }else if( p->span.z && p->span.z[0] ){
1039955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
10403cf86063Sdanielk1977       /* sqlite3VdbeCompressSpace(v, addr); */
10411bee3d7bSdrh     }else{
10421bee3d7bSdrh       char zName[30];
10431bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
10445bb3eb9bSdrh       sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1);
1045955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0);
104682c3d636Sdrh     }
104782c3d636Sdrh   }
104876d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
10495080aaa7Sdrh }
105082c3d636Sdrh 
105193758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
105282c3d636Sdrh /*
1053d8bc7086Sdrh ** Name of the connection operator, used for error messages.
1054d8bc7086Sdrh */
1055d8bc7086Sdrh static const char *selectOpName(int id){
1056d8bc7086Sdrh   char *z;
1057d8bc7086Sdrh   switch( id ){
1058d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
1059d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
1060d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
1061d8bc7086Sdrh     default:           z = "UNION";       break;
1062d8bc7086Sdrh   }
1063d8bc7086Sdrh   return z;
1064d8bc7086Sdrh }
106593758c8dSdanielk1977 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1066d8bc7086Sdrh 
1067d8bc7086Sdrh /*
1068315555caSdrh ** Forward declaration
1069315555caSdrh */
10709b3187e1Sdrh static int prepSelectStmt(Parse*, Select*);
1071315555caSdrh 
1072315555caSdrh /*
107322f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
107422f70c32Sdrh ** the result set of that SELECT.
107522f70c32Sdrh */
10764adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
107722f70c32Sdrh   Table *pTab;
1078b733d037Sdrh   int i, j;
107922f70c32Sdrh   ExprList *pEList;
1080290c1948Sdrh   Column *aCol, *pCol;
108117435752Sdrh   sqlite3 *db = pParse->db;
108222f70c32Sdrh 
108392378253Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
10849b3187e1Sdrh   if( prepSelectStmt(pParse, pSelect) ){
108522f70c32Sdrh     return 0;
108622f70c32Sdrh   }
1087142bdf40Sdanielk1977   if( sqlite3SelectResolve(pParse, pSelect, 0) ){
1088142bdf40Sdanielk1977     return 0;
1089142bdf40Sdanielk1977   }
109017435752Sdrh   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
109122f70c32Sdrh   if( pTab==0 ){
109222f70c32Sdrh     return 0;
109322f70c32Sdrh   }
1094ed8a3bb1Sdrh   pTab->nRef = 1;
109517435752Sdrh   pTab->zName = zTabName ? sqlite3DbStrDup(db, zTabName) : 0;
109622f70c32Sdrh   pEList = pSelect->pEList;
109722f70c32Sdrh   pTab->nCol = pEList->nExpr;
1098417be79cSdrh   assert( pTab->nCol>0 );
109917435752Sdrh   pTab->aCol = aCol = sqlite3DbMallocZero(db, sizeof(pTab->aCol[0])*pTab->nCol);
1100290c1948Sdrh   for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
110179d5f63fSdrh     Expr *p, *pR;
1102517eb646Sdanielk1977     char *zType;
110391bb0eedSdrh     char *zName;
11042564ef97Sdrh     int nName;
1105b3bf556eSdanielk1977     CollSeq *pColl;
110679d5f63fSdrh     int cnt;
1107b3bce662Sdanielk1977     NameContext sNC;
110879d5f63fSdrh 
110979d5f63fSdrh     /* Get an appropriate name for the column
111079d5f63fSdrh     */
111179d5f63fSdrh     p = pEList->a[i].pExpr;
1112290c1948Sdrh     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
111391bb0eedSdrh     if( (zName = pEList->a[i].zName)!=0 ){
111479d5f63fSdrh       /* If the column contains an "AS <name>" phrase, use <name> as the name */
111517435752Sdrh       zName = sqlite3DbStrDup(db, zName);
1116517eb646Sdanielk1977     }else if( p->op==TK_DOT
1117b733d037Sdrh               && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
111879d5f63fSdrh       /* For columns of the from A.B use B as the name */
111917435752Sdrh       zName = sqlite3MPrintf(db, "%T", &pR->token);
1120b733d037Sdrh     }else if( p->span.z && p->span.z[0] ){
112179d5f63fSdrh       /* Use the original text of the column expression as its name */
112217435752Sdrh       zName = sqlite3MPrintf(db, "%T", &p->span);
112322f70c32Sdrh     }else{
112479d5f63fSdrh       /* If all else fails, make up a name */
112517435752Sdrh       zName = sqlite3MPrintf(db, "column%d", i+1);
112622f70c32Sdrh     }
11277751940dSdanielk1977     if( !zName || db->mallocFailed ){
11287751940dSdanielk1977       db->mallocFailed = 1;
112917435752Sdrh       sqlite3_free(zName);
1130a04a34ffSdanielk1977       sqlite3DeleteTable(pTab);
1131dd5b2fa5Sdrh       return 0;
1132dd5b2fa5Sdrh     }
11337751940dSdanielk1977     sqlite3Dequote(zName);
113479d5f63fSdrh 
113579d5f63fSdrh     /* Make sure the column name is unique.  If the name is not unique,
113679d5f63fSdrh     ** append a integer to the name so that it becomes unique.
113779d5f63fSdrh     */
11382564ef97Sdrh     nName = strlen(zName);
113979d5f63fSdrh     for(j=cnt=0; j<i; j++){
114079d5f63fSdrh       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
11412564ef97Sdrh         zName[nName] = 0;
11421e536953Sdanielk1977         zName = sqlite3MPrintf(db, "%z:%d", zName, ++cnt);
114379d5f63fSdrh         j = -1;
1144dd5b2fa5Sdrh         if( zName==0 ) break;
114579d5f63fSdrh       }
114679d5f63fSdrh     }
114791bb0eedSdrh     pCol->zName = zName;
1148e014a838Sdanielk1977 
114979d5f63fSdrh     /* Get the typename, type affinity, and collating sequence for the
115079d5f63fSdrh     ** column.
115179d5f63fSdrh     */
1152c43e8be8Sdrh     memset(&sNC, 0, sizeof(sNC));
1153b3bce662Sdanielk1977     sNC.pSrcList = pSelect->pSrc;
115417435752Sdrh     zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
1155290c1948Sdrh     pCol->zType = zType;
1156c60e9b82Sdanielk1977     pCol->affinity = sqlite3ExprAffinity(p);
1157b3bf556eSdanielk1977     pColl = sqlite3ExprCollSeq(pParse, p);
1158b3bf556eSdanielk1977     if( pColl ){
115917435752Sdrh       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
11600202b29eSdanielk1977     }
116122f70c32Sdrh   }
116222f70c32Sdrh   pTab->iPKey = -1;
116322f70c32Sdrh   return pTab;
116422f70c32Sdrh }
116522f70c32Sdrh 
116622f70c32Sdrh /*
11679b3187e1Sdrh ** Prepare a SELECT statement for processing by doing the following
11689b3187e1Sdrh ** things:
1169d8bc7086Sdrh **
11709b3187e1Sdrh **    (1)  Make sure VDBE cursor numbers have been assigned to every
11719b3187e1Sdrh **         element of the FROM clause.
11729b3187e1Sdrh **
11739b3187e1Sdrh **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
11749b3187e1Sdrh **         defines FROM clause.  When views appear in the FROM clause,
117563eb5f29Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
117663eb5f29Sdrh **         that implements the view.  A copy is made of the view's SELECT
117763eb5f29Sdrh **         statement so that we can freely modify or delete that statement
117863eb5f29Sdrh **         without worrying about messing up the presistent representation
117963eb5f29Sdrh **         of the view.
1180d8bc7086Sdrh **
11819b3187e1Sdrh **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
1182ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
1183ad2d8307Sdrh **
11849b3187e1Sdrh **    (4)  Scan the list of columns in the result set (pEList) looking
118554473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
118654473229Sdrh **         If found, expand each "*" to be every column in every table
118754473229Sdrh **         and TABLE.* to be every column in TABLE.
1188d8bc7086Sdrh **
1189d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
1190d8bc7086Sdrh ** in pParse and return non-zero.
1191d8bc7086Sdrh */
11929b3187e1Sdrh static int prepSelectStmt(Parse *pParse, Select *p){
119354473229Sdrh   int i, j, k, rc;
1194ad3cab52Sdrh   SrcList *pTabList;
1195daffd0e5Sdrh   ExprList *pEList;
1196290c1948Sdrh   struct SrcList_item *pFrom;
119717435752Sdrh   sqlite3 *db = pParse->db;
1198daffd0e5Sdrh 
119917435752Sdrh   if( p==0 || p->pSrc==0 || db->mallocFailed ){
12006f7adc8aSdrh     return 1;
12016f7adc8aSdrh   }
1202daffd0e5Sdrh   pTabList = p->pSrc;
1203daffd0e5Sdrh   pEList = p->pEList;
1204d8bc7086Sdrh 
12059b3187e1Sdrh   /* Make sure cursor numbers have been assigned to all entries in
12069b3187e1Sdrh   ** the FROM clause of the SELECT statement.
12079b3187e1Sdrh   */
12089b3187e1Sdrh   sqlite3SrcListAssignCursors(pParse, p->pSrc);
12099b3187e1Sdrh 
12109b3187e1Sdrh   /* Look up every table named in the FROM clause of the select.  If
12119b3187e1Sdrh   ** an entry of the FROM clause is a subquery instead of a table or view,
12129b3187e1Sdrh   ** then create a transient table structure to describe the subquery.
1213d8bc7086Sdrh   */
1214290c1948Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1215f0113000Sdanielk1977     Table *pTab;
12169b3187e1Sdrh     if( pFrom->pTab!=0 ){
12179b3187e1Sdrh       /* This statement has already been prepared.  There is no need
12189b3187e1Sdrh       ** to go further. */
12199b3187e1Sdrh       assert( i==0 );
1220d8bc7086Sdrh       return 0;
1221d8bc7086Sdrh     }
1222290c1948Sdrh     if( pFrom->zName==0 ){
122393758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
122422f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
1225290c1948Sdrh       assert( pFrom->pSelect!=0 );
1226290c1948Sdrh       if( pFrom->zAlias==0 ){
122791bb0eedSdrh         pFrom->zAlias =
12281e536953Sdanielk1977           sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pFrom->pSelect);
1229ad2d8307Sdrh       }
1230ed8a3bb1Sdrh       assert( pFrom->pTab==0 );
1231290c1948Sdrh       pFrom->pTab = pTab =
1232290c1948Sdrh         sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
123322f70c32Sdrh       if( pTab==0 ){
1234daffd0e5Sdrh         return 1;
1235daffd0e5Sdrh       }
1236b9bb7c18Sdrh       /* The isEphem flag indicates that the Table structure has been
12375cf590c1Sdrh       ** dynamically allocated and may be freed at any time.  In other words,
12385cf590c1Sdrh       ** pTab is not pointing to a persistent table structure that defines
12395cf590c1Sdrh       ** part of the schema. */
1240b9bb7c18Sdrh       pTab->isEphem = 1;
124193758c8dSdanielk1977 #endif
124222f70c32Sdrh     }else{
1243a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
1244ed8a3bb1Sdrh       assert( pFrom->pTab==0 );
1245290c1948Sdrh       pFrom->pTab = pTab =
1246290c1948Sdrh         sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
1247a76b5dfcSdrh       if( pTab==0 ){
1248d8bc7086Sdrh         return 1;
1249d8bc7086Sdrh       }
1250ed8a3bb1Sdrh       pTab->nRef++;
125193626f48Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
125293626f48Sdanielk1977       if( pTab->pSelect || IsVirtual(pTab) ){
125363eb5f29Sdrh         /* We reach here if the named table is a really a view */
12544adee20fSdanielk1977         if( sqlite3ViewGetColumnNames(pParse, pTab) ){
1255417be79cSdrh           return 1;
1256417be79cSdrh         }
1257290c1948Sdrh         /* If pFrom->pSelect!=0 it means we are dealing with a
125863eb5f29Sdrh         ** view within a view.  The SELECT structure has already been
125963eb5f29Sdrh         ** copied by the outer view so we can skip the copy step here
126063eb5f29Sdrh         ** in the inner view.
126163eb5f29Sdrh         */
1262290c1948Sdrh         if( pFrom->pSelect==0 ){
126317435752Sdrh           pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
1264a76b5dfcSdrh         }
1265d8bc7086Sdrh       }
126693758c8dSdanielk1977 #endif
126722f70c32Sdrh     }
126863eb5f29Sdrh   }
1269d8bc7086Sdrh 
1270ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
1271ad2d8307Sdrh   */
1272ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
1273ad2d8307Sdrh 
12747c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
127554473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
127654473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
12777c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
12787c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
12797c917d19Sdrh   ** each one to the list of all columns in all tables.
128054473229Sdrh   **
128154473229Sdrh   ** The first loop just checks to see if there are any "*" operators
128254473229Sdrh   ** that need expanding.
1283d8bc7086Sdrh   */
12847c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
128554473229Sdrh     Expr *pE = pEList->a[k].pExpr;
128654473229Sdrh     if( pE->op==TK_ALL ) break;
128754473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
128854473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
12897c917d19Sdrh   }
129054473229Sdrh   rc = 0;
12917c917d19Sdrh   if( k<pEList->nExpr ){
129254473229Sdrh     /*
129354473229Sdrh     ** If we get here it means the result set contains one or more "*"
129454473229Sdrh     ** operators that need to be expanded.  Loop through each expression
129554473229Sdrh     ** in the result set and expand them one by one.
129654473229Sdrh     */
12977c917d19Sdrh     struct ExprList_item *a = pEList->a;
12987c917d19Sdrh     ExprList *pNew = 0;
1299d70dc52dSdrh     int flags = pParse->db->flags;
1300d70dc52dSdrh     int longNames = (flags & SQLITE_FullColNames)!=0 &&
1301d70dc52dSdrh                       (flags & SQLITE_ShortColNames)==0;
1302d70dc52dSdrh 
13037c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
130454473229Sdrh       Expr *pE = a[k].pExpr;
130554473229Sdrh       if( pE->op!=TK_ALL &&
130654473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
130754473229Sdrh         /* This particular expression does not need to be expanded.
130854473229Sdrh         */
130917435752Sdrh         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
1310261919ccSdanielk1977         if( pNew ){
13117c917d19Sdrh           pNew->a[pNew->nExpr-1].zName = a[k].zName;
1312261919ccSdanielk1977         }else{
1313261919ccSdanielk1977           rc = 1;
1314261919ccSdanielk1977         }
13157c917d19Sdrh         a[k].pExpr = 0;
13167c917d19Sdrh         a[k].zName = 0;
13177c917d19Sdrh       }else{
131854473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
131954473229Sdrh         ** expanded. */
132054473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
1321cf55b7aeSdrh         char *zTName;            /* text of name of TABLE */
132254473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
132317435752Sdrh           zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
132454473229Sdrh         }else{
1325cf55b7aeSdrh           zTName = 0;
132654473229Sdrh         }
1327290c1948Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1328290c1948Sdrh           Table *pTab = pFrom->pTab;
1329290c1948Sdrh           char *zTabName = pFrom->zAlias;
133054473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
133154473229Sdrh             zTabName = pTab->zName;
133254473229Sdrh           }
1333cf55b7aeSdrh           if( zTName && (zTabName==0 || zTabName[0]==0 ||
1334cf55b7aeSdrh                  sqlite3StrICmp(zTName, zTabName)!=0) ){
133554473229Sdrh             continue;
133654473229Sdrh           }
133754473229Sdrh           tableSeen = 1;
1338d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
1339f0113000Sdanielk1977             Expr *pExpr, *pRight;
1340ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
1341ad2d8307Sdrh 
1342034ca14fSdanielk1977             /* If a column is marked as 'hidden' (currently only possible
1343034ca14fSdanielk1977             ** for virtual tables), do not include it in the expanded
1344034ca14fSdanielk1977             ** result-set list.
1345034ca14fSdanielk1977             */
1346034ca14fSdanielk1977             if( IsHiddenColumn(&pTab->aCol[j]) ){
1347034ca14fSdanielk1977               assert(IsVirtual(pTab));
1348034ca14fSdanielk1977               continue;
1349034ca14fSdanielk1977             }
1350034ca14fSdanielk1977 
135191bb0eedSdrh             if( i>0 ){
135291bb0eedSdrh               struct SrcList_item *pLeft = &pTabList->a[i-1];
135361dfc31dSdrh               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
135491bb0eedSdrh                         columnIndex(pLeft->pTab, zName)>=0 ){
1355ad2d8307Sdrh                 /* In a NATURAL join, omit the join columns from the
1356ad2d8307Sdrh                 ** table on the right */
1357ad2d8307Sdrh                 continue;
1358ad2d8307Sdrh               }
135961dfc31dSdrh               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
1360ad2d8307Sdrh                 /* In a join with a USING clause, omit columns in the
1361ad2d8307Sdrh                 ** using clause from the table on the right. */
1362ad2d8307Sdrh                 continue;
1363ad2d8307Sdrh               }
136491bb0eedSdrh             }
1365a1644fd8Sdanielk1977             pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
136622f70c32Sdrh             if( pRight==0 ) break;
13671e536953Sdanielk1977             setQuotedToken(pParse, &pRight->token, zName);
1368d70dc52dSdrh             if( zTabName && (longNames || pTabList->nSrc>1) ){
1369a1644fd8Sdanielk1977               Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
1370a1644fd8Sdanielk1977               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
137122f70c32Sdrh               if( pExpr==0 ) break;
13721e536953Sdanielk1977               setQuotedToken(pParse, &pLeft->token, zTabName);
13731e536953Sdanielk1977               setToken(&pExpr->span,
13741e536953Sdanielk1977                   sqlite3MPrintf(db, "%s.%s", zTabName, zName));
13756977fea8Sdrh               pExpr->span.dyn = 1;
13766977fea8Sdrh               pExpr->token.z = 0;
13776977fea8Sdrh               pExpr->token.n = 0;
13786977fea8Sdrh               pExpr->token.dyn = 0;
137922f70c32Sdrh             }else{
138022f70c32Sdrh               pExpr = pRight;
13816977fea8Sdrh               pExpr->span = pExpr->token;
1382f3b863edSdanielk1977               pExpr->span.dyn = 0;
138322f70c32Sdrh             }
1384d70dc52dSdrh             if( longNames ){
138517435752Sdrh               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
1386d70dc52dSdrh             }else{
138717435752Sdrh               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
1388d8bc7086Sdrh             }
1389d8bc7086Sdrh           }
1390d70dc52dSdrh         }
139154473229Sdrh         if( !tableSeen ){
1392cf55b7aeSdrh           if( zTName ){
1393cf55b7aeSdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
1394f5db2d3eSdrh           }else{
13954adee20fSdanielk1977             sqlite3ErrorMsg(pParse, "no tables specified");
1396f5db2d3eSdrh           }
139754473229Sdrh           rc = 1;
139854473229Sdrh         }
139917435752Sdrh         sqlite3_free(zTName);
14007c917d19Sdrh       }
14017c917d19Sdrh     }
14024adee20fSdanielk1977     sqlite3ExprListDelete(pEList);
14037c917d19Sdrh     p->pEList = pNew;
1404d8bc7086Sdrh   }
1405e5c941b8Sdrh   if( p->pEList && p->pEList->nExpr>SQLITE_MAX_COLUMN ){
1406e5c941b8Sdrh     sqlite3ErrorMsg(pParse, "too many columns in result set");
1407e5c941b8Sdrh     rc = SQLITE_ERROR;
1408e5c941b8Sdrh   }
140917435752Sdrh   if( db->mallocFailed ){
1410f3b863edSdanielk1977     rc = SQLITE_NOMEM;
1411f3b863edSdanielk1977   }
141254473229Sdrh   return rc;
1413d8bc7086Sdrh }
1414d8bc7086Sdrh 
1415ff78bd2fSdrh /*
14169a99334dSdrh ** pE is a pointer to an expression which is a single term in
14179a99334dSdrh ** ORDER BY or GROUP BY clause.
1418d8bc7086Sdrh **
14199a99334dSdrh ** If pE evaluates to an integer constant i, then return i.
14209a99334dSdrh ** This is an indication to the caller that it should sort
14219a99334dSdrh ** by the i-th column of the result set.
14229a99334dSdrh **
14239a99334dSdrh ** If pE is a well-formed expression and the SELECT statement
14249a99334dSdrh ** is not compound, then return 0.  This indicates to the
14259a99334dSdrh ** caller that it should sort by the value of the ORDER BY
14269a99334dSdrh ** expression.
14279a99334dSdrh **
14289a99334dSdrh ** If the SELECT is compound, then attempt to match pE against
14299a99334dSdrh ** result set columns in the left-most SELECT statement.  Return
14309a99334dSdrh ** the index i of the matching column, as an indication to the
14319a99334dSdrh ** caller that it should sort by the i-th column.  If there is
14329a99334dSdrh ** no match, return -1 and leave an error message in pParse.
1433d8bc7086Sdrh */
14349a99334dSdrh static int matchOrderByTermToExprList(
14359a99334dSdrh   Parse *pParse,     /* Parsing context for error messages */
14369a99334dSdrh   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
14379a99334dSdrh   Expr *pE,          /* The specific ORDER BY term */
14389a99334dSdrh   int idx,           /* When ORDER BY term is this */
14399a99334dSdrh   int isCompound,    /* True if this is a compound SELECT */
14409a99334dSdrh   u8 *pHasAgg        /* True if expression contains aggregate functions */
1441d8bc7086Sdrh ){
14429a99334dSdrh   int i;             /* Loop counter */
14439a99334dSdrh   ExprList *pEList;  /* The columns of the result set */
14449a99334dSdrh   NameContext nc;    /* Name context for resolving pE */
14459a99334dSdrh 
14469a99334dSdrh 
14479a99334dSdrh   /* If the term is an integer constant, return the value of that
14489a99334dSdrh   ** constant */
14499a99334dSdrh   pEList = pSelect->pEList;
14509a99334dSdrh   if( sqlite3ExprIsInteger(pE, &i) ){
14519a99334dSdrh     if( i<=0 ){
14529a99334dSdrh       /* If i is too small, make it too big.  That way the calling
14539a99334dSdrh       ** function still sees a value that is out of range, but does
14549a99334dSdrh       ** not confuse the column number with 0 or -1 result code.
14559a99334dSdrh       */
14569a99334dSdrh       i = pEList->nExpr+1;
14579a99334dSdrh     }
14589a99334dSdrh     return i;
14599a99334dSdrh   }
14609a99334dSdrh 
14619a99334dSdrh   /* If the term is a simple identifier that try to match that identifier
14629a99334dSdrh   ** against a column name in the result set.
14639a99334dSdrh   */
14649a99334dSdrh   if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){
146517435752Sdrh     sqlite3 *db = pParse->db;
14669a99334dSdrh     char *zCol = sqlite3NameFromToken(db, &pE->token);
1467ef0bea92Sdrh     if( zCol==0 ){
14689a99334dSdrh       return -1;
14699a99334dSdrh     }
14709a99334dSdrh     for(i=0; i<pEList->nExpr; i++){
14719a99334dSdrh       char *zAs = pEList->a[i].zName;
14729a99334dSdrh       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
14739a99334dSdrh         sqlite3_free(zCol);
14749a99334dSdrh         return i+1;
14759a99334dSdrh       }
14769a99334dSdrh     }
14779a99334dSdrh     sqlite3_free(zCol);
14784c774314Sdrh   }
147970517ab9Sdanielk1977 
14809a99334dSdrh   /* Resolve all names in the ORDER BY term expression
14819a99334dSdrh   */
148270517ab9Sdanielk1977   memset(&nc, 0, sizeof(nc));
148370517ab9Sdanielk1977   nc.pParse = pParse;
14849a99334dSdrh   nc.pSrcList = pSelect->pSrc;
148570517ab9Sdanielk1977   nc.pEList = pEList;
148670517ab9Sdanielk1977   nc.allowAgg = 1;
14874c774314Sdrh   nc.nErr = 0;
14889a99334dSdrh   if( sqlite3ExprResolveNames(&nc, pE) ){
14891e281291Sdrh     if( isCompound ){
14901e281291Sdrh       sqlite3ErrorClear(pParse);
14911e281291Sdrh       return 0;
14921e281291Sdrh     }else{
14939a99334dSdrh       return -1;
14949a99334dSdrh     }
14951e281291Sdrh   }
14969a99334dSdrh   if( nc.hasAgg && pHasAgg ){
14979a99334dSdrh     *pHasAgg = 1;
14989a99334dSdrh   }
14999a99334dSdrh 
15009a99334dSdrh   /* For a compound SELECT, we need to try to match the ORDER BY
15019a99334dSdrh   ** expression against an expression in the result set
15029a99334dSdrh   */
15039a99334dSdrh   if( isCompound ){
15049a99334dSdrh     for(i=0; i<pEList->nExpr; i++){
15059a99334dSdrh       if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
15069a99334dSdrh         return i+1;
15079a99334dSdrh       }
15089a99334dSdrh     }
15094c774314Sdrh   }
15101e281291Sdrh   return 0;
151170517ab9Sdanielk1977 }
151270517ab9Sdanielk1977 
15139a99334dSdrh 
15149a99334dSdrh /*
15159a99334dSdrh ** Analyze and ORDER BY or GROUP BY clause in a simple SELECT statement.
15169a99334dSdrh ** Return the number of errors seen.
15179a99334dSdrh **
15189a99334dSdrh ** Every term of the ORDER BY or GROUP BY clause needs to be an
15199a99334dSdrh ** expression.  If any expression is an integer constant, then
15209a99334dSdrh ** that expression is replaced by the corresponding
15219a99334dSdrh ** expression from the result set.
15229a99334dSdrh */
15239a99334dSdrh static int processOrderGroupBy(
15249a99334dSdrh   Parse *pParse,        /* Parsing context.  Leave error messages here */
15259a99334dSdrh   Select *pSelect,      /* The SELECT statement containing the clause */
15269a99334dSdrh   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
15279a99334dSdrh   int isOrder,          /* 1 for ORDER BY.  0 for GROUP BY */
15289a99334dSdrh   u8 *pHasAgg           /* Set to TRUE if any term contains an aggregate */
15299a99334dSdrh ){
15309a99334dSdrh   int i;
15319a99334dSdrh   sqlite3 *db = pParse->db;
15329a99334dSdrh   ExprList *pEList;
15339a99334dSdrh 
15349a99334dSdrh   if( pOrderBy==0 ) return 0;
15359a99334dSdrh   if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){
15369a99334dSdrh     const char *zType = isOrder ? "ORDER" : "GROUP";
15379a99334dSdrh     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
15389a99334dSdrh     return 1;
15399a99334dSdrh   }
15409a99334dSdrh   pEList = pSelect->pEList;
15419a99334dSdrh   if( pEList==0 ){
15429a99334dSdrh     return 0;
15439a99334dSdrh   }
15449a99334dSdrh   for(i=0; i<pOrderBy->nExpr; i++){
15459a99334dSdrh     int iCol;
15469a99334dSdrh     Expr *pE = pOrderBy->a[i].pExpr;
15479a99334dSdrh     iCol = matchOrderByTermToExprList(pParse, pSelect, pE, i+1, 0, pHasAgg);
154870517ab9Sdanielk1977     if( iCol<0 ){
15499a99334dSdrh       return 1;
15509a99334dSdrh     }
15519a99334dSdrh     if( iCol>pEList->nExpr ){
15529a99334dSdrh       const char *zType = isOrder ? "ORDER" : "GROUP";
155370517ab9Sdanielk1977       sqlite3ErrorMsg(pParse,
15549a99334dSdrh          "%r %s BY term out of range - should be "
15559a99334dSdrh          "between 1 and %d", i+1, zType, pEList->nExpr);
15569a99334dSdrh       return 1;
15579a99334dSdrh     }
15589a99334dSdrh     if( iCol>0 ){
15599a99334dSdrh       CollSeq *pColl = pE->pColl;
15609a99334dSdrh       int flags = pE->flags & EP_ExpCollate;
15619a99334dSdrh       sqlite3ExprDelete(pE);
15629a99334dSdrh       pE = sqlite3ExprDup(db, pEList->a[iCol-1].pExpr);
15639a99334dSdrh       pOrderBy->a[i].pExpr = pE;
15649a99334dSdrh       if( pColl && flags ){
15659a99334dSdrh         pE->pColl = pColl;
15669a99334dSdrh         pE->flags |= flags;
15679a99334dSdrh       }
15689a99334dSdrh     }
15699a99334dSdrh   }
15709a99334dSdrh   return 0;
15719a99334dSdrh }
15729a99334dSdrh 
15739a99334dSdrh /*
15749a99334dSdrh ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement.  Return
15759a99334dSdrh ** the number of errors seen.
15769a99334dSdrh **
15779a99334dSdrh ** The processing depends on whether the SELECT is simple or compound.
15789a99334dSdrh ** For a simple SELECT statement, evry term of the ORDER BY or GROUP BY
15799a99334dSdrh ** clause needs to be an expression.  If any expression is an integer
15809a99334dSdrh ** constant, then that expression is replaced by the corresponding
15819a99334dSdrh ** expression from the result set.
15829a99334dSdrh **
15839a99334dSdrh ** For compound SELECT statements, every expression needs to be of
15849a99334dSdrh ** type TK_COLUMN with a iTable value as given in the 4th parameter.
15859a99334dSdrh ** If any expression is an integer, that becomes the column number.
15869a99334dSdrh ** Otherwise, match the expression against result set columns from
15879a99334dSdrh ** the left-most SELECT.
15889a99334dSdrh */
15899a99334dSdrh static int processCompoundOrderBy(
15909a99334dSdrh   Parse *pParse,        /* Parsing context.  Leave error messages here */
15919a99334dSdrh   Select *pSelect,      /* The SELECT statement containing the ORDER BY */
15929a99334dSdrh   int iTable            /* Output table for compound SELECT statements */
15939a99334dSdrh ){
15949a99334dSdrh   int i;
15959a99334dSdrh   ExprList *pOrderBy;
15969a99334dSdrh   ExprList *pEList;
15971e281291Sdrh   sqlite3 *db;
15981e281291Sdrh   int moreToDo = 1;
15999a99334dSdrh 
16009a99334dSdrh   pOrderBy = pSelect->pOrderBy;
16019a99334dSdrh   if( pOrderBy==0 ) return 0;
16029a99334dSdrh   if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){
16039a99334dSdrh     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
16049a99334dSdrh     return 1;
16059a99334dSdrh   }
16061e281291Sdrh   db = pParse->db;
16071e281291Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
16081e281291Sdrh     pOrderBy->a[i].done = 0;
16091e281291Sdrh   }
16109a99334dSdrh   while( pSelect->pPrior ){
16119a99334dSdrh     pSelect = pSelect->pPrior;
16129a99334dSdrh   }
16131e281291Sdrh   while( pSelect && moreToDo ){
16141e281291Sdrh     moreToDo = 0;
16159a99334dSdrh     for(i=0; i<pOrderBy->nExpr; i++){
16169a99334dSdrh       int iCol;
1617*8f0ecaaeSdrh       Expr *pE, *pDup;
16181e281291Sdrh       if( pOrderBy->a[i].done ) continue;
16191e281291Sdrh       pE = pOrderBy->a[i].pExpr;
1620*8f0ecaaeSdrh       pDup = sqlite3ExprDup(db, pE);
16211e281291Sdrh       if( pDup==0 ){
16221e281291Sdrh         return 1;
16231e281291Sdrh       }
16241e281291Sdrh       iCol = matchOrderByTermToExprList(pParse, pSelect, pDup, i+1, 1, 0);
16251e281291Sdrh       sqlite3ExprDelete(pDup);
16269a99334dSdrh       if( iCol<0 ){
16279a99334dSdrh         return 1;
16289a99334dSdrh       }
16291e281291Sdrh       pEList = pSelect->pEList;
16301e281291Sdrh       if( pEList==0 ){
16311e281291Sdrh         return 1;
16321e281291Sdrh       }
16339a99334dSdrh       if( iCol>pEList->nExpr ){
16349a99334dSdrh         sqlite3ErrorMsg(pParse,
16359a99334dSdrh            "%r ORDER BY term out of range - should be "
16369a99334dSdrh            "between 1 and %d", i+1, pEList->nExpr);
16379a99334dSdrh         return 1;
16389a99334dSdrh       }
16391e281291Sdrh       if( iCol>0 ){
1640967e8b73Sdrh         pE->op = TK_COLUMN;
1641d8bc7086Sdrh         pE->iTable = iTable;
1642a58fdfb1Sdanielk1977         pE->iAgg = -1;
16439a99334dSdrh         pE->iColumn = iCol-1;
16449a99334dSdrh         pE->pTab = 0;
16451e281291Sdrh         pOrderBy->a[i].done = 1;
16461e281291Sdrh       }else{
16471e281291Sdrh         moreToDo = 1;
16481e281291Sdrh       }
16491e281291Sdrh     }
16501e281291Sdrh     pSelect = pSelect->pNext;
16511e281291Sdrh   }
16521e281291Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
16531e281291Sdrh     if( pOrderBy->a[i].done==0 ){
16541e281291Sdrh       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
16551e281291Sdrh             "column in the result set", i+1);
16561e281291Sdrh       return 1;
16571e281291Sdrh     }
165870517ab9Sdanielk1977   }
16599a99334dSdrh   return 0;
1660d8bc7086Sdrh }
1661d8bc7086Sdrh 
1662d8bc7086Sdrh /*
1663d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1664d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1665d8bc7086Sdrh */
16664adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1667d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1668d8bc7086Sdrh   if( v==0 ){
16694adee20fSdanielk1977     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1670d8bc7086Sdrh   }
1671d8bc7086Sdrh   return v;
1672d8bc7086Sdrh }
1673d8bc7086Sdrh 
167415007a99Sdrh 
1675d8bc7086Sdrh /*
16767b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
1677ec7429aeSdrh ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
16787b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
1679a2dc3b1aSdanielk1977 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1680a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute
1681a2dc3b1aSdanielk1977 ** the limit and offset.  If there is no limit and/or offset, then
1682a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative.
16837b58daeaSdrh **
1684d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if
1685ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset.  iLimit and
16867b58daeaSdrh ** iOffset should have been preset to appropriate default values
16877b58daeaSdrh ** (usually but not always -1) prior to calling this routine.
1688ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
16897b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
16907b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
16917b58daeaSdrh ** SELECT statements.
16927b58daeaSdrh */
1693ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
169402afc861Sdrh   Vdbe *v = 0;
169502afc861Sdrh   int iLimit = 0;
169615007a99Sdrh   int iOffset;
169715007a99Sdrh   int addr1, addr2;
169815007a99Sdrh 
16997b58daeaSdrh   /*
17007b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
17017b58daeaSdrh   ** contraversy about what the correct behavior should be.
17027b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
17037b58daeaSdrh   ** no rows.
17047b58daeaSdrh   */
1705a2dc3b1aSdanielk1977   if( p->pLimit ){
170615007a99Sdrh     p->iLimit = iLimit = pParse->nMem;
1707d59ba6ceSdrh     pParse->nMem += 2;
170815007a99Sdrh     v = sqlite3GetVdbe(pParse);
17097b58daeaSdrh     if( v==0 ) return;
1710a2dc3b1aSdanielk1977     sqlite3ExprCode(pParse, p->pLimit);
1711a2dc3b1aSdanielk1977     sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
17121e4eaeb5Sdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iLimit, 1);
1713ad6d9460Sdrh     VdbeComment((v, "# LIMIT counter"));
171415007a99Sdrh     sqlite3VdbeAddOp(v, OP_IfMemZero, iLimit, iBreak);
17151e4eaeb5Sdanielk1977     sqlite3VdbeAddOp(v, OP_MemLoad, iLimit, 0);
17167b58daeaSdrh   }
1717a2dc3b1aSdanielk1977   if( p->pOffset ){
171815007a99Sdrh     p->iOffset = iOffset = pParse->nMem++;
171915007a99Sdrh     v = sqlite3GetVdbe(pParse);
17207b58daeaSdrh     if( v==0 ) return;
1721a2dc3b1aSdanielk1977     sqlite3ExprCode(pParse, p->pOffset);
1722a2dc3b1aSdanielk1977     sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
172315007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iOffset, p->pLimit==0);
1724ad6d9460Sdrh     VdbeComment((v, "# OFFSET counter"));
172515007a99Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iOffset, 0);
172615007a99Sdrh     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
172715007a99Sdrh     sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
172815007a99Sdrh     sqlite3VdbeJumpHere(v, addr1);
1729d59ba6ceSdrh     if( p->pLimit ){
1730d59ba6ceSdrh       sqlite3VdbeAddOp(v, OP_Add, 0, 0);
1731d59ba6ceSdrh     }
17327b58daeaSdrh   }
1733d59ba6ceSdrh   if( p->pLimit ){
173415007a99Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iLimit, 0);
173515007a99Sdrh     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
173615007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemInt, -1, iLimit+1);
173715007a99Sdrh     addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
173815007a99Sdrh     sqlite3VdbeJumpHere(v, addr1);
173915007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iLimit+1, 1);
1740d59ba6ceSdrh     VdbeComment((v, "# LIMIT+OFFSET"));
174115007a99Sdrh     sqlite3VdbeJumpHere(v, addr2);
1742d59ba6ceSdrh   }
17437b58daeaSdrh }
17447b58daeaSdrh 
17457b58daeaSdrh /*
17460342b1f5Sdrh ** Allocate a virtual index to use for sorting.
1747d3d39e93Sdrh */
17484db38a70Sdrh static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
17490342b1f5Sdrh   if( pOrderBy ){
1750dc1bdc4fSdanielk1977     int addr;
17519d2985c7Sdrh     assert( pOrderBy->iECursor==0 );
17529d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
1753b9bb7c18Sdrh     addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenEphemeral,
17549d2985c7Sdrh                             pOrderBy->iECursor, pOrderBy->nExpr+1);
1755b9bb7c18Sdrh     assert( p->addrOpenEphm[2] == -1 );
1756b9bb7c18Sdrh     p->addrOpenEphm[2] = addr;
1757736c22b8Sdrh   }
1758dc1bdc4fSdanielk1977 }
1759dc1bdc4fSdanielk1977 
1760b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1761fbc4ee7bSdrh /*
1762fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
1763fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
1764fbc4ee7bSdrh ** the column has no default collating sequence.
1765fbc4ee7bSdrh **
1766fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
1767fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
1768fbc4ee7bSdrh */
1769dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1770fbc4ee7bSdrh   CollSeq *pRet;
1771dc1bdc4fSdanielk1977   if( p->pPrior ){
1772dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1773fbc4ee7bSdrh   }else{
1774fbc4ee7bSdrh     pRet = 0;
1775dc1bdc4fSdanielk1977   }
1776fbc4ee7bSdrh   if( pRet==0 ){
1777dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1778dc1bdc4fSdanielk1977   }
1779dc1bdc4fSdanielk1977   return pRet;
1780d3d39e93Sdrh }
1781b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1782d3d39e93Sdrh 
1783b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1784d3d39e93Sdrh /*
178582c3d636Sdrh ** This routine is called to process a query that is really the union
178682c3d636Sdrh ** or intersection of two or more separate queries.
1787c926afbcSdrh **
1788e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1789e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1790e78e8284Sdrh ** in which case this routine will be called recursively.
1791e78e8284Sdrh **
1792e78e8284Sdrh ** The results of the total query are to be written into a destination
1793e78e8284Sdrh ** of type eDest with parameter iParm.
1794e78e8284Sdrh **
1795e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1796e78e8284Sdrh **
1797e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1798e78e8284Sdrh **
1799e78e8284Sdrh ** This statement is parsed up as follows:
1800e78e8284Sdrh **
1801e78e8284Sdrh **     SELECT c FROM t3
1802e78e8284Sdrh **      |
1803e78e8284Sdrh **      `----->  SELECT b FROM t2
1804e78e8284Sdrh **                |
18054b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1806e78e8284Sdrh **
1807e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1808e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1809e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1810e78e8284Sdrh **
1811e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1812e78e8284Sdrh ** individual selects always group from left to right.
181382c3d636Sdrh */
181484ac9d02Sdanielk1977 static int multiSelect(
1815fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
1816fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
1817fbc4ee7bSdrh   int eDest,            /* \___  Store query results as specified */
1818fbc4ee7bSdrh   int iParm,            /* /     by these two parameters.         */
181984ac9d02Sdanielk1977   char *aff             /* If eDest is SRT_Union, the affinity string */
182084ac9d02Sdanielk1977 ){
182184ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
182210e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
182310e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
18248cdbf836Sdrh   int nCol;             /* Number of columns in the result set */
18250342b1f5Sdrh   ExprList *pOrderBy;   /* The ORDER BY clause on p */
18260342b1f5Sdrh   int aSetP2[2];        /* Set P2 value of these op to number of columns */
18270342b1f5Sdrh   int nSetP2 = 0;       /* Number of slots in aSetP2[] used */
182882c3d636Sdrh 
18297b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1830fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
183182c3d636Sdrh   */
183284ac9d02Sdanielk1977   if( p==0 || p->pPrior==0 ){
183384ac9d02Sdanielk1977     rc = 1;
183484ac9d02Sdanielk1977     goto multi_select_end;
183584ac9d02Sdanielk1977   }
1836d8bc7086Sdrh   pPrior = p->pPrior;
18370342b1f5Sdrh   assert( pPrior->pRightmost!=pPrior );
18380342b1f5Sdrh   assert( pPrior->pRightmost==p->pRightmost );
1839d8bc7086Sdrh   if( pPrior->pOrderBy ){
18404adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1841da93d238Sdrh       selectOpName(p->op));
184284ac9d02Sdanielk1977     rc = 1;
184384ac9d02Sdanielk1977     goto multi_select_end;
184482c3d636Sdrh   }
1845a2dc3b1aSdanielk1977   if( pPrior->pLimit ){
18464adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
18477b58daeaSdrh       selectOpName(p->op));
184884ac9d02Sdanielk1977     rc = 1;
184984ac9d02Sdanielk1977     goto multi_select_end;
18507b58daeaSdrh   }
185182c3d636Sdrh 
1852d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
1853d8bc7086Sdrh   */
18544adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
185584ac9d02Sdanielk1977   if( v==0 ){
185684ac9d02Sdanielk1977     rc = 1;
185784ac9d02Sdanielk1977     goto multi_select_end;
185884ac9d02Sdanielk1977   }
1859d8bc7086Sdrh 
18601cc3d75fSdrh   /* Create the destination temporary table if necessary
18611cc3d75fSdrh   */
1862b9bb7c18Sdrh   if( eDest==SRT_EphemTab ){
1863b4964b72Sdanielk1977     assert( p->pEList );
18640342b1f5Sdrh     assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1865b9bb7c18Sdrh     aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 0);
18661cc3d75fSdrh     eDest = SRT_Table;
18671cc3d75fSdrh   }
18681cc3d75fSdrh 
1869f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1870d8bc7086Sdrh   */
18710342b1f5Sdrh   pOrderBy = p->pOrderBy;
187282c3d636Sdrh   switch( p->op ){
1873f46f905aSdrh     case TK_ALL: {
18740342b1f5Sdrh       if( pOrderBy==0 ){
1875ec7429aeSdrh         int addr = 0;
1876a2dc3b1aSdanielk1977         assert( !pPrior->pLimit );
1877a2dc3b1aSdanielk1977         pPrior->pLimit = p->pLimit;
1878a2dc3b1aSdanielk1977         pPrior->pOffset = p->pOffset;
1879b3bce662Sdanielk1977         rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
1880ad68cb6bSdanielk1977         p->pLimit = 0;
1881ad68cb6bSdanielk1977         p->pOffset = 0;
188284ac9d02Sdanielk1977         if( rc ){
188384ac9d02Sdanielk1977           goto multi_select_end;
188484ac9d02Sdanielk1977         }
1885f46f905aSdrh         p->pPrior = 0;
18867b58daeaSdrh         p->iLimit = pPrior->iLimit;
18877b58daeaSdrh         p->iOffset = pPrior->iOffset;
1888ec7429aeSdrh         if( p->iLimit>=0 ){
1889ec7429aeSdrh           addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0);
1890ec7429aeSdrh           VdbeComment((v, "# Jump ahead if LIMIT reached"));
1891ec7429aeSdrh         }
1892b3bce662Sdanielk1977         rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
1893f46f905aSdrh         p->pPrior = pPrior;
189484ac9d02Sdanielk1977         if( rc ){
189584ac9d02Sdanielk1977           goto multi_select_end;
189684ac9d02Sdanielk1977         }
1897ec7429aeSdrh         if( addr ){
1898ec7429aeSdrh           sqlite3VdbeJumpHere(v, addr);
1899ec7429aeSdrh         }
1900f46f905aSdrh         break;
1901f46f905aSdrh       }
1902f46f905aSdrh       /* For UNION ALL ... ORDER BY fall through to the next case */
1903f46f905aSdrh     }
190482c3d636Sdrh     case TK_EXCEPT:
190582c3d636Sdrh     case TK_UNION: {
1906d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1907742f947bSdanielk1977       int op = 0;      /* One of the SRT_ operations to apply to self */
1908d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
1909a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
1910dc1bdc4fSdanielk1977       int addr;
191182c3d636Sdrh 
1912d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
19130342b1f5Sdrh       if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
1914d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1915c926afbcSdrh         ** right.
1916d8bc7086Sdrh         */
191782c3d636Sdrh         unionTab = iParm;
191882c3d636Sdrh       }else{
1919d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1920d8bc7086Sdrh         ** intermediate results.
1921d8bc7086Sdrh         */
192282c3d636Sdrh         unionTab = pParse->nTab++;
19239a99334dSdrh         if( processCompoundOrderBy(pParse, p, unionTab) ){
192484ac9d02Sdanielk1977           rc = 1;
192584ac9d02Sdanielk1977           goto multi_select_end;
1926d8bc7086Sdrh         }
1927b9bb7c18Sdrh         addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, unionTab, 0);
19280342b1f5Sdrh         if( priorOp==SRT_Table ){
19290342b1f5Sdrh           assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
19300342b1f5Sdrh           aSetP2[nSetP2++] = addr;
19310342b1f5Sdrh         }else{
1932b9bb7c18Sdrh           assert( p->addrOpenEphm[0] == -1 );
1933b9bb7c18Sdrh           p->addrOpenEphm[0] = addr;
1934b9bb7c18Sdrh           p->pRightmost->usesEphm = 1;
1935dc1bdc4fSdanielk1977         }
19360342b1f5Sdrh         createSortingIndex(pParse, p, pOrderBy);
193784ac9d02Sdanielk1977         assert( p->pEList );
1938d8bc7086Sdrh       }
1939d8bc7086Sdrh 
1940d8bc7086Sdrh       /* Code the SELECT statements to our left
1941d8bc7086Sdrh       */
1942b3bce662Sdanielk1977       assert( !pPrior->pOrderBy );
1943b3bce662Sdanielk1977       rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
194484ac9d02Sdanielk1977       if( rc ){
194584ac9d02Sdanielk1977         goto multi_select_end;
194684ac9d02Sdanielk1977       }
1947d8bc7086Sdrh 
1948d8bc7086Sdrh       /* Code the current SELECT statement
1949d8bc7086Sdrh       */
1950d8bc7086Sdrh       switch( p->op ){
1951d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
1952d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
1953d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
1954d8bc7086Sdrh       }
195582c3d636Sdrh       p->pPrior = 0;
1956c926afbcSdrh       p->pOrderBy = 0;
19574b14b4d7Sdrh       p->disallowOrderBy = pOrderBy!=0;
1958a2dc3b1aSdanielk1977       pLimit = p->pLimit;
1959a2dc3b1aSdanielk1977       p->pLimit = 0;
1960a2dc3b1aSdanielk1977       pOffset = p->pOffset;
1961a2dc3b1aSdanielk1977       p->pOffset = 0;
1962b3bce662Sdanielk1977       rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
19635bd1bf2eSdrh       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
19645bd1bf2eSdrh       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
19655bd1bf2eSdrh       sqlite3ExprListDelete(p->pOrderBy);
196682c3d636Sdrh       p->pPrior = pPrior;
1967c926afbcSdrh       p->pOrderBy = pOrderBy;
1968a2dc3b1aSdanielk1977       sqlite3ExprDelete(p->pLimit);
1969a2dc3b1aSdanielk1977       p->pLimit = pLimit;
1970a2dc3b1aSdanielk1977       p->pOffset = pOffset;
1971be5fd490Sdrh       p->iLimit = -1;
1972be5fd490Sdrh       p->iOffset = -1;
197384ac9d02Sdanielk1977       if( rc ){
197484ac9d02Sdanielk1977         goto multi_select_end;
197584ac9d02Sdanielk1977       }
197684ac9d02Sdanielk1977 
1977d8bc7086Sdrh 
1978d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1979d8bc7086Sdrh       ** it is that we currently need.
1980d8bc7086Sdrh       */
1981c926afbcSdrh       if( eDest!=priorOp || unionTab!=iParm ){
19826b56344dSdrh         int iCont, iBreak, iStart;
198382c3d636Sdrh         assert( p->pEList );
198441202ccaSdrh         if( eDest==SRT_Callback ){
198592378253Sdrh           Select *pFirst = p;
198692378253Sdrh           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
198792378253Sdrh           generateColumnNames(pParse, 0, pFirst->pEList);
198841202ccaSdrh         }
19894adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
19904adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
1991ec7429aeSdrh         computeLimitRegisters(pParse, p, iBreak);
19924adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
19934adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
199438640e15Sdrh         rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
19950342b1f5Sdrh                              pOrderBy, -1, eDest, iParm,
199684ac9d02Sdanielk1977                              iCont, iBreak, 0);
199784ac9d02Sdanielk1977         if( rc ){
199884ac9d02Sdanielk1977           rc = 1;
199984ac9d02Sdanielk1977           goto multi_select_end;
200084ac9d02Sdanielk1977         }
20014adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
20024adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
20034adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
20044adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
200582c3d636Sdrh       }
200682c3d636Sdrh       break;
200782c3d636Sdrh     }
200882c3d636Sdrh     case TK_INTERSECT: {
200982c3d636Sdrh       int tab1, tab2;
20106b56344dSdrh       int iCont, iBreak, iStart;
2011a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset;
2012dc1bdc4fSdanielk1977       int addr;
201382c3d636Sdrh 
2014d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
20156206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
2016d8bc7086Sdrh       ** by allocating the tables we will need.
2017d8bc7086Sdrh       */
201882c3d636Sdrh       tab1 = pParse->nTab++;
201982c3d636Sdrh       tab2 = pParse->nTab++;
20209a99334dSdrh       if( processCompoundOrderBy(pParse, p, tab1) ){
202184ac9d02Sdanielk1977         rc = 1;
202284ac9d02Sdanielk1977         goto multi_select_end;
2023d8bc7086Sdrh       }
20240342b1f5Sdrh       createSortingIndex(pParse, p, pOrderBy);
2025dc1bdc4fSdanielk1977 
2026b9bb7c18Sdrh       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab1, 0);
2027b9bb7c18Sdrh       assert( p->addrOpenEphm[0] == -1 );
2028b9bb7c18Sdrh       p->addrOpenEphm[0] = addr;
2029b9bb7c18Sdrh       p->pRightmost->usesEphm = 1;
203084ac9d02Sdanielk1977       assert( p->pEList );
2031d8bc7086Sdrh 
2032d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
2033d8bc7086Sdrh       */
2034b3bce662Sdanielk1977       rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
203584ac9d02Sdanielk1977       if( rc ){
203684ac9d02Sdanielk1977         goto multi_select_end;
203784ac9d02Sdanielk1977       }
2038d8bc7086Sdrh 
2039d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
2040d8bc7086Sdrh       */
2041b9bb7c18Sdrh       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab2, 0);
2042b9bb7c18Sdrh       assert( p->addrOpenEphm[1] == -1 );
2043b9bb7c18Sdrh       p->addrOpenEphm[1] = addr;
204482c3d636Sdrh       p->pPrior = 0;
2045a2dc3b1aSdanielk1977       pLimit = p->pLimit;
2046a2dc3b1aSdanielk1977       p->pLimit = 0;
2047a2dc3b1aSdanielk1977       pOffset = p->pOffset;
2048a2dc3b1aSdanielk1977       p->pOffset = 0;
2049b3bce662Sdanielk1977       rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
205082c3d636Sdrh       p->pPrior = pPrior;
2051a2dc3b1aSdanielk1977       sqlite3ExprDelete(p->pLimit);
2052a2dc3b1aSdanielk1977       p->pLimit = pLimit;
2053a2dc3b1aSdanielk1977       p->pOffset = pOffset;
205484ac9d02Sdanielk1977       if( rc ){
205584ac9d02Sdanielk1977         goto multi_select_end;
205684ac9d02Sdanielk1977       }
2057d8bc7086Sdrh 
2058d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
2059d8bc7086Sdrh       ** tables.
2060d8bc7086Sdrh       */
206182c3d636Sdrh       assert( p->pEList );
206241202ccaSdrh       if( eDest==SRT_Callback ){
206392378253Sdrh         Select *pFirst = p;
206492378253Sdrh         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
206592378253Sdrh         generateColumnNames(pParse, 0, pFirst->pEList);
206641202ccaSdrh       }
20674adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
20684adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
2069ec7429aeSdrh       computeLimitRegisters(pParse, p, iBreak);
20704adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
20714a9f241cSdrh       iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0);
20724adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
207338640e15Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
20740342b1f5Sdrh                              pOrderBy, -1, eDest, iParm,
207584ac9d02Sdanielk1977                              iCont, iBreak, 0);
207684ac9d02Sdanielk1977       if( rc ){
207784ac9d02Sdanielk1977         rc = 1;
207884ac9d02Sdanielk1977         goto multi_select_end;
207984ac9d02Sdanielk1977       }
20804adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
20814adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
20824adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
20834adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
20844adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
208582c3d636Sdrh       break;
208682c3d636Sdrh     }
208782c3d636Sdrh   }
20888cdbf836Sdrh 
20898cdbf836Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
20908cdbf836Sdrh   ** in their result sets.
20918cdbf836Sdrh   */
209282c3d636Sdrh   assert( p->pEList && pPrior->pEList );
209382c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
20944adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
2095da93d238Sdrh       " do not have the same number of result columns", selectOpName(p->op));
209684ac9d02Sdanielk1977     rc = 1;
209784ac9d02Sdanielk1977     goto multi_select_end;
20982282792aSdrh   }
209984ac9d02Sdanielk1977 
21008cdbf836Sdrh   /* Set the number of columns in temporary tables
21018cdbf836Sdrh   */
21028cdbf836Sdrh   nCol = p->pEList->nExpr;
21030342b1f5Sdrh   while( nSetP2 ){
21040342b1f5Sdrh     sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
21058cdbf836Sdrh   }
21068cdbf836Sdrh 
2107fbc4ee7bSdrh   /* Compute collating sequences used by either the ORDER BY clause or
2108fbc4ee7bSdrh   ** by any temporary tables needed to implement the compound select.
2109fbc4ee7bSdrh   ** Attach the KeyInfo structure to all temporary tables.  Invoke the
2110fbc4ee7bSdrh   ** ORDER BY processing if there is an ORDER BY clause.
21118cdbf836Sdrh   **
21128cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
21138cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
21148cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
21158cdbf836Sdrh   ** no temp tables are required.
2116fbc4ee7bSdrh   */
2117b9bb7c18Sdrh   if( pOrderBy || p->usesEphm ){
2118fbc4ee7bSdrh     int i;                        /* Loop counter */
2119fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
21200342b1f5Sdrh     Select *pLoop;                /* For looping through SELECT statements */
21211e31e0b2Sdrh     int nKeyCol;                  /* Number of entries in pKeyInfo->aCol[] */
2122f68d7d17Sdrh     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
2123f68d7d17Sdrh     CollSeq **aCopy;              /* A copy of pKeyInfo->aColl[] */
2124fbc4ee7bSdrh 
21250342b1f5Sdrh     assert( p->pRightmost==p );
21261e31e0b2Sdrh     nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0);
212717435752Sdrh     pKeyInfo = sqlite3DbMallocZero(pParse->db,
212817435752Sdrh                        sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1));
2129dc1bdc4fSdanielk1977     if( !pKeyInfo ){
2130dc1bdc4fSdanielk1977       rc = SQLITE_NOMEM;
2131dc1bdc4fSdanielk1977       goto multi_select_end;
2132dc1bdc4fSdanielk1977     }
2133dc1bdc4fSdanielk1977 
213414db2665Sdanielk1977     pKeyInfo->enc = ENC(pParse->db);
2135dc1bdc4fSdanielk1977     pKeyInfo->nField = nCol;
2136dc1bdc4fSdanielk1977 
21370342b1f5Sdrh     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
21380342b1f5Sdrh       *apColl = multiSelectCollSeq(pParse, p, i);
21390342b1f5Sdrh       if( 0==*apColl ){
21400342b1f5Sdrh         *apColl = pParse->db->pDfltColl;
2141dc1bdc4fSdanielk1977       }
2142dc1bdc4fSdanielk1977     }
2143dc1bdc4fSdanielk1977 
21440342b1f5Sdrh     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
21450342b1f5Sdrh       for(i=0; i<2; i++){
2146b9bb7c18Sdrh         int addr = pLoop->addrOpenEphm[i];
21470342b1f5Sdrh         if( addr<0 ){
21480342b1f5Sdrh           /* If [0] is unused then [1] is also unused.  So we can
21490342b1f5Sdrh           ** always safely abort as soon as the first unused slot is found */
2150b9bb7c18Sdrh           assert( pLoop->addrOpenEphm[1]<0 );
21510342b1f5Sdrh           break;
21520342b1f5Sdrh         }
21530342b1f5Sdrh         sqlite3VdbeChangeP2(v, addr, nCol);
21540342b1f5Sdrh         sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO);
21550ee5a1e7Sdrh         pLoop->addrOpenEphm[i] = -1;
21560342b1f5Sdrh       }
2157dc1bdc4fSdanielk1977     }
2158dc1bdc4fSdanielk1977 
21590342b1f5Sdrh     if( pOrderBy ){
21600342b1f5Sdrh       struct ExprList_item *pOTerm = pOrderBy->a;
21614efc083fSdrh       int nOrderByExpr = pOrderBy->nExpr;
21620342b1f5Sdrh       int addr;
21634db38a70Sdrh       u8 *pSortOrder;
21640342b1f5Sdrh 
2165f68d7d17Sdrh       /* Reuse the same pKeyInfo for the ORDER BY as was used above for
2166f68d7d17Sdrh       ** the compound select statements.  Except we have to change out the
2167f68d7d17Sdrh       ** pKeyInfo->aColl[] values.  Some of the aColl[] values will be
2168f68d7d17Sdrh       ** reused when constructing the pKeyInfo for the ORDER BY, so make
2169f68d7d17Sdrh       ** a copy.  Sufficient space to hold both the nCol entries for
2170f68d7d17Sdrh       ** the compound select and the nOrderbyExpr entries for the ORDER BY
2171f68d7d17Sdrh       ** was allocated above.  But we need to move the compound select
2172f68d7d17Sdrh       ** entries out of the way before constructing the ORDER BY entries.
2173f68d7d17Sdrh       ** Move the compound select entries into aCopy[] where they can be
2174f68d7d17Sdrh       ** accessed and reused when constructing the ORDER BY entries.
2175f68d7d17Sdrh       ** Because nCol might be greater than or less than nOrderByExpr
2176f68d7d17Sdrh       ** we have to use memmove() when doing the copy.
2177f68d7d17Sdrh       */
21781e31e0b2Sdrh       aCopy = &pKeyInfo->aColl[nOrderByExpr];
21794efc083fSdrh       pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
2180f68d7d17Sdrh       memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
2181f68d7d17Sdrh 
21820342b1f5Sdrh       apColl = pKeyInfo->aColl;
21834efc083fSdrh       for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
21840342b1f5Sdrh         Expr *pExpr = pOTerm->pExpr;
21858b4c40d8Sdrh         if( (pExpr->flags & EP_ExpCollate) ){
21868b4c40d8Sdrh           assert( pExpr->pColl!=0 );
21878b4c40d8Sdrh           *apColl = pExpr->pColl;
218884ac9d02Sdanielk1977         }else{
21890342b1f5Sdrh           *apColl = aCopy[pExpr->iColumn];
219084ac9d02Sdanielk1977         }
21914db38a70Sdrh         *pSortOrder = pOTerm->sortOrder;
219284ac9d02Sdanielk1977       }
21930342b1f5Sdrh       assert( p->pRightmost==p );
2194b9bb7c18Sdrh       assert( p->addrOpenEphm[2]>=0 );
2195b9bb7c18Sdrh       addr = p->addrOpenEphm[2];
2196a670b226Sdanielk1977       sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2);
21974efc083fSdrh       pKeyInfo->nField = nOrderByExpr;
21984db38a70Sdrh       sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
21994db38a70Sdrh       pKeyInfo = 0;
2200cdd536f0Sdrh       generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
2201dc1bdc4fSdanielk1977     }
2202dc1bdc4fSdanielk1977 
220317435752Sdrh     sqlite3_free(pKeyInfo);
2204dc1bdc4fSdanielk1977   }
2205dc1bdc4fSdanielk1977 
2206dc1bdc4fSdanielk1977 multi_select_end:
220784ac9d02Sdanielk1977   return rc;
22082282792aSdrh }
2209b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
22102282792aSdrh 
2211b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
221217435752Sdrh /* Forward Declarations */
221317435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*);
221417435752Sdrh static void substSelect(sqlite3*, Select *, int, ExprList *);
221517435752Sdrh 
22162282792aSdrh /*
2217832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
22186a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
221984e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
22206a3ea0e6Sdrh ** unchanged.)
2221832508b7Sdrh **
2222832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
2223832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
2224832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
2225832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
2226832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
2227832508b7Sdrh ** of the subquery rather the result set of the subquery.
2228832508b7Sdrh */
222917435752Sdrh static void substExpr(
223017435752Sdrh   sqlite3 *db,        /* Report malloc errors to this connection */
223117435752Sdrh   Expr *pExpr,        /* Expr in which substitution occurs */
223217435752Sdrh   int iTable,         /* Table to be substituted */
223317435752Sdrh   ExprList *pEList    /* Substitute expressions */
223417435752Sdrh ){
2235832508b7Sdrh   if( pExpr==0 ) return;
223650350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
223750350a15Sdrh     if( pExpr->iColumn<0 ){
223850350a15Sdrh       pExpr->op = TK_NULL;
223950350a15Sdrh     }else{
2240832508b7Sdrh       Expr *pNew;
224184e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
2242832508b7Sdrh       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
2243832508b7Sdrh       pNew = pEList->a[pExpr->iColumn].pExpr;
2244832508b7Sdrh       assert( pNew!=0 );
2245832508b7Sdrh       pExpr->op = pNew->op;
2246d94a6698Sdrh       assert( pExpr->pLeft==0 );
224717435752Sdrh       pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
2248d94a6698Sdrh       assert( pExpr->pRight==0 );
224917435752Sdrh       pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
2250d94a6698Sdrh       assert( pExpr->pList==0 );
225117435752Sdrh       pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
2252832508b7Sdrh       pExpr->iTable = pNew->iTable;
2253fbbe005aSdanielk1977       pExpr->pTab = pNew->pTab;
2254832508b7Sdrh       pExpr->iColumn = pNew->iColumn;
2255832508b7Sdrh       pExpr->iAgg = pNew->iAgg;
225617435752Sdrh       sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
225717435752Sdrh       sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
225817435752Sdrh       pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
2259a1cb183dSdanielk1977       pExpr->flags = pNew->flags;
226050350a15Sdrh     }
2261832508b7Sdrh   }else{
226217435752Sdrh     substExpr(db, pExpr->pLeft, iTable, pEList);
226317435752Sdrh     substExpr(db, pExpr->pRight, iTable, pEList);
226417435752Sdrh     substSelect(db, pExpr->pSelect, iTable, pEList);
226517435752Sdrh     substExprList(db, pExpr->pList, iTable, pEList);
2266832508b7Sdrh   }
2267832508b7Sdrh }
226817435752Sdrh static void substExprList(
226917435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
227017435752Sdrh   ExprList *pList,     /* List to scan and in which to make substitutes */
227117435752Sdrh   int iTable,          /* Table to be substituted */
227217435752Sdrh   ExprList *pEList     /* Substitute values */
227317435752Sdrh ){
2274832508b7Sdrh   int i;
2275832508b7Sdrh   if( pList==0 ) return;
2276832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
227717435752Sdrh     substExpr(db, pList->a[i].pExpr, iTable, pEList);
2278832508b7Sdrh   }
2279832508b7Sdrh }
228017435752Sdrh static void substSelect(
228117435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
228217435752Sdrh   Select *p,           /* SELECT statement in which to make substitutions */
228317435752Sdrh   int iTable,          /* Table to be replaced */
228417435752Sdrh   ExprList *pEList     /* Substitute values */
228517435752Sdrh ){
2286b3bce662Sdanielk1977   if( !p ) return;
228717435752Sdrh   substExprList(db, p->pEList, iTable, pEList);
228817435752Sdrh   substExprList(db, p->pGroupBy, iTable, pEList);
228917435752Sdrh   substExprList(db, p->pOrderBy, iTable, pEList);
229017435752Sdrh   substExpr(db, p->pHaving, iTable, pEList);
229117435752Sdrh   substExpr(db, p->pWhere, iTable, pEList);
229217435752Sdrh   substSelect(db, p->pPrior, iTable, pEList);
2293b3bce662Sdanielk1977 }
2294b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_VIEW) */
2295832508b7Sdrh 
2296b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
2297832508b7Sdrh /*
22981350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
22991350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
23001350b030Sdrh ** occurs.
23011350b030Sdrh **
23021350b030Sdrh ** To understand the concept of flattening, consider the following
23031350b030Sdrh ** query:
23041350b030Sdrh **
23051350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
23061350b030Sdrh **
23071350b030Sdrh ** The default way of implementing this query is to execute the
23081350b030Sdrh ** subquery first and store the results in a temporary table, then
23091350b030Sdrh ** run the outer query on that temporary table.  This requires two
23101350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
23111350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
2312832508b7Sdrh ** optimized.
23131350b030Sdrh **
2314832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
23151350b030Sdrh ** a single flat select, like this:
23161350b030Sdrh **
23171350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
23181350b030Sdrh **
23191350b030Sdrh ** The code generated for this simpification gives the same result
2320832508b7Sdrh ** but only has to scan the data once.  And because indices might
2321832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
2322832508b7Sdrh ** avoided.
23231350b030Sdrh **
2324832508b7Sdrh ** Flattening is only attempted if all of the following are true:
23251350b030Sdrh **
2326832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
23271350b030Sdrh **
2328832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
2329832508b7Sdrh **
23308af4d3acSdrh **   (3)  The subquery is not the right operand of a left outer join, or
23318af4d3acSdrh **        the subquery is not itself a join.  (Ticket #306)
2332832508b7Sdrh **
2333832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
2334832508b7Sdrh **
2335832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
2336832508b7Sdrh **        aggregates.
2337832508b7Sdrh **
2338832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
2339832508b7Sdrh **        DISTINCT.
2340832508b7Sdrh **
234108192d5fSdrh **   (7)  The subquery has a FROM clause.
234208192d5fSdrh **
2343df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
2344df199a25Sdrh **
2345df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
2346df199a25Sdrh **        aggregates.
2347df199a25Sdrh **
2348df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
2349df199a25Sdrh **        use LIMIT.
2350df199a25Sdrh **
2351174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
2352174b6195Sdrh **
23533fc673e6Sdrh **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
23543fc673e6Sdrh **        subquery has no WHERE clause.  (added by ticket #350)
23553fc673e6Sdrh **
2356ac83963aSdrh **  (13)  The subquery and outer query do not both use LIMIT
2357ac83963aSdrh **
2358ac83963aSdrh **  (14)  The subquery does not use OFFSET
2359ac83963aSdrh **
2360ad91c6cdSdrh **  (15)  The outer query is not part of a compound select or the
2361ad91c6cdSdrh **        subquery does not have both an ORDER BY and a LIMIT clause.
2362ad91c6cdSdrh **        (See ticket #2339)
2363ad91c6cdSdrh **
2364832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
2365832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
2366832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
2367832508b7Sdrh **
2368665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
2369832508b7Sdrh ** If flattening is attempted this routine returns 1.
2370832508b7Sdrh **
2371832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
2372832508b7Sdrh ** the subquery before this routine runs.
23731350b030Sdrh */
23748c74a8caSdrh static int flattenSubquery(
237517435752Sdrh   sqlite3 *db,         /* Database connection */
23768c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
23778c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
23788c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
23798c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
23808c74a8caSdrh ){
23810bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
2382ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
2383ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
23840bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
23856a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
238691bb0eedSdrh   int i;              /* Loop counter */
238791bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
238891bb0eedSdrh   struct SrcList_item *pSubitem;   /* The subquery */
23891350b030Sdrh 
2390832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
2391832508b7Sdrh   */
2392832508b7Sdrh   if( p==0 ) return 0;
2393832508b7Sdrh   pSrc = p->pSrc;
2394ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
239591bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
239691bb0eedSdrh   pSub = pSubitem->pSelect;
2397832508b7Sdrh   assert( pSub!=0 );
2398ac83963aSdrh   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
2399ac83963aSdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
2400832508b7Sdrh   pSubSrc = pSub->pSrc;
2401832508b7Sdrh   assert( pSubSrc );
2402ac83963aSdrh   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
2403ac83963aSdrh   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
2404ac83963aSdrh   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
2405ac83963aSdrh   ** became arbitrary expressions, we were forced to add restrictions (13)
2406ac83963aSdrh   ** and (14). */
2407ac83963aSdrh   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
2408ac83963aSdrh   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
2409ad91c6cdSdrh   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
2410ad91c6cdSdrh     return 0;                                            /* Restriction (15) */
2411ad91c6cdSdrh   }
2412ac83963aSdrh   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
2413ac83963aSdrh   if( (pSub->isDistinct || pSub->pLimit)
2414ac83963aSdrh          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
2415df199a25Sdrh      return 0;
2416df199a25Sdrh   }
2417ac83963aSdrh   if( p->isDistinct && subqueryIsAgg ) return 0;         /* Restriction (6)  */
2418ac83963aSdrh   if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){
2419ac83963aSdrh      return 0;                                           /* Restriction (11) */
2420ac83963aSdrh   }
2421832508b7Sdrh 
24228af4d3acSdrh   /* Restriction 3:  If the subquery is a join, make sure the subquery is
24238af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
24248af4d3acSdrh   ** is not allowed:
24258af4d3acSdrh   **
24268af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
24278af4d3acSdrh   **
24288af4d3acSdrh   ** If we flatten the above, we would get
24298af4d3acSdrh   **
24308af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
24318af4d3acSdrh   **
24328af4d3acSdrh   ** which is not at all the same thing.
24338af4d3acSdrh   */
243461dfc31dSdrh   if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){
24358af4d3acSdrh     return 0;
24368af4d3acSdrh   }
24378af4d3acSdrh 
24383fc673e6Sdrh   /* Restriction 12:  If the subquery is the right operand of a left outer
24393fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
24403fc673e6Sdrh   ** An examples of why this is not allowed:
24413fc673e6Sdrh   **
24423fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
24433fc673e6Sdrh   **
24443fc673e6Sdrh   ** If we flatten the above, we would get
24453fc673e6Sdrh   **
24463fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
24473fc673e6Sdrh   **
24483fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
24493fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
24503fc673e6Sdrh   */
245161dfc31dSdrh   if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){
24523fc673e6Sdrh     return 0;
24533fc673e6Sdrh   }
24543fc673e6Sdrh 
24550bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
245663eb5f29Sdrh   ** iFrom-th entry of the FROM clause in the outer query.
2457832508b7Sdrh   */
2458c31c2eb8Sdrh 
2459c31c2eb8Sdrh   /* Move all of the FROM elements of the subquery into the
2460c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
2461c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
2462c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
2463c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
2464c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
2465c31c2eb8Sdrh   ** elements we are now copying in.
2466c31c2eb8Sdrh   */
246791bb0eedSdrh   iParent = pSubitem->iCursor;
2468c31c2eb8Sdrh   {
2469c31c2eb8Sdrh     int nSubSrc = pSubSrc->nSrc;
247091bb0eedSdrh     int jointype = pSubitem->jointype;
2471c31c2eb8Sdrh 
2472a04a34ffSdanielk1977     sqlite3DeleteTable(pSubitem->pTab);
247317435752Sdrh     sqlite3_free(pSubitem->zDatabase);
247417435752Sdrh     sqlite3_free(pSubitem->zName);
247517435752Sdrh     sqlite3_free(pSubitem->zAlias);
2476cfa063b3Sdrh     pSubitem->pTab = 0;
2477cfa063b3Sdrh     pSubitem->zDatabase = 0;
2478cfa063b3Sdrh     pSubitem->zName = 0;
2479cfa063b3Sdrh     pSubitem->zAlias = 0;
2480c31c2eb8Sdrh     if( nSubSrc>1 ){
2481c31c2eb8Sdrh       int extra = nSubSrc - 1;
2482c31c2eb8Sdrh       for(i=1; i<nSubSrc; i++){
248317435752Sdrh         pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0);
2484cfa063b3Sdrh         if( pSrc==0 ){
2485cfa063b3Sdrh           p->pSrc = 0;
2486cfa063b3Sdrh           return 1;
2487cfa063b3Sdrh         }
2488c31c2eb8Sdrh       }
2489c31c2eb8Sdrh       p->pSrc = pSrc;
2490c31c2eb8Sdrh       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2491c31c2eb8Sdrh         pSrc->a[i] = pSrc->a[i-extra];
2492c31c2eb8Sdrh       }
2493c31c2eb8Sdrh     }
2494c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
2495c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
2496c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2497c31c2eb8Sdrh     }
249861dfc31dSdrh     pSrc->a[iFrom].jointype = jointype;
2499c31c2eb8Sdrh   }
2500c31c2eb8Sdrh 
2501c31c2eb8Sdrh   /* Now begin substituting subquery result set expressions for
2502c31c2eb8Sdrh   ** references to the iParent in the outer query.
2503c31c2eb8Sdrh   **
2504c31c2eb8Sdrh   ** Example:
2505c31c2eb8Sdrh   **
2506c31c2eb8Sdrh   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2507c31c2eb8Sdrh   **   \                     \_____________ subquery __________/          /
2508c31c2eb8Sdrh   **    \_____________________ outer query ______________________________/
2509c31c2eb8Sdrh   **
2510c31c2eb8Sdrh   ** We look at every expression in the outer query and every place we see
2511c31c2eb8Sdrh   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2512c31c2eb8Sdrh   */
2513832508b7Sdrh   pList = p->pEList;
2514832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
25156977fea8Sdrh     Expr *pExpr;
25166977fea8Sdrh     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
251717435752Sdrh       pList->a[i].zName =
251817435752Sdrh              sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
2519832508b7Sdrh     }
2520832508b7Sdrh   }
25211e536953Sdanielk1977   substExprList(db, p->pEList, iParent, pSub->pEList);
25221b2e0329Sdrh   if( isAgg ){
25231e536953Sdanielk1977     substExprList(db, p->pGroupBy, iParent, pSub->pEList);
25241e536953Sdanielk1977     substExpr(db, p->pHaving, iParent, pSub->pEList);
25251b2e0329Sdrh   }
2526174b6195Sdrh   if( pSub->pOrderBy ){
2527174b6195Sdrh     assert( p->pOrderBy==0 );
2528174b6195Sdrh     p->pOrderBy = pSub->pOrderBy;
2529174b6195Sdrh     pSub->pOrderBy = 0;
2530174b6195Sdrh   }else if( p->pOrderBy ){
25311e536953Sdanielk1977     substExprList(db, p->pOrderBy, iParent, pSub->pEList);
2532174b6195Sdrh   }
2533832508b7Sdrh   if( pSub->pWhere ){
253417435752Sdrh     pWhere = sqlite3ExprDup(db, pSub->pWhere);
2535832508b7Sdrh   }else{
2536832508b7Sdrh     pWhere = 0;
2537832508b7Sdrh   }
2538832508b7Sdrh   if( subqueryIsAgg ){
2539832508b7Sdrh     assert( p->pHaving==0 );
25401b2e0329Sdrh     p->pHaving = p->pWhere;
25411b2e0329Sdrh     p->pWhere = pWhere;
25421e536953Sdanielk1977     substExpr(db, p->pHaving, iParent, pSub->pEList);
254317435752Sdrh     p->pHaving = sqlite3ExprAnd(db, p->pHaving,
254417435752Sdrh                                 sqlite3ExprDup(db, pSub->pHaving));
25451b2e0329Sdrh     assert( p->pGroupBy==0 );
254617435752Sdrh     p->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
2547832508b7Sdrh   }else{
25481e536953Sdanielk1977     substExpr(db, p->pWhere, iParent, pSub->pEList);
254917435752Sdrh     p->pWhere = sqlite3ExprAnd(db, p->pWhere, pWhere);
2550832508b7Sdrh   }
2551c31c2eb8Sdrh 
2552c31c2eb8Sdrh   /* The flattened query is distinct if either the inner or the
2553c31c2eb8Sdrh   ** outer query is distinct.
2554c31c2eb8Sdrh   */
2555832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
25568c74a8caSdrh 
2557a58fdfb1Sdanielk1977   /*
2558a58fdfb1Sdanielk1977   ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2559ac83963aSdrh   **
2560ac83963aSdrh   ** One is tempted to try to add a and b to combine the limits.  But this
2561ac83963aSdrh   ** does not work if either limit is negative.
2562a58fdfb1Sdanielk1977   */
2563a2dc3b1aSdanielk1977   if( pSub->pLimit ){
2564a2dc3b1aSdanielk1977     p->pLimit = pSub->pLimit;
2565a2dc3b1aSdanielk1977     pSub->pLimit = 0;
2566df199a25Sdrh   }
25678c74a8caSdrh 
2568c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
2569c31c2eb8Sdrh   ** success.
2570c31c2eb8Sdrh   */
25714adee20fSdanielk1977   sqlite3SelectDelete(pSub);
2572832508b7Sdrh   return 1;
25731350b030Sdrh }
2574b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */
25751350b030Sdrh 
25761350b030Sdrh /*
25779562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it
25789562b551Sdrh ** is a simple min() or max() query.  If it is and this query can be
25799562b551Sdrh ** satisfied using a single seek to the beginning or end of an index,
2580e78e8284Sdrh ** then generate the code for this SELECT and return 1.  If this is not a
25819562b551Sdrh ** simple min() or max() query, then return 0;
25829562b551Sdrh **
25839562b551Sdrh ** A simply min() or max() query looks like this:
25849562b551Sdrh **
25859562b551Sdrh **    SELECT min(a) FROM table;
25869562b551Sdrh **    SELECT max(a) FROM table;
25879562b551Sdrh **
25889562b551Sdrh ** The query may have only a single table in its FROM argument.  There
25899562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
25909562b551Sdrh ** be the min() or max() of a single column of the table.  The column
25919562b551Sdrh ** in the min() or max() function must be indexed.
25929562b551Sdrh **
25934adee20fSdanielk1977 ** The parameters to this routine are the same as for sqlite3Select().
25949562b551Sdrh ** See the header comment on that routine for additional information.
25959562b551Sdrh */
25969562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
25979562b551Sdrh   Expr *pExpr;
25989562b551Sdrh   int iCol;
25999562b551Sdrh   Table *pTab;
26009562b551Sdrh   Index *pIdx;
26019562b551Sdrh   int base;
26029562b551Sdrh   Vdbe *v;
26039562b551Sdrh   int seekOp;
26046e17529eSdrh   ExprList *pEList, *pList, eList;
26059562b551Sdrh   struct ExprList_item eListItem;
26066e17529eSdrh   SrcList *pSrc;
2607ec7429aeSdrh   int brk;
2608da184236Sdanielk1977   int iDb;
26096e17529eSdrh 
26109562b551Sdrh   /* Check to see if this query is a simple min() or max() query.  Return
26119562b551Sdrh   ** zero if it is  not.
26129562b551Sdrh   */
26139562b551Sdrh   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
26146e17529eSdrh   pSrc = p->pSrc;
26156e17529eSdrh   if( pSrc->nSrc!=1 ) return 0;
26166e17529eSdrh   pEList = p->pEList;
26176e17529eSdrh   if( pEList->nExpr!=1 ) return 0;
26186e17529eSdrh   pExpr = pEList->a[0].pExpr;
26199562b551Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
26206e17529eSdrh   pList = pExpr->pList;
26216e17529eSdrh   if( pList==0 || pList->nExpr!=1 ) return 0;
26226977fea8Sdrh   if( pExpr->token.n!=3 ) return 0;
26232646da7eSdrh   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
26240bce8354Sdrh     seekOp = OP_Rewind;
26252646da7eSdrh   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
26260bce8354Sdrh     seekOp = OP_Last;
26270bce8354Sdrh   }else{
26280bce8354Sdrh     return 0;
26290bce8354Sdrh   }
26306e17529eSdrh   pExpr = pList->a[0].pExpr;
26319562b551Sdrh   if( pExpr->op!=TK_COLUMN ) return 0;
26329562b551Sdrh   iCol = pExpr->iColumn;
26336e17529eSdrh   pTab = pSrc->a[0].pTab;
26349562b551Sdrh 
2635a41c7497Sdanielk1977   /* This optimization cannot be used with virtual tables. */
2636a41c7497Sdanielk1977   if( IsVirtual(pTab) ) return 0;
2637c00da105Sdanielk1977 
26389562b551Sdrh   /* If we get to here, it means the query is of the correct form.
263917f71934Sdrh   ** Check to make sure we have an index and make pIdx point to the
264017f71934Sdrh   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
264117f71934Sdrh   ** key column, no index is necessary so set pIdx to NULL.  If no
264217f71934Sdrh   ** usable index is found, return 0.
26439562b551Sdrh   */
26449562b551Sdrh   if( iCol<0 ){
26459562b551Sdrh     pIdx = 0;
26469562b551Sdrh   }else{
2647dc1bdc4fSdanielk1977     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
2648206f3d96Sdrh     if( pColl==0 ) return 0;
26499562b551Sdrh     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
26509562b551Sdrh       assert( pIdx->nColumn>=1 );
2651b3bf556eSdanielk1977       if( pIdx->aiColumn[0]==iCol &&
2652b3bf556eSdanielk1977           0==sqlite3StrICmp(pIdx->azColl[0], pColl->zName) ){
2653b3bf556eSdanielk1977         break;
2654b3bf556eSdanielk1977       }
26559562b551Sdrh     }
26569562b551Sdrh     if( pIdx==0 ) return 0;
26579562b551Sdrh   }
26589562b551Sdrh 
2659e5f50722Sdrh   /* Identify column types if we will be using the callback.  This
26609562b551Sdrh   ** step is skipped if the output is going to a table or a memory cell.
2661e5f50722Sdrh   ** The column names have already been generated in the calling function.
26629562b551Sdrh   */
26634adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
26649562b551Sdrh   if( v==0 ) return 0;
26659562b551Sdrh 
26660c37e630Sdrh   /* If the output is destined for a temporary table, open that table.
26670c37e630Sdrh   */
2668b9bb7c18Sdrh   if( eDest==SRT_EphemTab ){
2669b9bb7c18Sdrh     sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 1);
26700c37e630Sdrh   }
26710c37e630Sdrh 
267217f71934Sdrh   /* Generating code to find the min or the max.  Basically all we have
267317f71934Sdrh   ** to do is find the first or the last entry in the chosen index.  If
267417f71934Sdrh   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
267517f71934Sdrh   ** or last entry in the main table.
26769562b551Sdrh   */
2677da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2678b9bb7c18Sdrh   assert( iDb>=0 || pTab->isEphem );
2679da184236Sdanielk1977   sqlite3CodeVerifySchema(pParse, iDb);
2680c00da105Sdanielk1977   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
26816e17529eSdrh   base = pSrc->a[0].iCursor;
2682ec7429aeSdrh   brk = sqlite3VdbeMakeLabel(v);
2683ec7429aeSdrh   computeLimitRegisters(pParse, p, brk);
26846e17529eSdrh   if( pSrc->a[0].pSelect==0 ){
2685c00da105Sdanielk1977     sqlite3OpenTable(pParse, base, iDb, pTab, OP_OpenRead);
26866e17529eSdrh   }
26879562b551Sdrh   if( pIdx==0 ){
26884adee20fSdanielk1977     sqlite3VdbeAddOp(v, seekOp, base, 0);
26899562b551Sdrh   }else{
26903719d7f9Sdanielk1977     /* Even though the cursor used to open the index here is closed
26913719d7f9Sdanielk1977     ** as soon as a single value has been read from it, allocate it
26923719d7f9Sdanielk1977     ** using (pParse->nTab++) to prevent the cursor id from being
26933719d7f9Sdanielk1977     ** reused. This is important for statements of the form
26943719d7f9Sdanielk1977     ** "INSERT INTO x SELECT max() FROM x".
26953719d7f9Sdanielk1977     */
26963719d7f9Sdanielk1977     int iIdx;
2697b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
26983719d7f9Sdanielk1977     iIdx = pParse->nTab++;
2699da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
2700da184236Sdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
27013719d7f9Sdanielk1977     sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
2702b3bf556eSdanielk1977         (char*)pKey, P3_KEYINFO_HANDOFF);
27039eb516c0Sdrh     if( seekOp==OP_Rewind ){
2704f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
27051af3fdb4Sdrh       sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
27061af3fdb4Sdrh       seekOp = OP_MoveGt;
27079eb516c0Sdrh     }
2708309be024Sdrh     if( pIdx->aSortOrder[0]==SQLITE_SO_DESC ){
2709309be024Sdrh       /* Ticket #2514: invert the seek operator if we are using
2710309be024Sdrh       ** a descending index. */
2711309be024Sdrh       if( seekOp==OP_Last ){
2712309be024Sdrh         seekOp = OP_Rewind;
2713309be024Sdrh       }else{
2714309be024Sdrh         assert( seekOp==OP_MoveGt );
2715309be024Sdrh         seekOp = OP_MoveLt;
2716309be024Sdrh       }
2717309be024Sdrh     }
27183719d7f9Sdanielk1977     sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
2719f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
27203719d7f9Sdanielk1977     sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
27217cf6e4deSdrh     sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
27229562b551Sdrh   }
27235cf8e8c7Sdrh   eList.nExpr = 1;
27245cf8e8c7Sdrh   memset(&eListItem, 0, sizeof(eListItem));
27255cf8e8c7Sdrh   eList.a = &eListItem;
27265cf8e8c7Sdrh   eList.a[0].pExpr = pExpr;
2727ec7429aeSdrh   selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0);
2728ec7429aeSdrh   sqlite3VdbeResolveLabel(v, brk);
27294adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Close, base, 0);
27306e17529eSdrh 
27319562b551Sdrh   return 1;
27329562b551Sdrh }
27339562b551Sdrh 
27349562b551Sdrh /*
2735b3bce662Sdanielk1977 ** This routine resolves any names used in the result set of the
2736b3bce662Sdanielk1977 ** supplied SELECT statement. If the SELECT statement being resolved
2737b3bce662Sdanielk1977 ** is a sub-select, then pOuterNC is a pointer to the NameContext
2738b3bce662Sdanielk1977 ** of the parent SELECT.
2739b3bce662Sdanielk1977 */
2740b3bce662Sdanielk1977 int sqlite3SelectResolve(
2741b3bce662Sdanielk1977   Parse *pParse,         /* The parser context */
2742b3bce662Sdanielk1977   Select *p,             /* The SELECT statement being coded. */
2743b3bce662Sdanielk1977   NameContext *pOuterNC  /* The outer name context. May be NULL. */
2744b3bce662Sdanielk1977 ){
2745b3bce662Sdanielk1977   ExprList *pEList;          /* Result set. */
2746b3bce662Sdanielk1977   int i;                     /* For-loop variable used in multiple places */
2747b3bce662Sdanielk1977   NameContext sNC;           /* Local name-context */
274813449892Sdrh   ExprList *pGroupBy;        /* The group by clause */
2749b3bce662Sdanielk1977 
2750b3bce662Sdanielk1977   /* If this routine has run before, return immediately. */
2751b3bce662Sdanielk1977   if( p->isResolved ){
2752b3bce662Sdanielk1977     assert( !pOuterNC );
2753b3bce662Sdanielk1977     return SQLITE_OK;
2754b3bce662Sdanielk1977   }
2755b3bce662Sdanielk1977   p->isResolved = 1;
2756b3bce662Sdanielk1977 
2757b3bce662Sdanielk1977   /* If there have already been errors, do nothing. */
2758b3bce662Sdanielk1977   if( pParse->nErr>0 ){
2759b3bce662Sdanielk1977     return SQLITE_ERROR;
2760b3bce662Sdanielk1977   }
2761b3bce662Sdanielk1977 
2762b3bce662Sdanielk1977   /* Prepare the select statement. This call will allocate all cursors
2763b3bce662Sdanielk1977   ** required to handle the tables and subqueries in the FROM clause.
2764b3bce662Sdanielk1977   */
2765b3bce662Sdanielk1977   if( prepSelectStmt(pParse, p) ){
2766b3bce662Sdanielk1977     return SQLITE_ERROR;
2767b3bce662Sdanielk1977   }
2768b3bce662Sdanielk1977 
2769a2dc3b1aSdanielk1977   /* Resolve the expressions in the LIMIT and OFFSET clauses. These
2770a2dc3b1aSdanielk1977   ** are not allowed to refer to any names, so pass an empty NameContext.
2771a2dc3b1aSdanielk1977   */
2772ffe07b2dSdrh   memset(&sNC, 0, sizeof(sNC));
2773b3bce662Sdanielk1977   sNC.pParse = pParse;
2774a2dc3b1aSdanielk1977   if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2775a2dc3b1aSdanielk1977       sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2776a2dc3b1aSdanielk1977     return SQLITE_ERROR;
2777a2dc3b1aSdanielk1977   }
2778a2dc3b1aSdanielk1977 
2779a2dc3b1aSdanielk1977   /* Set up the local name-context to pass to ExprResolveNames() to
2780a2dc3b1aSdanielk1977   ** resolve the expression-list.
2781a2dc3b1aSdanielk1977   */
2782a2dc3b1aSdanielk1977   sNC.allowAgg = 1;
2783a2dc3b1aSdanielk1977   sNC.pSrcList = p->pSrc;
2784a2dc3b1aSdanielk1977   sNC.pNext = pOuterNC;
2785b3bce662Sdanielk1977 
2786b3bce662Sdanielk1977   /* Resolve names in the result set. */
2787b3bce662Sdanielk1977   pEList = p->pEList;
2788b3bce662Sdanielk1977   if( !pEList ) return SQLITE_ERROR;
2789b3bce662Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
2790b3bce662Sdanielk1977     Expr *pX = pEList->a[i].pExpr;
2791b3bce662Sdanielk1977     if( sqlite3ExprResolveNames(&sNC, pX) ){
2792b3bce662Sdanielk1977       return SQLITE_ERROR;
2793b3bce662Sdanielk1977     }
2794b3bce662Sdanielk1977   }
2795b3bce662Sdanielk1977 
2796b3bce662Sdanielk1977   /* If there are no aggregate functions in the result-set, and no GROUP BY
2797b3bce662Sdanielk1977   ** expression, do not allow aggregates in any of the other expressions.
2798b3bce662Sdanielk1977   */
2799b3bce662Sdanielk1977   assert( !p->isAgg );
280013449892Sdrh   pGroupBy = p->pGroupBy;
280113449892Sdrh   if( pGroupBy || sNC.hasAgg ){
2802b3bce662Sdanielk1977     p->isAgg = 1;
2803b3bce662Sdanielk1977   }else{
2804b3bce662Sdanielk1977     sNC.allowAgg = 0;
2805b3bce662Sdanielk1977   }
2806b3bce662Sdanielk1977 
2807b3bce662Sdanielk1977   /* If a HAVING clause is present, then there must be a GROUP BY clause.
2808b3bce662Sdanielk1977   */
280913449892Sdrh   if( p->pHaving && !pGroupBy ){
2810b3bce662Sdanielk1977     sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2811b3bce662Sdanielk1977     return SQLITE_ERROR;
2812b3bce662Sdanielk1977   }
2813b3bce662Sdanielk1977 
2814b3bce662Sdanielk1977   /* Add the expression list to the name-context before parsing the
2815b3bce662Sdanielk1977   ** other expressions in the SELECT statement. This is so that
2816b3bce662Sdanielk1977   ** expressions in the WHERE clause (etc.) can refer to expressions by
2817b3bce662Sdanielk1977   ** aliases in the result set.
2818b3bce662Sdanielk1977   **
2819b3bce662Sdanielk1977   ** Minor point: If this is the case, then the expression will be
2820b3bce662Sdanielk1977   ** re-evaluated for each reference to it.
2821b3bce662Sdanielk1977   */
2822b3bce662Sdanielk1977   sNC.pEList = p->pEList;
2823b3bce662Sdanielk1977   if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2824994c80afSdrh      sqlite3ExprResolveNames(&sNC, p->pHaving) ){
2825b3bce662Sdanielk1977     return SQLITE_ERROR;
2826b3bce662Sdanielk1977   }
28279a99334dSdrh   if( p->pPrior==0 ){
282801874bfcSdanielk1977     if( processOrderGroupBy(pParse, p, p->pOrderBy, 1, &sNC.hasAgg) ){
2829994c80afSdrh       return SQLITE_ERROR;
2830994c80afSdrh     }
28319a99334dSdrh   }
28329a99334dSdrh   if( processOrderGroupBy(pParse, p, pGroupBy, 0, &sNC.hasAgg) ){
28334c774314Sdrh     return SQLITE_ERROR;
2834994c80afSdrh   }
2835b3bce662Sdanielk1977 
28361e536953Sdanielk1977   if( pParse->db->mallocFailed ){
28379afe689eSdanielk1977     return SQLITE_NOMEM;
28389afe689eSdanielk1977   }
28399afe689eSdanielk1977 
284013449892Sdrh   /* Make sure the GROUP BY clause does not contain aggregate functions.
284113449892Sdrh   */
284213449892Sdrh   if( pGroupBy ){
284313449892Sdrh     struct ExprList_item *pItem;
284413449892Sdrh 
284513449892Sdrh     for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
284613449892Sdrh       if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
284713449892Sdrh         sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
284813449892Sdrh             "the GROUP BY clause");
284913449892Sdrh         return SQLITE_ERROR;
285013449892Sdrh       }
285113449892Sdrh     }
285213449892Sdrh   }
285313449892Sdrh 
2854f6bbe022Sdrh   /* If this is one SELECT of a compound, be sure to resolve names
2855f6bbe022Sdrh   ** in the other SELECTs.
2856f6bbe022Sdrh   */
2857f6bbe022Sdrh   if( p->pPrior ){
2858f6bbe022Sdrh     return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC);
2859f6bbe022Sdrh   }else{
2860b3bce662Sdanielk1977     return SQLITE_OK;
2861b3bce662Sdanielk1977   }
2862f6bbe022Sdrh }
2863b3bce662Sdanielk1977 
2864b3bce662Sdanielk1977 /*
286513449892Sdrh ** Reset the aggregate accumulator.
286613449892Sdrh **
286713449892Sdrh ** The aggregate accumulator is a set of memory cells that hold
286813449892Sdrh ** intermediate results while calculating an aggregate.  This
286913449892Sdrh ** routine simply stores NULLs in all of those memory cells.
2870b3bce662Sdanielk1977 */
287113449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
287213449892Sdrh   Vdbe *v = pParse->pVdbe;
287313449892Sdrh   int i;
2874c99130fdSdrh   struct AggInfo_func *pFunc;
287513449892Sdrh   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
287613449892Sdrh     return;
287713449892Sdrh   }
287813449892Sdrh   for(i=0; i<pAggInfo->nColumn; i++){
2879d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0);
288013449892Sdrh   }
2881c99130fdSdrh   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
2882d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0);
2883c99130fdSdrh     if( pFunc->iDistinct>=0 ){
2884c99130fdSdrh       Expr *pE = pFunc->pExpr;
2885c99130fdSdrh       if( pE->pList==0 || pE->pList->nExpr!=1 ){
2886c99130fdSdrh         sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
2887c99130fdSdrh            "by an expression");
2888c99130fdSdrh         pFunc->iDistinct = -1;
2889c99130fdSdrh       }else{
2890c99130fdSdrh         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
2891b9bb7c18Sdrh         sqlite3VdbeOp3(v, OP_OpenEphemeral, pFunc->iDistinct, 0,
2892c99130fdSdrh                           (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
2893c99130fdSdrh       }
2894c99130fdSdrh     }
289513449892Sdrh   }
2896b3bce662Sdanielk1977 }
2897b3bce662Sdanielk1977 
2898b3bce662Sdanielk1977 /*
289913449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function
290013449892Sdrh ** in the AggInfo structure.
2901b3bce662Sdanielk1977 */
290213449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
290313449892Sdrh   Vdbe *v = pParse->pVdbe;
290413449892Sdrh   int i;
290513449892Sdrh   struct AggInfo_func *pF;
290613449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
2907a10a34b8Sdrh     ExprList *pList = pF->pExpr->pList;
2908a10a34b8Sdrh     sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0,
2909a10a34b8Sdrh                       (void*)pF->pFunc, P3_FUNCDEF);
2910b3bce662Sdanielk1977   }
291113449892Sdrh }
291213449892Sdrh 
291313449892Sdrh /*
291413449892Sdrh ** Update the accumulator memory cells for an aggregate based on
291513449892Sdrh ** the current cursor position.
291613449892Sdrh */
291713449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
291813449892Sdrh   Vdbe *v = pParse->pVdbe;
291913449892Sdrh   int i;
292013449892Sdrh   struct AggInfo_func *pF;
292113449892Sdrh   struct AggInfo_col *pC;
292213449892Sdrh 
292313449892Sdrh   pAggInfo->directMode = 1;
292413449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
292513449892Sdrh     int nArg;
2926c99130fdSdrh     int addrNext = 0;
292713449892Sdrh     ExprList *pList = pF->pExpr->pList;
292813449892Sdrh     if( pList ){
292913449892Sdrh       nArg = pList->nExpr;
293013449892Sdrh       sqlite3ExprCodeExprList(pParse, pList);
293113449892Sdrh     }else{
293213449892Sdrh       nArg = 0;
293313449892Sdrh     }
2934c99130fdSdrh     if( pF->iDistinct>=0 ){
2935c99130fdSdrh       addrNext = sqlite3VdbeMakeLabel(v);
2936c99130fdSdrh       assert( nArg==1 );
2937f8875400Sdrh       codeDistinct(v, pF->iDistinct, addrNext, 1);
2938c99130fdSdrh     }
293913449892Sdrh     if( pF->pFunc->needCollSeq ){
294013449892Sdrh       CollSeq *pColl = 0;
294113449892Sdrh       struct ExprList_item *pItem;
294213449892Sdrh       int j;
294343617e9aSdrh       assert( pList!=0 );  /* pList!=0 if pF->pFunc->needCollSeq is true */
294443617e9aSdrh       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
294513449892Sdrh         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
294613449892Sdrh       }
294713449892Sdrh       if( !pColl ){
294813449892Sdrh         pColl = pParse->db->pDfltColl;
294913449892Sdrh       }
295013449892Sdrh       sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
295113449892Sdrh     }
295213449892Sdrh     sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF);
2953c99130fdSdrh     if( addrNext ){
2954c99130fdSdrh       sqlite3VdbeResolveLabel(v, addrNext);
2955c99130fdSdrh     }
295613449892Sdrh   }
295713449892Sdrh   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
29585774b806Sdrh     sqlite3ExprCode(pParse, pC->pExpr);
295913449892Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1);
296013449892Sdrh   }
296113449892Sdrh   pAggInfo->directMode = 0;
296213449892Sdrh }
296313449892Sdrh 
2964b3bce662Sdanielk1977 
2965b3bce662Sdanielk1977 /*
29669bb61fe7Sdrh ** Generate code for the given SELECT statement.
29679bb61fe7Sdrh **
2968fef5208cSdrh ** The results are distributed in various ways depending on the
2969fef5208cSdrh ** value of eDest and iParm.
2970fef5208cSdrh **
2971fef5208cSdrh **     eDest Value       Result
2972fef5208cSdrh **     ------------    -------------------------------------------
2973fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
2974fef5208cSdrh **
2975fef5208cSdrh **     SRT_Mem         Store first result in memory cell iParm
2976fef5208cSdrh **
2977e014a838Sdanielk1977 **     SRT_Set         Store results as keys of table iParm.
2978fef5208cSdrh **
297982c3d636Sdrh **     SRT_Union       Store results as a key in a temporary table iParm
298082c3d636Sdrh **
29814b11c6d3Sjplyon **     SRT_Except      Remove results from the temporary table iParm.
2982c4a3c779Sdrh **
2983c4a3c779Sdrh **     SRT_Table       Store results in temporary table iParm
29849bb61fe7Sdrh **
2985e78e8284Sdrh ** The table above is incomplete.  Additional eDist value have be added
2986e78e8284Sdrh ** since this comment was written.  See the selectInnerLoop() function for
2987e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings.
2988e78e8284Sdrh **
29899bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
29909bb61fe7Sdrh ** encountered, then an appropriate error message is left in
29919bb61fe7Sdrh ** pParse->zErrMsg.
29929bb61fe7Sdrh **
29939bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
29949bb61fe7Sdrh ** calling function needs to do that.
29951b2e0329Sdrh **
29961b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
29971b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
29981b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
29991b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
30001b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
30011b2e0329Sdrh ** can be changed.
3002e78e8284Sdrh **
3003e78e8284Sdrh ** Example 1:   The meaning of the pParent parameter.
3004e78e8284Sdrh **
3005e78e8284Sdrh **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
3006e78e8284Sdrh **    \                      \_______ subquery _______/        /
3007e78e8284Sdrh **     \                                                      /
3008e78e8284Sdrh **      \____________________ outer query ___________________/
3009e78e8284Sdrh **
3010e78e8284Sdrh ** This routine is called for the outer query first.   For that call,
3011e78e8284Sdrh ** pParent will be NULL.  During the processing of the outer query, this
3012e78e8284Sdrh ** routine is called recursively to handle the subquery.  For the recursive
3013e78e8284Sdrh ** call, pParent will point to the outer query.  Because the subquery is
3014e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will
3015e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.)
30169bb61fe7Sdrh */
30174adee20fSdanielk1977 int sqlite3Select(
3018cce7d176Sdrh   Parse *pParse,         /* The parser context */
30199bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
3020e78e8284Sdrh   int eDest,             /* How to dispose of the results */
3021e78e8284Sdrh   int iParm,             /* A parameter used by the eDest disposal method */
3022832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
3023832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
302484ac9d02Sdanielk1977   int *pParentAgg,       /* True if pParent uses aggregate functions */
3025b3bce662Sdanielk1977   char *aff              /* If eDest is SRT_Union, the affinity string */
3026cce7d176Sdrh ){
302713449892Sdrh   int i, j;              /* Loop counters */
302813449892Sdrh   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
302913449892Sdrh   Vdbe *v;               /* The virtual machine under construction */
3030b3bce662Sdanielk1977   int isAgg;             /* True for select lists like "count(*)" */
3031a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
3032ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
30339bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
30349bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
30352282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
30362282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
303719a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
303819a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
30391d83f052Sdrh   int rc = 1;            /* Value to return from this function */
3040b9bb7c18Sdrh   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
304113449892Sdrh   AggInfo sAggInfo;      /* Information used by aggregate queries */
3042ec7429aeSdrh   int iEnd;              /* Address of the end of the query */
304317435752Sdrh   sqlite3 *db;           /* The database connection */
30449bb61fe7Sdrh 
304517435752Sdrh   db = pParse->db;
304617435752Sdrh   if( p==0 || db->mallocFailed || pParse->nErr ){
30476f7adc8aSdrh     return 1;
30486f7adc8aSdrh   }
30494adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
305013449892Sdrh   memset(&sAggInfo, 0, sizeof(sAggInfo));
3051daffd0e5Sdrh 
30529a99334dSdrh   pOrderBy = p->pOrderBy;
30539a99334dSdrh   if( IgnorableOrderby(eDest) ){
30549a99334dSdrh     p->pOrderBy = 0;
30559a99334dSdrh   }
30569a99334dSdrh   if( sqlite3SelectResolve(pParse, p, 0) ){
30579a99334dSdrh     goto select_end;
30589a99334dSdrh   }
30599a99334dSdrh   p->pOrderBy = pOrderBy;
30609a99334dSdrh 
3061b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
306282c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
306382c3d636Sdrh   */
306482c3d636Sdrh   if( p->pPrior ){
30650342b1f5Sdrh     if( p->pRightmost==0 ){
30661e281291Sdrh       Select *pLoop, *pRight = 0;
30670325d873Sdrh       int cnt = 0;
30680325d873Sdrh       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
30690342b1f5Sdrh         pLoop->pRightmost = p;
30701e281291Sdrh         pLoop->pNext = pRight;
30711e281291Sdrh         pRight = pLoop;
30720342b1f5Sdrh       }
30730325d873Sdrh       if( SQLITE_MAX_COMPOUND_SELECT>0 && cnt>SQLITE_MAX_COMPOUND_SELECT ){
30740325d873Sdrh         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
30750325d873Sdrh         return 1;
30760325d873Sdrh       }
30770342b1f5Sdrh     }
307884ac9d02Sdanielk1977     return multiSelect(pParse, p, eDest, iParm, aff);
307982c3d636Sdrh   }
3080b7f9164eSdrh #endif
308182c3d636Sdrh 
308282c3d636Sdrh   /* Make local copies of the parameters for this query.
308382c3d636Sdrh   */
30849bb61fe7Sdrh   pTabList = p->pSrc;
30859bb61fe7Sdrh   pWhere = p->pWhere;
30862282792aSdrh   pGroupBy = p->pGroupBy;
30872282792aSdrh   pHaving = p->pHaving;
3088b3bce662Sdanielk1977   isAgg = p->isAgg;
308919a775c2Sdrh   isDistinct = p->isDistinct;
3090b3bce662Sdanielk1977   pEList = p->pEList;
3091b3bce662Sdanielk1977   if( pEList==0 ) goto select_end;
30929bb61fe7Sdrh 
30939bb61fe7Sdrh   /*
30949bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
30959bb61fe7Sdrh   ** errors before this routine starts.
30969bb61fe7Sdrh   */
30971d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
3098cce7d176Sdrh 
30992282792aSdrh   /* If writing to memory or generating a set
31002282792aSdrh   ** only a single column may be output.
310119a775c2Sdrh   */
310293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
3103e305f43fSdrh   if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){
31041d83f052Sdrh     goto select_end;
310519a775c2Sdrh   }
310693758c8dSdanielk1977 #endif
310719a775c2Sdrh 
3108c926afbcSdrh   /* ORDER BY is ignored for some destinations.
31092282792aSdrh   */
311013449892Sdrh   if( IgnorableOrderby(eDest) ){
3111acd4c695Sdrh     pOrderBy = 0;
31122282792aSdrh   }
31132282792aSdrh 
3114d820cb1bSdrh   /* Begin generating code.
3115d820cb1bSdrh   */
31164adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
3117d820cb1bSdrh   if( v==0 ) goto select_end;
3118d820cb1bSdrh 
3119d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
3120d820cb1bSdrh   */
312151522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3122ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
3123742f947bSdanielk1977     const char *zSavedAuthContext = 0;
3124c31c2eb8Sdrh     int needRestoreContext;
312513449892Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
3126c31c2eb8Sdrh 
31271787ccabSdanielk1977     if( pItem->pSelect==0 || pItem->isPopulated ) continue;
312813449892Sdrh     if( pItem->zName!=0 ){
31295cf590c1Sdrh       zSavedAuthContext = pParse->zAuthContext;
313013449892Sdrh       pParse->zAuthContext = pItem->zName;
3131c31c2eb8Sdrh       needRestoreContext = 1;
3132c31c2eb8Sdrh     }else{
3133c31c2eb8Sdrh       needRestoreContext = 0;
31345cf590c1Sdrh     }
3135e6a58a4eSdanielk1977 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
3136fc976065Sdanielk1977     /* Increment Parse.nHeight by the height of the largest expression
3137fc976065Sdanielk1977     ** tree refered to by this, the parent select. The child select
3138fc976065Sdanielk1977     ** may contain expression trees of at most
3139fc976065Sdanielk1977     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
3140fc976065Sdanielk1977     ** more conservative than necessary, but much easier than enforcing
3141fc976065Sdanielk1977     ** an exact limit.
3142fc976065Sdanielk1977     */
3143fc976065Sdanielk1977     pParse->nHeight += sqlite3SelectExprHeight(p);
3144fc976065Sdanielk1977 #endif
3145b9bb7c18Sdrh     sqlite3Select(pParse, pItem->pSelect, SRT_EphemTab,
314613449892Sdrh                  pItem->iCursor, p, i, &isAgg, 0);
3147cfa063b3Sdrh     if( db->mallocFailed ){
3148cfa063b3Sdrh       goto select_end;
3149cfa063b3Sdrh     }
3150e6a58a4eSdanielk1977 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
3151fc976065Sdanielk1977     pParse->nHeight -= sqlite3SelectExprHeight(p);
3152fc976065Sdanielk1977 #endif
3153c31c2eb8Sdrh     if( needRestoreContext ){
31545cf590c1Sdrh       pParse->zAuthContext = zSavedAuthContext;
31555cf590c1Sdrh     }
3156832508b7Sdrh     pTabList = p->pSrc;
3157832508b7Sdrh     pWhere = p->pWhere;
315813449892Sdrh     if( !IgnorableOrderby(eDest) ){
3159832508b7Sdrh       pOrderBy = p->pOrderBy;
3160acd4c695Sdrh     }
3161832508b7Sdrh     pGroupBy = p->pGroupBy;
3162832508b7Sdrh     pHaving = p->pHaving;
3163832508b7Sdrh     isDistinct = p->isDistinct;
31641b2e0329Sdrh   }
316551522cd3Sdrh #endif
31661b2e0329Sdrh 
31676e17529eSdrh   /* Check for the special case of a min() or max() function by itself
31686e17529eSdrh   ** in the result set.
31696e17529eSdrh   */
31706e17529eSdrh   if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
31716e17529eSdrh     rc = 0;
31726e17529eSdrh     goto select_end;
31736e17529eSdrh   }
31746e17529eSdrh 
31751b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
31761b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
31771b2e0329Sdrh   */
3178b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
31791b2e0329Sdrh   if( pParent && pParentAgg &&
318017435752Sdrh       flattenSubquery(db, pParent, parentTab, *pParentAgg, isAgg) ){
31811b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
3182b3bce662Sdanielk1977     goto select_end;
31831b2e0329Sdrh   }
3184b7f9164eSdrh #endif
3185832508b7Sdrh 
31860318d441Sdanielk1977   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
31870318d441Sdanielk1977   ** GROUP BY may use an index, DISTINCT never does.
31883c4809a2Sdanielk1977   */
31893c4809a2Sdanielk1977   if( p->isDistinct && !p->isAgg && !p->pGroupBy ){
31903c4809a2Sdanielk1977     p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
31913c4809a2Sdanielk1977     pGroupBy = p->pGroupBy;
31923c4809a2Sdanielk1977     p->isDistinct = 0;
31933c4809a2Sdanielk1977     isDistinct = 0;
31943c4809a2Sdanielk1977   }
31953c4809a2Sdanielk1977 
31968b4c40d8Sdrh   /* If there is an ORDER BY clause, then this sorting
31978b4c40d8Sdrh   ** index might end up being unused if the data can be
31989d2985c7Sdrh   ** extracted in pre-sorted order.  If that is the case, then the
3199b9bb7c18Sdrh   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
32009d2985c7Sdrh   ** we figure out that the sorting index is not needed.  The addrSortIndex
32019d2985c7Sdrh   ** variable is used to facilitate that change.
32027cedc8d4Sdanielk1977   */
32037cedc8d4Sdanielk1977   if( pOrderBy ){
32040342b1f5Sdrh     KeyInfo *pKeyInfo;
32057cedc8d4Sdanielk1977     if( pParse->nErr ){
32067cedc8d4Sdanielk1977       goto select_end;
32077cedc8d4Sdanielk1977     }
32080342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
32099d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
3210b9bb7c18Sdrh     p->addrOpenEphm[2] = addrSortIndex =
32111e31e0b2Sdrh       sqlite3VdbeOp3(v, OP_OpenEphemeral, pOrderBy->iECursor, pOrderBy->nExpr+2,                     (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
32129d2985c7Sdrh   }else{
32139d2985c7Sdrh     addrSortIndex = -1;
32147cedc8d4Sdanielk1977   }
32157cedc8d4Sdanielk1977 
32162d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
32172d0794e3Sdrh   */
3218b9bb7c18Sdrh   if( eDest==SRT_EphemTab ){
3219b9bb7c18Sdrh     sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, pEList->nExpr);
32202d0794e3Sdrh   }
32212d0794e3Sdrh 
3222f42bacc2Sdrh   /* Set the limiter.
3223f42bacc2Sdrh   */
3224f42bacc2Sdrh   iEnd = sqlite3VdbeMakeLabel(v);
3225f42bacc2Sdrh   computeLimitRegisters(pParse, p, iEnd);
3226f42bacc2Sdrh 
3227dece1a84Sdrh   /* Open a virtual index to use for the distinct set.
3228cce7d176Sdrh   */
322919a775c2Sdrh   if( isDistinct ){
32300342b1f5Sdrh     KeyInfo *pKeyInfo;
32313c4809a2Sdanielk1977     assert( isAgg || pGroupBy );
3232832508b7Sdrh     distinct = pParse->nTab++;
32330342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
3234b9bb7c18Sdrh     sqlite3VdbeOp3(v, OP_OpenEphemeral, distinct, 0,
32350342b1f5Sdrh                         (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
3236832508b7Sdrh   }else{
3237832508b7Sdrh     distinct = -1;
3238efb7251dSdrh   }
3239832508b7Sdrh 
324013449892Sdrh   /* Aggregate and non-aggregate queries are handled differently */
324113449892Sdrh   if( !isAgg && pGroupBy==0 ){
324213449892Sdrh     /* This case is for non-aggregate queries
324313449892Sdrh     ** Begin the database scan
3244832508b7Sdrh     */
324513449892Sdrh     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy);
32461d83f052Sdrh     if( pWInfo==0 ) goto select_end;
3247cce7d176Sdrh 
3248b9bb7c18Sdrh     /* If sorting index that was created by a prior OP_OpenEphemeral
3249b9bb7c18Sdrh     ** instruction ended up not being needed, then change the OP_OpenEphemeral
32509d2985c7Sdrh     ** into an OP_Noop.
32519d2985c7Sdrh     */
32529d2985c7Sdrh     if( addrSortIndex>=0 && pOrderBy==0 ){
3253f8875400Sdrh       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
3254b9bb7c18Sdrh       p->addrOpenEphm[2] = -1;
32559d2985c7Sdrh     }
32569d2985c7Sdrh 
325713449892Sdrh     /* Use the standard inner loop
3258cce7d176Sdrh     */
32593c4809a2Sdanielk1977     assert(!isDistinct);
32603c4809a2Sdanielk1977     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, eDest,
326184ac9d02Sdanielk1977                     iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
32621d83f052Sdrh        goto select_end;
3263cce7d176Sdrh     }
32642282792aSdrh 
3265cce7d176Sdrh     /* End the database scan loop.
3266cce7d176Sdrh     */
32674adee20fSdanielk1977     sqlite3WhereEnd(pWInfo);
326813449892Sdrh   }else{
326913449892Sdrh     /* This is the processing for aggregate queries */
327013449892Sdrh     NameContext sNC;    /* Name context for processing aggregate information */
327113449892Sdrh     int iAMem;          /* First Mem address for storing current GROUP BY */
327213449892Sdrh     int iBMem;          /* First Mem address for previous GROUP BY */
327313449892Sdrh     int iUseFlag;       /* Mem address holding flag indicating that at least
327413449892Sdrh                         ** one row of the input to the aggregator has been
327513449892Sdrh                         ** processed */
327613449892Sdrh     int iAbortFlag;     /* Mem address which causes query abort if positive */
327713449892Sdrh     int groupBySort;    /* Rows come from source in GROUP BY order */
3278cce7d176Sdrh 
327913449892Sdrh 
328013449892Sdrh     /* The following variables hold addresses or labels for parts of the
328113449892Sdrh     ** virtual machine program we are putting together */
328213449892Sdrh     int addrOutputRow;      /* Start of subroutine that outputs a result row */
328313449892Sdrh     int addrSetAbort;       /* Set the abort flag and return */
328413449892Sdrh     int addrInitializeLoop; /* Start of code that initializes the input loop */
328513449892Sdrh     int addrTopOfLoop;      /* Top of the input loop */
328613449892Sdrh     int addrGroupByChange;  /* Code that runs when any GROUP BY term changes */
328713449892Sdrh     int addrProcessRow;     /* Code to process a single input row */
328813449892Sdrh     int addrEnd;            /* End of all processing */
3289b9bb7c18Sdrh     int addrSortingIdx;     /* The OP_OpenEphemeral for the sorting index */
3290e313382eSdrh     int addrReset;          /* Subroutine for resetting the accumulator */
329113449892Sdrh 
329213449892Sdrh     addrEnd = sqlite3VdbeMakeLabel(v);
329313449892Sdrh 
329413449892Sdrh     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
329513449892Sdrh     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
329613449892Sdrh     ** SELECT statement.
32972282792aSdrh     */
329813449892Sdrh     memset(&sNC, 0, sizeof(sNC));
329913449892Sdrh     sNC.pParse = pParse;
330013449892Sdrh     sNC.pSrcList = pTabList;
330113449892Sdrh     sNC.pAggInfo = &sAggInfo;
330213449892Sdrh     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
33039d2985c7Sdrh     sAggInfo.pGroupBy = pGroupBy;
330413449892Sdrh     if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){
33051d83f052Sdrh       goto select_end;
33062282792aSdrh     }
330713449892Sdrh     if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){
330813449892Sdrh       goto select_end;
33092282792aSdrh     }
331013449892Sdrh     if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
331113449892Sdrh       goto select_end;
331213449892Sdrh     }
331313449892Sdrh     sAggInfo.nAccumulator = sAggInfo.nColumn;
331413449892Sdrh     for(i=0; i<sAggInfo.nFunc; i++){
331513449892Sdrh       if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
331613449892Sdrh         goto select_end;
331713449892Sdrh       }
331813449892Sdrh     }
331917435752Sdrh     if( db->mallocFailed ) goto select_end;
332013449892Sdrh 
332113449892Sdrh     /* Processing for aggregates with GROUP BY is very different and
33223c4809a2Sdanielk1977     ** much more complex than aggregates without a GROUP BY.
332313449892Sdrh     */
332413449892Sdrh     if( pGroupBy ){
332513449892Sdrh       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
332613449892Sdrh 
332713449892Sdrh       /* Create labels that we will be needing
332813449892Sdrh       */
332913449892Sdrh 
333013449892Sdrh       addrInitializeLoop = sqlite3VdbeMakeLabel(v);
333113449892Sdrh       addrGroupByChange = sqlite3VdbeMakeLabel(v);
333213449892Sdrh       addrProcessRow = sqlite3VdbeMakeLabel(v);
333313449892Sdrh 
333413449892Sdrh       /* If there is a GROUP BY clause we might need a sorting index to
333513449892Sdrh       ** implement it.  Allocate that sorting index now.  If it turns out
3336b9bb7c18Sdrh       ** that we do not need it after all, the OpenEphemeral instruction
333713449892Sdrh       ** will be converted into a Noop.
333813449892Sdrh       */
333913449892Sdrh       sAggInfo.sortingIdx = pParse->nTab++;
334013449892Sdrh       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
334113449892Sdrh       addrSortingIdx =
3342b9bb7c18Sdrh           sqlite3VdbeOp3(v, OP_OpenEphemeral, sAggInfo.sortingIdx,
334313449892Sdrh                          sAggInfo.nSortingColumn,
334413449892Sdrh                          (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
334513449892Sdrh 
334613449892Sdrh       /* Initialize memory locations used by GROUP BY aggregate processing
334713449892Sdrh       */
334813449892Sdrh       iUseFlag = pParse->nMem++;
334913449892Sdrh       iAbortFlag = pParse->nMem++;
335013449892Sdrh       iAMem = pParse->nMem;
335113449892Sdrh       pParse->nMem += pGroupBy->nExpr;
335213449892Sdrh       iBMem = pParse->nMem;
335313449892Sdrh       pParse->nMem += pGroupBy->nExpr;
3354d654be80Sdrh       sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag);
3355de29e3e9Sdrh       VdbeComment((v, "# clear abort flag"));
3356d654be80Sdrh       sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag);
3357de29e3e9Sdrh       VdbeComment((v, "# indicate accumulator empty"));
335813449892Sdrh       sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop);
335913449892Sdrh 
336013449892Sdrh       /* Generate a subroutine that outputs a single row of the result
336113449892Sdrh       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
336213449892Sdrh       ** is less than or equal to zero, the subroutine is a no-op.  If
336313449892Sdrh       ** the processing calls for the query to abort, this subroutine
336413449892Sdrh       ** increments the iAbortFlag memory location before returning in
336513449892Sdrh       ** order to signal the caller to abort.
336613449892Sdrh       */
336713449892Sdrh       addrSetAbort = sqlite3VdbeCurrentAddr(v);
3368de29e3e9Sdrh       sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag);
3369de29e3e9Sdrh       VdbeComment((v, "# set abort flag"));
337013449892Sdrh       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
337113449892Sdrh       addrOutputRow = sqlite3VdbeCurrentAddr(v);
337213449892Sdrh       sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2);
3373de29e3e9Sdrh       VdbeComment((v, "# Groupby result generator entry point"));
337413449892Sdrh       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
337513449892Sdrh       finalizeAggFunctions(pParse, &sAggInfo);
337613449892Sdrh       if( pHaving ){
337713449892Sdrh         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1);
337813449892Sdrh       }
337913449892Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
338013449892Sdrh                            distinct, eDest, iParm,
338113449892Sdrh                            addrOutputRow+1, addrSetAbort, aff);
338213449892Sdrh       if( rc ){
338313449892Sdrh         goto select_end;
338413449892Sdrh       }
338513449892Sdrh       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
3386de29e3e9Sdrh       VdbeComment((v, "# end groupby result generator"));
338713449892Sdrh 
3388e313382eSdrh       /* Generate a subroutine that will reset the group-by accumulator
3389e313382eSdrh       */
3390e313382eSdrh       addrReset = sqlite3VdbeCurrentAddr(v);
3391e313382eSdrh       resetAccumulator(pParse, &sAggInfo);
3392e313382eSdrh       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
3393e313382eSdrh 
339413449892Sdrh       /* Begin a loop that will extract all source rows in GROUP BY order.
339513449892Sdrh       ** This might involve two separate loops with an OP_Sort in between, or
339613449892Sdrh       ** it might be a single loop that uses an index to extract information
339713449892Sdrh       ** in the right order to begin with.
339813449892Sdrh       */
339913449892Sdrh       sqlite3VdbeResolveLabel(v, addrInitializeLoop);
3400e313382eSdrh       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
340113449892Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy);
34025360ad34Sdrh       if( pWInfo==0 ) goto select_end;
340313449892Sdrh       if( pGroupBy==0 ){
340413449892Sdrh         /* The optimizer is able to deliver rows in group by order so
3405b9bb7c18Sdrh         ** we do not have to sort.  The OP_OpenEphemeral table will be
340613449892Sdrh         ** cancelled later because we still need to use the pKeyInfo
340713449892Sdrh         */
340813449892Sdrh         pGroupBy = p->pGroupBy;
340913449892Sdrh         groupBySort = 0;
341013449892Sdrh       }else{
341113449892Sdrh         /* Rows are coming out in undetermined order.  We have to push
341213449892Sdrh         ** each row into a sorting index, terminate the first loop,
341313449892Sdrh         ** then loop over the sorting index in order to get the output
341413449892Sdrh         ** in sorted order
341513449892Sdrh         */
341613449892Sdrh         groupBySort = 1;
341713449892Sdrh         sqlite3ExprCodeExprList(pParse, pGroupBy);
341813449892Sdrh         sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0);
341913449892Sdrh         j = pGroupBy->nExpr+1;
342013449892Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
342113449892Sdrh           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
342213449892Sdrh           if( pCol->iSorterColumn<j ) continue;
3423945498f3Sdrh           sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn, pCol->iTable);
342413449892Sdrh           j++;
342513449892Sdrh         }
342613449892Sdrh         sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0);
342713449892Sdrh         sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0);
342813449892Sdrh         sqlite3WhereEnd(pWInfo);
342997571957Sdrh         sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
3430de29e3e9Sdrh         VdbeComment((v, "# GROUP BY sort"));
343113449892Sdrh         sAggInfo.useSortingIdx = 1;
343213449892Sdrh       }
343313449892Sdrh 
343413449892Sdrh       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
343513449892Sdrh       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
343613449892Sdrh       ** Then compare the current GROUP BY terms against the GROUP BY terms
343713449892Sdrh       ** from the previous row currently stored in a0, a1, a2...
343813449892Sdrh       */
343913449892Sdrh       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
344013449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
344113449892Sdrh         if( groupBySort ){
344213449892Sdrh           sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j);
344313449892Sdrh         }else{
344413449892Sdrh           sAggInfo.directMode = 1;
344513449892Sdrh           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr);
344613449892Sdrh         }
344713449892Sdrh         sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1);
344813449892Sdrh       }
344913449892Sdrh       for(j=pGroupBy->nExpr-1; j>=0; j--){
345013449892Sdrh         if( j<pGroupBy->nExpr-1 ){
345113449892Sdrh           sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0);
345213449892Sdrh         }
345313449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0);
345413449892Sdrh         if( j==0 ){
3455e313382eSdrh           sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow);
345613449892Sdrh         }else{
34574f686238Sdrh           sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange);
345813449892Sdrh         }
345913449892Sdrh         sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ);
346013449892Sdrh       }
346113449892Sdrh 
346213449892Sdrh       /* Generate code that runs whenever the GROUP BY changes.
346313449892Sdrh       ** Change in the GROUP BY are detected by the previous code
346413449892Sdrh       ** block.  If there were no changes, this block is skipped.
346513449892Sdrh       **
346613449892Sdrh       ** This code copies current group by terms in b0,b1,b2,...
346713449892Sdrh       ** over to a0,a1,a2.  It then calls the output subroutine
346813449892Sdrh       ** and resets the aggregate accumulator registers in preparation
346913449892Sdrh       ** for the next GROUP BY batch.
347013449892Sdrh       */
347113449892Sdrh       sqlite3VdbeResolveLabel(v, addrGroupByChange);
347213449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
3473d654be80Sdrh         sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j);
347413449892Sdrh       }
347513449892Sdrh       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
3476de29e3e9Sdrh       VdbeComment((v, "# output one row"));
347713449892Sdrh       sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd);
3478de29e3e9Sdrh       VdbeComment((v, "# check abort flag"));
3479e313382eSdrh       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
3480de29e3e9Sdrh       VdbeComment((v, "# reset accumulator"));
348113449892Sdrh 
348213449892Sdrh       /* Update the aggregate accumulators based on the content of
348313449892Sdrh       ** the current row
348413449892Sdrh       */
348513449892Sdrh       sqlite3VdbeResolveLabel(v, addrProcessRow);
348613449892Sdrh       updateAccumulator(pParse, &sAggInfo);
3487de29e3e9Sdrh       sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag);
3488de29e3e9Sdrh       VdbeComment((v, "# indicate data in accumulator"));
348913449892Sdrh 
349013449892Sdrh       /* End of the loop
349113449892Sdrh       */
349213449892Sdrh       if( groupBySort ){
349313449892Sdrh         sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
349413449892Sdrh       }else{
349513449892Sdrh         sqlite3WhereEnd(pWInfo);
3496f8875400Sdrh         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
349713449892Sdrh       }
349813449892Sdrh 
349913449892Sdrh       /* Output the final row of result
350013449892Sdrh       */
350113449892Sdrh       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
3502de29e3e9Sdrh       VdbeComment((v, "# output final row"));
350313449892Sdrh 
350413449892Sdrh     } /* endif pGroupBy */
350513449892Sdrh     else {
350613449892Sdrh       /* This case runs if the aggregate has no GROUP BY clause.  The
350713449892Sdrh       ** processing is much simpler since there is only a single row
350813449892Sdrh       ** of output.
350913449892Sdrh       */
351013449892Sdrh       resetAccumulator(pParse, &sAggInfo);
351113449892Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
35125360ad34Sdrh       if( pWInfo==0 ) goto select_end;
351313449892Sdrh       updateAccumulator(pParse, &sAggInfo);
351413449892Sdrh       sqlite3WhereEnd(pWInfo);
351513449892Sdrh       finalizeAggFunctions(pParse, &sAggInfo);
351613449892Sdrh       pOrderBy = 0;
35175774b806Sdrh       if( pHaving ){
35185774b806Sdrh         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1);
35195774b806Sdrh       }
352013449892Sdrh       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
352113449892Sdrh                       eDest, iParm, addrEnd, addrEnd, aff);
352213449892Sdrh     }
352313449892Sdrh     sqlite3VdbeResolveLabel(v, addrEnd);
352413449892Sdrh 
352513449892Sdrh   } /* endif aggregate query */
35262282792aSdrh 
3527cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
3528cce7d176Sdrh   ** and send them to the callback one by one.
3529cce7d176Sdrh   */
3530cce7d176Sdrh   if( pOrderBy ){
3531cdd536f0Sdrh     generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
3532cce7d176Sdrh   }
35336a535340Sdrh 
353493758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
3535f620b4e2Sdrh   /* If this was a subquery, we have now converted the subquery into a
35361787ccabSdanielk1977   ** temporary table.  So set the SrcList_item.isPopulated flag to prevent
35371787ccabSdanielk1977   ** this subquery from being evaluated again and to force the use of
35381787ccabSdanielk1977   ** the temporary table.
3539f620b4e2Sdrh   */
3540f620b4e2Sdrh   if( pParent ){
3541f620b4e2Sdrh     assert( pParent->pSrc->nSrc>parentTab );
3542f620b4e2Sdrh     assert( pParent->pSrc->a[parentTab].pSelect==p );
35431787ccabSdanielk1977     pParent->pSrc->a[parentTab].isPopulated = 1;
3544f620b4e2Sdrh   }
354593758c8dSdanielk1977 #endif
3546f620b4e2Sdrh 
3547ec7429aeSdrh   /* Jump here to skip this query
3548ec7429aeSdrh   */
3549ec7429aeSdrh   sqlite3VdbeResolveLabel(v, iEnd);
3550ec7429aeSdrh 
35511d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
35521d83f052Sdrh   ** to indicate no errors.
35531d83f052Sdrh   */
35541d83f052Sdrh   rc = 0;
35551d83f052Sdrh 
35561d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
35571d83f052Sdrh   ** successful coding of the SELECT.
35581d83f052Sdrh   */
35591d83f052Sdrh select_end:
3560955de52cSdanielk1977 
3561955de52cSdanielk1977   /* Identify column names if we will be using them in a callback.  This
3562955de52cSdanielk1977   ** step is skipped if the output is going to some other destination.
3563955de52cSdanielk1977   */
3564955de52cSdanielk1977   if( rc==SQLITE_OK && eDest==SRT_Callback ){
3565955de52cSdanielk1977     generateColumnNames(pParse, pTabList, pEList);
3566955de52cSdanielk1977   }
3567955de52cSdanielk1977 
356817435752Sdrh   sqlite3_free(sAggInfo.aCol);
356917435752Sdrh   sqlite3_free(sAggInfo.aFunc);
35701d83f052Sdrh   return rc;
3571cce7d176Sdrh }
3572485f0039Sdrh 
357377a2a5e7Sdrh #if defined(SQLITE_DEBUG)
3574485f0039Sdrh /*
3575485f0039Sdrh *******************************************************************************
3576485f0039Sdrh ** The following code is used for testing and debugging only.  The code
3577485f0039Sdrh ** that follows does not appear in normal builds.
3578485f0039Sdrh **
3579485f0039Sdrh ** These routines are used to print out the content of all or part of a
3580485f0039Sdrh ** parse structures such as Select or Expr.  Such printouts are useful
3581485f0039Sdrh ** for helping to understand what is happening inside the code generator
3582485f0039Sdrh ** during the execution of complex SELECT statements.
3583485f0039Sdrh **
3584485f0039Sdrh ** These routine are not called anywhere from within the normal
3585485f0039Sdrh ** code base.  Then are intended to be called from within the debugger
3586485f0039Sdrh ** or from temporary "printf" statements inserted for debugging.
3587485f0039Sdrh */
3588485f0039Sdrh void sqlite3PrintExpr(Expr *p){
3589485f0039Sdrh   if( p->token.z && p->token.n>0 ){
3590485f0039Sdrh     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
3591485f0039Sdrh   }else{
3592485f0039Sdrh     sqlite3DebugPrintf("(%d", p->op);
3593485f0039Sdrh   }
3594485f0039Sdrh   if( p->pLeft ){
3595485f0039Sdrh     sqlite3DebugPrintf(" ");
3596485f0039Sdrh     sqlite3PrintExpr(p->pLeft);
3597485f0039Sdrh   }
3598485f0039Sdrh   if( p->pRight ){
3599485f0039Sdrh     sqlite3DebugPrintf(" ");
3600485f0039Sdrh     sqlite3PrintExpr(p->pRight);
3601485f0039Sdrh   }
3602485f0039Sdrh   sqlite3DebugPrintf(")");
3603485f0039Sdrh }
3604485f0039Sdrh void sqlite3PrintExprList(ExprList *pList){
3605485f0039Sdrh   int i;
3606485f0039Sdrh   for(i=0; i<pList->nExpr; i++){
3607485f0039Sdrh     sqlite3PrintExpr(pList->a[i].pExpr);
3608485f0039Sdrh     if( i<pList->nExpr-1 ){
3609485f0039Sdrh       sqlite3DebugPrintf(", ");
3610485f0039Sdrh     }
3611485f0039Sdrh   }
3612485f0039Sdrh }
3613485f0039Sdrh void sqlite3PrintSelect(Select *p, int indent){
3614485f0039Sdrh   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
3615485f0039Sdrh   sqlite3PrintExprList(p->pEList);
3616485f0039Sdrh   sqlite3DebugPrintf("\n");
3617485f0039Sdrh   if( p->pSrc ){
3618485f0039Sdrh     char *zPrefix;
3619485f0039Sdrh     int i;
3620485f0039Sdrh     zPrefix = "FROM";
3621485f0039Sdrh     for(i=0; i<p->pSrc->nSrc; i++){
3622485f0039Sdrh       struct SrcList_item *pItem = &p->pSrc->a[i];
3623485f0039Sdrh       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
3624485f0039Sdrh       zPrefix = "";
3625485f0039Sdrh       if( pItem->pSelect ){
3626485f0039Sdrh         sqlite3DebugPrintf("(\n");
3627485f0039Sdrh         sqlite3PrintSelect(pItem->pSelect, indent+10);
3628485f0039Sdrh         sqlite3DebugPrintf("%*s)", indent+8, "");
3629485f0039Sdrh       }else if( pItem->zName ){
3630485f0039Sdrh         sqlite3DebugPrintf("%s", pItem->zName);
3631485f0039Sdrh       }
3632485f0039Sdrh       if( pItem->pTab ){
3633485f0039Sdrh         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
3634485f0039Sdrh       }
3635485f0039Sdrh       if( pItem->zAlias ){
3636485f0039Sdrh         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
3637485f0039Sdrh       }
3638485f0039Sdrh       if( i<p->pSrc->nSrc-1 ){
3639485f0039Sdrh         sqlite3DebugPrintf(",");
3640485f0039Sdrh       }
3641485f0039Sdrh       sqlite3DebugPrintf("\n");
3642485f0039Sdrh     }
3643485f0039Sdrh   }
3644485f0039Sdrh   if( p->pWhere ){
3645485f0039Sdrh     sqlite3DebugPrintf("%*s WHERE ", indent, "");
3646485f0039Sdrh     sqlite3PrintExpr(p->pWhere);
3647485f0039Sdrh     sqlite3DebugPrintf("\n");
3648485f0039Sdrh   }
3649485f0039Sdrh   if( p->pGroupBy ){
3650485f0039Sdrh     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
3651485f0039Sdrh     sqlite3PrintExprList(p->pGroupBy);
3652485f0039Sdrh     sqlite3DebugPrintf("\n");
3653485f0039Sdrh   }
3654485f0039Sdrh   if( p->pHaving ){
3655485f0039Sdrh     sqlite3DebugPrintf("%*s HAVING ", indent, "");
3656485f0039Sdrh     sqlite3PrintExpr(p->pHaving);
3657485f0039Sdrh     sqlite3DebugPrintf("\n");
3658485f0039Sdrh   }
3659485f0039Sdrh   if( p->pOrderBy ){
3660485f0039Sdrh     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
3661485f0039Sdrh     sqlite3PrintExprList(p->pOrderBy);
3662485f0039Sdrh     sqlite3DebugPrintf("\n");
3663485f0039Sdrh   }
3664485f0039Sdrh }
3665485f0039Sdrh /* End of the structure debug printing code
3666485f0039Sdrh *****************************************************************************/
3667485f0039Sdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
3668