xref: /sqlite-3.40.0/src/select.c (revision e6a58a4e)
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*e6a58a4eSdanielk1977 ** $Id: select.c,v 1.359 2007/08/31 17:42:48 danielk1977 Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19315555caSdrh 
20cce7d176Sdrh /*
21eda639e1Sdrh ** Delete all the content of a Select structure but do not deallocate
22eda639e1Sdrh ** the select structure itself.
23eda639e1Sdrh */
24f0113000Sdanielk1977 static void clearSelect(Select *p){
25eda639e1Sdrh   sqlite3ExprListDelete(p->pEList);
26eda639e1Sdrh   sqlite3SrcListDelete(p->pSrc);
27eda639e1Sdrh   sqlite3ExprDelete(p->pWhere);
28eda639e1Sdrh   sqlite3ExprListDelete(p->pGroupBy);
29eda639e1Sdrh   sqlite3ExprDelete(p->pHaving);
30eda639e1Sdrh   sqlite3ExprListDelete(p->pOrderBy);
31eda639e1Sdrh   sqlite3SelectDelete(p->pPrior);
32eda639e1Sdrh   sqlite3ExprDelete(p->pLimit);
33eda639e1Sdrh   sqlite3ExprDelete(p->pOffset);
34eda639e1Sdrh }
35eda639e1Sdrh 
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   }
25117435752Sdrh   pE = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
252206f3d96Sdrh   if( pE ){
253206f3d96Sdrh     *ppExpr = pE;
254206f3d96Sdrh   }
255ad2d8307Sdrh }
256ad2d8307Sdrh 
257ad2d8307Sdrh /*
2581f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
25922d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the
26022d6a53aSdrh ** expression.
2611cc093c2Sdrh **
262e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
2631cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
2641f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
2651f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
2661f16230bSdrh ** WHERE clause during join processing but we need to remember that they
2671f16230bSdrh ** originated in the ON or USING clause.
26822d6a53aSdrh **
26922d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the
27022d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not
27122d6a53aSdrh ** explicitly mentioned in the expression.  That information is needed
27222d6a53aSdrh ** for cases like this:
27322d6a53aSdrh **
27422d6a53aSdrh **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
27522d6a53aSdrh **
27622d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5
27722d6a53aSdrh ** term until after the t2 loop of the join.  In that way, a
27822d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
27922d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately
28022d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in
28122d6a53aSdrh ** the output, which is incorrect.
2821cc093c2Sdrh */
28322d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){
2841cc093c2Sdrh   while( p ){
2851f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
28622d6a53aSdrh     p->iRightJoinTable = iTable;
28722d6a53aSdrh     setJoinExpr(p->pLeft, iTable);
2881cc093c2Sdrh     p = p->pRight;
2891cc093c2Sdrh   }
2901cc093c2Sdrh }
2911cc093c2Sdrh 
2921cc093c2Sdrh /*
293ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
294ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
295ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
296ad2d8307Sdrh **
29791bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure.
29891bb0eedSdrh ** The left most table is the first entry in Select.pSrc.  The right-most
29991bb0eedSdrh ** table is the last entry.  The join operator is held in the entry to
30091bb0eedSdrh ** the left.  Thus entry 0 contains the join operator for the join between
30191bb0eedSdrh ** entries 0 and 1.  Any ON or USING clauses associated with the join are
30291bb0eedSdrh ** also attached to the left entry.
30391bb0eedSdrh **
304ad2d8307Sdrh ** This routine returns the number of errors encountered.
305ad2d8307Sdrh */
306ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
30791bb0eedSdrh   SrcList *pSrc;                  /* All tables in the FROM clause */
30891bb0eedSdrh   int i, j;                       /* Loop counters */
30991bb0eedSdrh   struct SrcList_item *pLeft;     /* Left table being joined */
31091bb0eedSdrh   struct SrcList_item *pRight;    /* Right table being joined */
311ad2d8307Sdrh 
31291bb0eedSdrh   pSrc = p->pSrc;
31391bb0eedSdrh   pLeft = &pSrc->a[0];
31491bb0eedSdrh   pRight = &pLeft[1];
31591bb0eedSdrh   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
31691bb0eedSdrh     Table *pLeftTab = pLeft->pTab;
31791bb0eedSdrh     Table *pRightTab = pRight->pTab;
31891bb0eedSdrh 
31991bb0eedSdrh     if( pLeftTab==0 || pRightTab==0 ) continue;
320ad2d8307Sdrh 
321ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
322ad2d8307Sdrh     ** every column that the two tables have in common.
323ad2d8307Sdrh     */
32461dfc31dSdrh     if( pRight->jointype & JT_NATURAL ){
32561dfc31dSdrh       if( pRight->pOn || pRight->pUsing ){
3264adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
327ad2d8307Sdrh            "an ON or USING clause", 0);
328ad2d8307Sdrh         return 1;
329ad2d8307Sdrh       }
33091bb0eedSdrh       for(j=0; j<pLeftTab->nCol; j++){
33191bb0eedSdrh         char *zName = pLeftTab->aCol[j].zName;
33291bb0eedSdrh         if( columnIndex(pRightTab, zName)>=0 ){
3331e536953Sdanielk1977           addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
33422d6a53aSdrh                               pRightTab, pRight->zAlias,
33522d6a53aSdrh                               pRight->iCursor, &p->pWhere);
33622d6a53aSdrh 
337ad2d8307Sdrh         }
338ad2d8307Sdrh       }
339ad2d8307Sdrh     }
340ad2d8307Sdrh 
341ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
342ad2d8307Sdrh     */
34361dfc31dSdrh     if( pRight->pOn && pRight->pUsing ){
3444adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
345da93d238Sdrh         "clauses in the same join");
346ad2d8307Sdrh       return 1;
347ad2d8307Sdrh     }
348ad2d8307Sdrh 
349ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
35091bb0eedSdrh     ** an AND operator.
351ad2d8307Sdrh     */
35261dfc31dSdrh     if( pRight->pOn ){
35361dfc31dSdrh       setJoinExpr(pRight->pOn, pRight->iCursor);
35417435752Sdrh       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
35561dfc31dSdrh       pRight->pOn = 0;
356ad2d8307Sdrh     }
357ad2d8307Sdrh 
358ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
359ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
360ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
361ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
362ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
363ad2d8307Sdrh     ** not contained in both tables to be joined.
364ad2d8307Sdrh     */
36561dfc31dSdrh     if( pRight->pUsing ){
36661dfc31dSdrh       IdList *pList = pRight->pUsing;
367ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
36891bb0eedSdrh         char *zName = pList->a[j].zName;
36991bb0eedSdrh         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
3704adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
37191bb0eedSdrh             "not present in both tables", zName);
372ad2d8307Sdrh           return 1;
373ad2d8307Sdrh         }
3741e536953Sdanielk1977         addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
37522d6a53aSdrh                             pRightTab, pRight->zAlias,
37622d6a53aSdrh                             pRight->iCursor, &p->pWhere);
377ad2d8307Sdrh       }
378ad2d8307Sdrh     }
379ad2d8307Sdrh   }
380ad2d8307Sdrh   return 0;
381ad2d8307Sdrh }
382ad2d8307Sdrh 
383ad2d8307Sdrh /*
384c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
385c926afbcSdrh ** stack into the sorter.
386c926afbcSdrh */
387d59ba6ceSdrh static void pushOntoSorter(
388d59ba6ceSdrh   Parse *pParse,         /* Parser context */
389d59ba6ceSdrh   ExprList *pOrderBy,    /* The ORDER BY clause */
390d59ba6ceSdrh   Select *pSelect        /* The whole SELECT statement */
391d59ba6ceSdrh ){
392d59ba6ceSdrh   Vdbe *v = pParse->pVdbe;
393c182d163Sdrh   sqlite3ExprCodeExprList(pParse, pOrderBy);
3949d2985c7Sdrh   sqlite3VdbeAddOp(v, OP_Sequence, pOrderBy->iECursor, 0);
3954db38a70Sdrh   sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr + 1, 0);
3964db38a70Sdrh   sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0);
3979d2985c7Sdrh   sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iECursor, 0);
398d59ba6ceSdrh   if( pSelect->iLimit>=0 ){
39915007a99Sdrh     int addr1, addr2;
40015007a99Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_IfMemZero, pSelect->iLimit+1, 0);
40115007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemIncr, -1, pSelect->iLimit+1);
40215007a99Sdrh     addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
403d59ba6ceSdrh     sqlite3VdbeJumpHere(v, addr1);
404d59ba6ceSdrh     sqlite3VdbeAddOp(v, OP_Last, pOrderBy->iECursor, 0);
405d59ba6ceSdrh     sqlite3VdbeAddOp(v, OP_Delete, pOrderBy->iECursor, 0);
40615007a99Sdrh     sqlite3VdbeJumpHere(v, addr2);
407d59ba6ceSdrh     pSelect->iLimit = -1;
408d59ba6ceSdrh   }
409c926afbcSdrh }
410c926afbcSdrh 
411c926afbcSdrh /*
412ec7429aeSdrh ** Add code to implement the OFFSET
413ea48eb2eSdrh */
414ec7429aeSdrh static void codeOffset(
415bab39e13Sdrh   Vdbe *v,          /* Generate code into this VM */
416ea48eb2eSdrh   Select *p,        /* The SELECT statement being coded */
417ea48eb2eSdrh   int iContinue,    /* Jump here to skip the current record */
418ea48eb2eSdrh   int nPop          /* Number of times to pop stack when jumping */
419ea48eb2eSdrh ){
42013449892Sdrh   if( p->iOffset>=0 && iContinue!=0 ){
42115007a99Sdrh     int addr;
42215007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iOffset);
4233a129247Sdrh     addr = sqlite3VdbeAddOp(v, OP_IfMemNeg, p->iOffset, 0);
424ea48eb2eSdrh     if( nPop>0 ){
425ea48eb2eSdrh       sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
426ea48eb2eSdrh     }
427ea48eb2eSdrh     sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
428ad6d9460Sdrh     VdbeComment((v, "# skip OFFSET records"));
42915007a99Sdrh     sqlite3VdbeJumpHere(v, addr);
430ea48eb2eSdrh   }
431ea48eb2eSdrh }
432ea48eb2eSdrh 
433ea48eb2eSdrh /*
434c99130fdSdrh ** Add code that will check to make sure the top N elements of the
435c99130fdSdrh ** stack are distinct.  iTab is a sorting index that holds previously
436c99130fdSdrh ** seen combinations of the N values.  A new entry is made in iTab
437c99130fdSdrh ** if the current N values are new.
438c99130fdSdrh **
439f8875400Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the
440c99130fdSdrh ** stack if the top N elements are not distinct.
441c99130fdSdrh */
442c99130fdSdrh static void codeDistinct(
443c99130fdSdrh   Vdbe *v,           /* Generate code into this VM */
444c99130fdSdrh   int iTab,          /* A sorting index used to test for distinctness */
445c99130fdSdrh   int addrRepeat,    /* Jump to here if not distinct */
446f8875400Sdrh   int N              /* The top N elements of the stack must be distinct */
447c99130fdSdrh ){
448c99130fdSdrh   sqlite3VdbeAddOp(v, OP_MakeRecord, -N, 0);
449c99130fdSdrh   sqlite3VdbeAddOp(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3);
450f8875400Sdrh   sqlite3VdbeAddOp(v, OP_Pop, N+1, 0);
451c99130fdSdrh   sqlite3VdbeAddOp(v, OP_Goto, 0, addrRepeat);
452c99130fdSdrh   VdbeComment((v, "# skip indistinct records"));
453c99130fdSdrh   sqlite3VdbeAddOp(v, OP_IdxInsert, iTab, 0);
454c99130fdSdrh }
455c99130fdSdrh 
456e305f43fSdrh /*
457e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression
458e305f43fSdrh ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
459e305f43fSdrh ** column.  We do this in a subroutine because the error occurs in multiple
460e305f43fSdrh ** places.
461e305f43fSdrh */
462e305f43fSdrh static int checkForMultiColumnSelectError(Parse *pParse, int eDest, int nExpr){
463e305f43fSdrh   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
464e305f43fSdrh     sqlite3ErrorMsg(pParse, "only a single result allowed for "
465e305f43fSdrh        "a SELECT that is part of an expression");
466e305f43fSdrh     return 1;
467e305f43fSdrh   }else{
468e305f43fSdrh     return 0;
469e305f43fSdrh   }
470e305f43fSdrh }
471c99130fdSdrh 
472c99130fdSdrh /*
4732282792aSdrh ** This routine generates the code for the inside of the inner loop
4742282792aSdrh ** of a SELECT.
47582c3d636Sdrh **
47638640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
47738640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
47838640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
47938640e15Sdrh ** datatypes for each column.
4802282792aSdrh */
4812282792aSdrh static int selectInnerLoop(
4822282792aSdrh   Parse *pParse,          /* The parser context */
483df199a25Sdrh   Select *p,              /* The complete select statement being coded */
4842282792aSdrh   ExprList *pEList,       /* List of values being extracted */
48582c3d636Sdrh   int srcTab,             /* Pull data from this table */
486967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
4872282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
4882282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
4892282792aSdrh   int eDest,              /* How to dispose of the results */
4902282792aSdrh   int iParm,              /* An argument to the disposal method */
4912282792aSdrh   int iContinue,          /* Jump here to continue with next row */
49284ac9d02Sdanielk1977   int iBreak,             /* Jump here to break out of the inner loop */
49384ac9d02Sdanielk1977   char *aff               /* affinity string if eDest is SRT_Union */
4942282792aSdrh ){
4952282792aSdrh   Vdbe *v = pParse->pVdbe;
4962282792aSdrh   int i;
497ea48eb2eSdrh   int hasDistinct;        /* True if the DISTINCT keyword is present */
49838640e15Sdrh 
499daffd0e5Sdrh   if( v==0 ) return 0;
50038640e15Sdrh   assert( pEList!=0 );
5012282792aSdrh 
502df199a25Sdrh   /* If there was a LIMIT clause on the SELECT statement, then do the check
503df199a25Sdrh   ** to see if this row should be output.
504df199a25Sdrh   */
505eda639e1Sdrh   hasDistinct = distinct>=0 && pEList->nExpr>0;
506ea48eb2eSdrh   if( pOrderBy==0 && !hasDistinct ){
507ec7429aeSdrh     codeOffset(v, p, iContinue, 0);
508df199a25Sdrh   }
509df199a25Sdrh 
510967e8b73Sdrh   /* Pull the requested columns.
5112282792aSdrh   */
51238640e15Sdrh   if( nColumn>0 ){
513967e8b73Sdrh     for(i=0; i<nColumn; i++){
5144adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
51582c3d636Sdrh     }
51638640e15Sdrh   }else{
51738640e15Sdrh     nColumn = pEList->nExpr;
518c182d163Sdrh     sqlite3ExprCodeExprList(pParse, pEList);
51982c3d636Sdrh   }
5202282792aSdrh 
521daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
522daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
523daffd0e5Sdrh   ** part of the result.
5242282792aSdrh   */
525ea48eb2eSdrh   if( hasDistinct ){
526f8875400Sdrh     assert( pEList!=0 );
527f8875400Sdrh     assert( pEList->nExpr==nColumn );
528f8875400Sdrh     codeDistinct(v, distinct, iContinue, nColumn);
529ea48eb2eSdrh     if( pOrderBy==0 ){
530ec7429aeSdrh       codeOffset(v, p, iContinue, nColumn);
531ea48eb2eSdrh     }
5322282792aSdrh   }
53382c3d636Sdrh 
534e305f43fSdrh   if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){
535e305f43fSdrh     return 0;
536e305f43fSdrh   }
537e305f43fSdrh 
538c926afbcSdrh   switch( eDest ){
53982c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
54082c3d636Sdrh     ** table iParm.
5412282792aSdrh     */
54213449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
543c926afbcSdrh     case SRT_Union: {
544f8875400Sdrh       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
54513449892Sdrh       if( aff ){
54684ac9d02Sdanielk1977         sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
54713449892Sdrh       }
548f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0);
549c926afbcSdrh       break;
550c926afbcSdrh     }
55182c3d636Sdrh 
55282c3d636Sdrh     /* Construct a record from the query result, but instead of
55382c3d636Sdrh     ** saving that record, use it as a key to delete elements from
55482c3d636Sdrh     ** the temporary table iParm.
55582c3d636Sdrh     */
556c926afbcSdrh     case SRT_Except: {
5570bd1f4eaSdrh       int addr;
558f8875400Sdrh       addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
55984ac9d02Sdanielk1977       sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
5604adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
5614adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
562c926afbcSdrh       break;
563c926afbcSdrh     }
5645338a5f7Sdanielk1977 #endif
5655338a5f7Sdanielk1977 
5665338a5f7Sdanielk1977     /* Store the result as data using a unique key.
5675338a5f7Sdanielk1977     */
5685338a5f7Sdanielk1977     case SRT_Table:
569b9bb7c18Sdrh     case SRT_EphemTab: {
5705338a5f7Sdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
5715338a5f7Sdanielk1977       if( pOrderBy ){
572d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
5735338a5f7Sdanielk1977       }else{
574f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
5755338a5f7Sdanielk1977         sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
576e4d90813Sdrh         sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
5775338a5f7Sdanielk1977       }
5785338a5f7Sdanielk1977       break;
5795338a5f7Sdanielk1977     }
5802282792aSdrh 
58193758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
5822282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
5832282792aSdrh     ** then there should be a single item on the stack.  Write this
5842282792aSdrh     ** item into the set table with bogus data.
5852282792aSdrh     */
586c926afbcSdrh     case SRT_Set: {
5874adee20fSdanielk1977       int addr1 = sqlite3VdbeCurrentAddr(v);
58852b36cabSdrh       int addr2;
589e014a838Sdanielk1977 
590967e8b73Sdrh       assert( nColumn==1 );
5914adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
5924adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
5934adee20fSdanielk1977       addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
5946c1426fdSdrh       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr,(iParm>>16)&0xff);
595c926afbcSdrh       if( pOrderBy ){
596de941c60Sdrh         /* At first glance you would think we could optimize out the
597de941c60Sdrh         ** ORDER BY in this case since the order of entries in the set
598de941c60Sdrh         ** does not matter.  But there might be a LIMIT clause, in which
599de941c60Sdrh         ** case the order does matter */
600d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
601c926afbcSdrh       }else{
6026c1426fdSdrh         sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
603f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
604c926afbcSdrh       }
605d654be80Sdrh       sqlite3VdbeJumpHere(v, addr2);
606c926afbcSdrh       break;
607c926afbcSdrh     }
60882c3d636Sdrh 
609504b6989Sdrh     /* If any row exist in the result set, record that fact and abort.
610ec7429aeSdrh     */
611ec7429aeSdrh     case SRT_Exists: {
612ec7429aeSdrh       sqlite3VdbeAddOp(v, OP_MemInt, 1, iParm);
613ec7429aeSdrh       sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
614ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
615ec7429aeSdrh       break;
616ec7429aeSdrh     }
617ec7429aeSdrh 
6182282792aSdrh     /* If this is a scalar select that is part of an expression, then
6192282792aSdrh     ** store the results in the appropriate memory cell and break out
6202282792aSdrh     ** of the scan loop.
6212282792aSdrh     */
622c926afbcSdrh     case SRT_Mem: {
623967e8b73Sdrh       assert( nColumn==1 );
624c926afbcSdrh       if( pOrderBy ){
625d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
626c926afbcSdrh       }else{
6274adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
628ec7429aeSdrh         /* The LIMIT clause will jump out of the loop for us */
629c926afbcSdrh       }
630c926afbcSdrh       break;
631c926afbcSdrh     }
63293758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
6332282792aSdrh 
634c182d163Sdrh     /* Send the data to the callback function or to a subroutine.  In the
635c182d163Sdrh     ** case of a subroutine, the subroutine itself is responsible for
636c182d163Sdrh     ** popping the data from the stack.
637f46f905aSdrh     */
638c182d163Sdrh     case SRT_Subroutine:
6399d2985c7Sdrh     case SRT_Callback: {
640f46f905aSdrh       if( pOrderBy ){
641ce665cf6Sdrh         sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
642d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
643c182d163Sdrh       }else if( eDest==SRT_Subroutine ){
6444adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
645c182d163Sdrh       }else{
646c182d163Sdrh         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
647ac82fcf5Sdrh       }
648142e30dfSdrh       break;
649142e30dfSdrh     }
650142e30dfSdrh 
6516a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER)
652d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
653d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
654d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
655d7489c39Sdrh     ** about the actual results of the select.
656d7489c39Sdrh     */
657c926afbcSdrh     default: {
658f46f905aSdrh       assert( eDest==SRT_Discard );
6594adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
660c926afbcSdrh       break;
661c926afbcSdrh     }
66293758c8dSdanielk1977 #endif
663c926afbcSdrh   }
664ec7429aeSdrh 
665ec7429aeSdrh   /* Jump to the end of the loop if the LIMIT is reached.
666ec7429aeSdrh   */
667ec7429aeSdrh   if( p->iLimit>=0 && pOrderBy==0 ){
66815007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
669ec7429aeSdrh     sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, iBreak);
670ec7429aeSdrh   }
67182c3d636Sdrh   return 0;
67282c3d636Sdrh }
67382c3d636Sdrh 
67482c3d636Sdrh /*
675dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records
676dece1a84Sdrh ** the collating sequence for each expression in that expression list.
677dece1a84Sdrh **
6780342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
6790342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to
6800342b1f5Sdrh ** implement that clause.  If the ExprList is the result set of a SELECT
6810342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual
6820342b1f5Sdrh ** index to implement a DISTINCT test.
6830342b1f5Sdrh **
684dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
685dece1a84Sdrh ** function is responsible for seeing that this structure is eventually
686dece1a84Sdrh ** freed.  Add the KeyInfo structure to the P3 field of an opcode using
687dece1a84Sdrh ** P3_KEYINFO_HANDOFF is the usual way of dealing with this.
688dece1a84Sdrh */
689dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
690dece1a84Sdrh   sqlite3 *db = pParse->db;
691dece1a84Sdrh   int nExpr;
692dece1a84Sdrh   KeyInfo *pInfo;
693dece1a84Sdrh   struct ExprList_item *pItem;
694dece1a84Sdrh   int i;
695dece1a84Sdrh 
696dece1a84Sdrh   nExpr = pList->nExpr;
69717435752Sdrh   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
698dece1a84Sdrh   if( pInfo ){
6992646da7eSdrh     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
700dece1a84Sdrh     pInfo->nField = nExpr;
70114db2665Sdanielk1977     pInfo->enc = ENC(db);
702dece1a84Sdrh     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
703dece1a84Sdrh       CollSeq *pColl;
704dece1a84Sdrh       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
705dece1a84Sdrh       if( !pColl ){
706dece1a84Sdrh         pColl = db->pDfltColl;
707dece1a84Sdrh       }
708dece1a84Sdrh       pInfo->aColl[i] = pColl;
709dece1a84Sdrh       pInfo->aSortOrder[i] = pItem->sortOrder;
710dece1a84Sdrh     }
711dece1a84Sdrh   }
712dece1a84Sdrh   return pInfo;
713dece1a84Sdrh }
714dece1a84Sdrh 
715dece1a84Sdrh 
716dece1a84Sdrh /*
717d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
718d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
719d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
720d8bc7086Sdrh ** routine generates the code needed to do that.
721d8bc7086Sdrh */
722c926afbcSdrh static void generateSortTail(
723cdd536f0Sdrh   Parse *pParse,   /* Parsing context */
724c926afbcSdrh   Select *p,       /* The SELECT statement */
725c926afbcSdrh   Vdbe *v,         /* Generate code into this VDBE */
726c926afbcSdrh   int nColumn,     /* Number of columns of data */
727c926afbcSdrh   int eDest,       /* Write the sorted results here */
728c926afbcSdrh   int iParm        /* Optional parameter associated with eDest */
729c926afbcSdrh ){
7300342b1f5Sdrh   int brk = sqlite3VdbeMakeLabel(v);
7310342b1f5Sdrh   int cont = sqlite3VdbeMakeLabel(v);
732d8bc7086Sdrh   int addr;
7330342b1f5Sdrh   int iTab;
73461fc595fSdrh   int pseudoTab = 0;
7350342b1f5Sdrh   ExprList *pOrderBy = p->pOrderBy;
736ffbc3088Sdrh 
7379d2985c7Sdrh   iTab = pOrderBy->iECursor;
738cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
739cdd536f0Sdrh     pseudoTab = pParse->nTab++;
740cdd536f0Sdrh     sqlite3VdbeAddOp(v, OP_OpenPseudo, pseudoTab, 0);
741cdd536f0Sdrh     sqlite3VdbeAddOp(v, OP_SetNumColumns, pseudoTab, nColumn);
742cdd536f0Sdrh   }
7430342b1f5Sdrh   addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk);
744ec7429aeSdrh   codeOffset(v, p, cont, 0);
745cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
746cdd536f0Sdrh     sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
747cdd536f0Sdrh   }
7484db38a70Sdrh   sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1);
749c926afbcSdrh   switch( eDest ){
750c926afbcSdrh     case SRT_Table:
751b9bb7c18Sdrh     case SRT_EphemTab: {
752f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
7534adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
754e4d90813Sdrh       sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
755c926afbcSdrh       break;
756c926afbcSdrh     }
75793758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
758c926afbcSdrh     case SRT_Set: {
759c926afbcSdrh       assert( nColumn==1 );
7604adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
7614adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
7624adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
7636c1426fdSdrh       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
764f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
765c926afbcSdrh       break;
766c926afbcSdrh     }
767c926afbcSdrh     case SRT_Mem: {
768c926afbcSdrh       assert( nColumn==1 );
7694adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
770ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
771c926afbcSdrh       break;
772c926afbcSdrh     }
77393758c8dSdanielk1977 #endif
774ce665cf6Sdrh     case SRT_Callback:
775ac82fcf5Sdrh     case SRT_Subroutine: {
776ac82fcf5Sdrh       int i;
777cdd536f0Sdrh       sqlite3VdbeAddOp(v, OP_Insert, pseudoTab, 0);
778ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
779cdd536f0Sdrh         sqlite3VdbeAddOp(v, OP_Column, pseudoTab, i);
780ac82fcf5Sdrh       }
781ce665cf6Sdrh       if( eDest==SRT_Callback ){
782ce665cf6Sdrh         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
783ce665cf6Sdrh       }else{
7844adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
785ce665cf6Sdrh       }
786ac82fcf5Sdrh       break;
787ac82fcf5Sdrh     }
788c926afbcSdrh     default: {
789f46f905aSdrh       /* Do nothing */
790c926afbcSdrh       break;
791c926afbcSdrh     }
792c926afbcSdrh   }
793ec7429aeSdrh 
794ec7429aeSdrh   /* Jump to the end of the loop when the LIMIT is reached
795ec7429aeSdrh   */
796ec7429aeSdrh   if( p->iLimit>=0 ){
79715007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
798ec7429aeSdrh     sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, brk);
799ec7429aeSdrh   }
800ec7429aeSdrh 
801ec7429aeSdrh   /* The bottom of the loop
802ec7429aeSdrh   */
8030342b1f5Sdrh   sqlite3VdbeResolveLabel(v, cont);
8040342b1f5Sdrh   sqlite3VdbeAddOp(v, OP_Next, iTab, addr);
8050342b1f5Sdrh   sqlite3VdbeResolveLabel(v, brk);
806cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
807cdd536f0Sdrh     sqlite3VdbeAddOp(v, OP_Close, pseudoTab, 0);
808cdd536f0Sdrh   }
809cdd536f0Sdrh 
810d8bc7086Sdrh }
811d8bc7086Sdrh 
812d8bc7086Sdrh /*
813517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
814517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
815e78e8284Sdrh **
816955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the
817955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The
818955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
819955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The
820955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is
821955de52cSdanielk1977 ** considered a column by this function.
822e78e8284Sdrh **
823955de52cSdanielk1977 **   SELECT col FROM tbl;
824955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl;
825955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl);
826955de52cSdanielk1977 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
827955de52cSdanielk1977 **
828955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL.
829fcb78a49Sdrh */
830955de52cSdanielk1977 static const char *columnType(
831955de52cSdanielk1977   NameContext *pNC,
832955de52cSdanielk1977   Expr *pExpr,
833955de52cSdanielk1977   const char **pzOriginDb,
834955de52cSdanielk1977   const char **pzOriginTab,
835955de52cSdanielk1977   const char **pzOriginCol
836955de52cSdanielk1977 ){
837955de52cSdanielk1977   char const *zType = 0;
838955de52cSdanielk1977   char const *zOriginDb = 0;
839955de52cSdanielk1977   char const *zOriginTab = 0;
840955de52cSdanielk1977   char const *zOriginCol = 0;
841517eb646Sdanielk1977   int j;
842b3bce662Sdanielk1977   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
8435338a5f7Sdanielk1977 
84400e279d9Sdanielk1977   switch( pExpr->op ){
84530bcf5dbSdrh     case TK_AGG_COLUMN:
84600e279d9Sdanielk1977     case TK_COLUMN: {
847955de52cSdanielk1977       /* The expression is a column. Locate the table the column is being
848955de52cSdanielk1977       ** extracted from in NameContext.pSrcList. This table may be real
849955de52cSdanielk1977       ** database table or a subquery.
850955de52cSdanielk1977       */
851955de52cSdanielk1977       Table *pTab = 0;            /* Table structure column is extracted from */
852955de52cSdanielk1977       Select *pS = 0;             /* Select the column is extracted from */
853955de52cSdanielk1977       int iCol = pExpr->iColumn;  /* Index of column in pTab */
854b3bce662Sdanielk1977       while( pNC && !pTab ){
855b3bce662Sdanielk1977         SrcList *pTabList = pNC->pSrcList;
856b3bce662Sdanielk1977         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
857b3bce662Sdanielk1977         if( j<pTabList->nSrc ){
8586a3ea0e6Sdrh           pTab = pTabList->a[j].pTab;
859955de52cSdanielk1977           pS = pTabList->a[j].pSelect;
860b3bce662Sdanielk1977         }else{
861b3bce662Sdanielk1977           pNC = pNC->pNext;
862b3bce662Sdanielk1977         }
863b3bce662Sdanielk1977       }
864955de52cSdanielk1977 
8657e62779aSdrh       if( pTab==0 ){
8667e62779aSdrh         /* FIX ME:
8677e62779aSdrh         ** This can occurs if you have something like "SELECT new.x;" inside
8687e62779aSdrh         ** a trigger.  In other words, if you reference the special "new"
8697e62779aSdrh         ** table in the result set of a select.  We do not have a good way
8707e62779aSdrh         ** to find the actual table type, so call it "TEXT".  This is really
8717e62779aSdrh         ** something of a bug, but I do not know how to fix it.
8727e62779aSdrh         **
8737e62779aSdrh         ** This code does not produce the correct answer - it just prevents
8747e62779aSdrh         ** a segfault.  See ticket #1229.
8757e62779aSdrh         */
8767e62779aSdrh         zType = "TEXT";
8777e62779aSdrh         break;
8787e62779aSdrh       }
879955de52cSdanielk1977 
880b3bce662Sdanielk1977       assert( pTab );
881955de52cSdanielk1977       if( pS ){
882955de52cSdanielk1977         /* The "table" is actually a sub-select or a view in the FROM clause
883955de52cSdanielk1977         ** of the SELECT statement. Return the declaration type and origin
884955de52cSdanielk1977         ** data for the result-set column of the sub-select.
885955de52cSdanielk1977         */
886955de52cSdanielk1977         if( iCol>=0 && iCol<pS->pEList->nExpr ){
887955de52cSdanielk1977           /* If iCol is less than zero, then the expression requests the
888955de52cSdanielk1977           ** rowid of the sub-select or view. This expression is legal (see
889955de52cSdanielk1977           ** test case misc2.2.2) - it always evaluates to NULL.
890955de52cSdanielk1977           */
891955de52cSdanielk1977           NameContext sNC;
892955de52cSdanielk1977           Expr *p = pS->pEList->a[iCol].pExpr;
893955de52cSdanielk1977           sNC.pSrcList = pS->pSrc;
894955de52cSdanielk1977           sNC.pNext = 0;
895955de52cSdanielk1977           sNC.pParse = pNC->pParse;
896955de52cSdanielk1977           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
897955de52cSdanielk1977         }
8984b2688abSdanielk1977       }else if( pTab->pSchema ){
899955de52cSdanielk1977         /* A real table */
900955de52cSdanielk1977         assert( !pS );
901fcb78a49Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
902fcb78a49Sdrh         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
903fcb78a49Sdrh         if( iCol<0 ){
904fcb78a49Sdrh           zType = "INTEGER";
905955de52cSdanielk1977           zOriginCol = "rowid";
906fcb78a49Sdrh         }else{
907fcb78a49Sdrh           zType = pTab->aCol[iCol].zType;
908955de52cSdanielk1977           zOriginCol = pTab->aCol[iCol].zName;
909955de52cSdanielk1977         }
910955de52cSdanielk1977         zOriginTab = pTab->zName;
911955de52cSdanielk1977         if( pNC->pParse ){
912955de52cSdanielk1977           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
913955de52cSdanielk1977           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
914955de52cSdanielk1977         }
915fcb78a49Sdrh       }
91600e279d9Sdanielk1977       break;
917736c22b8Sdrh     }
91893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
91900e279d9Sdanielk1977     case TK_SELECT: {
920955de52cSdanielk1977       /* The expression is a sub-select. Return the declaration type and
921955de52cSdanielk1977       ** origin info for the single column in the result set of the SELECT
922955de52cSdanielk1977       ** statement.
923955de52cSdanielk1977       */
924b3bce662Sdanielk1977       NameContext sNC;
92500e279d9Sdanielk1977       Select *pS = pExpr->pSelect;
926955de52cSdanielk1977       Expr *p = pS->pEList->a[0].pExpr;
927955de52cSdanielk1977       sNC.pSrcList = pS->pSrc;
928b3bce662Sdanielk1977       sNC.pNext = pNC;
929955de52cSdanielk1977       sNC.pParse = pNC->pParse;
930955de52cSdanielk1977       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
93100e279d9Sdanielk1977       break;
932fcb78a49Sdrh     }
93393758c8dSdanielk1977 #endif
93400e279d9Sdanielk1977   }
93500e279d9Sdanielk1977 
936955de52cSdanielk1977   if( pzOriginDb ){
937955de52cSdanielk1977     assert( pzOriginTab && pzOriginCol );
938955de52cSdanielk1977     *pzOriginDb = zOriginDb;
939955de52cSdanielk1977     *pzOriginTab = zOriginTab;
940955de52cSdanielk1977     *pzOriginCol = zOriginCol;
941955de52cSdanielk1977   }
942517eb646Sdanielk1977   return zType;
943517eb646Sdanielk1977 }
944517eb646Sdanielk1977 
945517eb646Sdanielk1977 /*
946517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
947517eb646Sdanielk1977 ** in the result set.
948517eb646Sdanielk1977 */
949517eb646Sdanielk1977 static void generateColumnTypes(
950517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
951517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
952517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
953517eb646Sdanielk1977 ){
954517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
955517eb646Sdanielk1977   int i;
956b3bce662Sdanielk1977   NameContext sNC;
957b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
958955de52cSdanielk1977   sNC.pParse = pParse;
959517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
960517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
961955de52cSdanielk1977     const char *zOrigDb = 0;
962955de52cSdanielk1977     const char *zOrigTab = 0;
963955de52cSdanielk1977     const char *zOrigCol = 0;
964955de52cSdanielk1977     const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
965955de52cSdanielk1977 
9664b1ae99dSdanielk1977     /* The vdbe must make it's own copy of the column-type and other
9674b1ae99dSdanielk1977     ** column specific strings, in case the schema is reset before this
9684b1ae99dSdanielk1977     ** virtual machine is deleted.
969fbcd585fSdanielk1977     */
9704b1ae99dSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P3_TRANSIENT);
9714b1ae99dSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P3_TRANSIENT);
9724b1ae99dSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P3_TRANSIENT);
9734b1ae99dSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P3_TRANSIENT);
974fcb78a49Sdrh   }
975fcb78a49Sdrh }
976fcb78a49Sdrh 
977fcb78a49Sdrh /*
978fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
979fcb78a49Sdrh ** in the result set.  This information is used to provide the
980fcabd464Sdrh ** azCol[] values in the callback.
98182c3d636Sdrh */
982832508b7Sdrh static void generateColumnNames(
983832508b7Sdrh   Parse *pParse,      /* Parser context */
984ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
985832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
986832508b7Sdrh ){
987d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
9886a3ea0e6Sdrh   int i, j;
9899bb575fdSdrh   sqlite3 *db = pParse->db;
990fcabd464Sdrh   int fullNames, shortNames;
991fcabd464Sdrh 
992fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN
9933cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
9943cf86063Sdanielk1977   if( pParse->explain ){
99561de0d1bSdanielk1977     return;
9963cf86063Sdanielk1977   }
9975338a5f7Sdanielk1977 #endif
9983cf86063Sdanielk1977 
999d6502758Sdrh   assert( v!=0 );
100017435752Sdrh   if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
1001d8bc7086Sdrh   pParse->colNamesSet = 1;
1002fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
1003fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
100422322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
100582c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
100682c3d636Sdrh     Expr *p;
10075a38705eSdrh     p = pEList->a[i].pExpr;
10085a38705eSdrh     if( p==0 ) continue;
100982c3d636Sdrh     if( pEList->a[i].zName ){
101082c3d636Sdrh       char *zName = pEList->a[i].zName;
1011955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
101282c3d636Sdrh       continue;
101382c3d636Sdrh     }
1014fa173a76Sdrh     if( p->op==TK_COLUMN && pTabList ){
10156a3ea0e6Sdrh       Table *pTab;
101697665873Sdrh       char *zCol;
10178aff1015Sdrh       int iCol = p->iColumn;
10186a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
10196a3ea0e6Sdrh       assert( j<pTabList->nSrc );
10206a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
10218aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
102297665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1023b1363206Sdrh       if( iCol<0 ){
102447a6db2bSdrh         zCol = "rowid";
1025b1363206Sdrh       }else{
1026b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
1027b1363206Sdrh       }
1028fcabd464Sdrh       if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
1029955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
1030fcabd464Sdrh       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
103182c3d636Sdrh         char *zName = 0;
103282c3d636Sdrh         char *zTab;
103382c3d636Sdrh 
10346a3ea0e6Sdrh         zTab = pTabList->a[j].zAlias;
1035fcabd464Sdrh         if( fullNames || zTab==0 ) zTab = pTab->zName;
1036f93339deSdrh         sqlite3SetString(&zName, zTab, ".", zCol, (char*)0);
1037955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P3_DYNAMIC);
103882c3d636Sdrh       }else{
1039955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
104082c3d636Sdrh       }
10416977fea8Sdrh     }else if( p->span.z && p->span.z[0] ){
1042955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
10433cf86063Sdanielk1977       /* sqlite3VdbeCompressSpace(v, addr); */
10441bee3d7bSdrh     }else{
10451bee3d7bSdrh       char zName[30];
10461bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
10475bb3eb9bSdrh       sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1);
1048955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0);
104982c3d636Sdrh     }
105082c3d636Sdrh   }
105176d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
10525080aaa7Sdrh }
105382c3d636Sdrh 
105493758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
105582c3d636Sdrh /*
1056d8bc7086Sdrh ** Name of the connection operator, used for error messages.
1057d8bc7086Sdrh */
1058d8bc7086Sdrh static const char *selectOpName(int id){
1059d8bc7086Sdrh   char *z;
1060d8bc7086Sdrh   switch( id ){
1061d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
1062d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
1063d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
1064d8bc7086Sdrh     default:           z = "UNION";       break;
1065d8bc7086Sdrh   }
1066d8bc7086Sdrh   return z;
1067d8bc7086Sdrh }
106893758c8dSdanielk1977 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1069d8bc7086Sdrh 
1070d8bc7086Sdrh /*
1071315555caSdrh ** Forward declaration
1072315555caSdrh */
10739b3187e1Sdrh static int prepSelectStmt(Parse*, Select*);
1074315555caSdrh 
1075315555caSdrh /*
107622f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
107722f70c32Sdrh ** the result set of that SELECT.
107822f70c32Sdrh */
10794adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
108022f70c32Sdrh   Table *pTab;
1081b733d037Sdrh   int i, j;
108222f70c32Sdrh   ExprList *pEList;
1083290c1948Sdrh   Column *aCol, *pCol;
108417435752Sdrh   sqlite3 *db = pParse->db;
108522f70c32Sdrh 
108692378253Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
10879b3187e1Sdrh   if( prepSelectStmt(pParse, pSelect) ){
108822f70c32Sdrh     return 0;
108922f70c32Sdrh   }
1090142bdf40Sdanielk1977   if( sqlite3SelectResolve(pParse, pSelect, 0) ){
1091142bdf40Sdanielk1977     return 0;
1092142bdf40Sdanielk1977   }
109317435752Sdrh   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
109422f70c32Sdrh   if( pTab==0 ){
109522f70c32Sdrh     return 0;
109622f70c32Sdrh   }
1097ed8a3bb1Sdrh   pTab->nRef = 1;
109817435752Sdrh   pTab->zName = zTabName ? sqlite3DbStrDup(db, zTabName) : 0;
109922f70c32Sdrh   pEList = pSelect->pEList;
110022f70c32Sdrh   pTab->nCol = pEList->nExpr;
1101417be79cSdrh   assert( pTab->nCol>0 );
110217435752Sdrh   pTab->aCol = aCol = sqlite3DbMallocZero(db, sizeof(pTab->aCol[0])*pTab->nCol);
1103290c1948Sdrh   for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
110479d5f63fSdrh     Expr *p, *pR;
1105517eb646Sdanielk1977     char *zType;
110691bb0eedSdrh     char *zName;
11072564ef97Sdrh     int nName;
1108b3bf556eSdanielk1977     CollSeq *pColl;
110979d5f63fSdrh     int cnt;
1110b3bce662Sdanielk1977     NameContext sNC;
111179d5f63fSdrh 
111279d5f63fSdrh     /* Get an appropriate name for the column
111379d5f63fSdrh     */
111479d5f63fSdrh     p = pEList->a[i].pExpr;
1115290c1948Sdrh     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
111691bb0eedSdrh     if( (zName = pEList->a[i].zName)!=0 ){
111779d5f63fSdrh       /* If the column contains an "AS <name>" phrase, use <name> as the name */
111817435752Sdrh       zName = sqlite3DbStrDup(db, zName);
1119517eb646Sdanielk1977     }else if( p->op==TK_DOT
1120b733d037Sdrh               && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
112179d5f63fSdrh       /* For columns of the from A.B use B as the name */
112217435752Sdrh       zName = sqlite3MPrintf(db, "%T", &pR->token);
1123b733d037Sdrh     }else if( p->span.z && p->span.z[0] ){
112479d5f63fSdrh       /* Use the original text of the column expression as its name */
112517435752Sdrh       zName = sqlite3MPrintf(db, "%T", &p->span);
112622f70c32Sdrh     }else{
112779d5f63fSdrh       /* If all else fails, make up a name */
112817435752Sdrh       zName = sqlite3MPrintf(db, "column%d", i+1);
112922f70c32Sdrh     }
11307751940dSdanielk1977     if( !zName || db->mallocFailed ){
11317751940dSdanielk1977       db->mallocFailed = 1;
113217435752Sdrh       sqlite3_free(zName);
1133a04a34ffSdanielk1977       sqlite3DeleteTable(pTab);
1134dd5b2fa5Sdrh       return 0;
1135dd5b2fa5Sdrh     }
11367751940dSdanielk1977     sqlite3Dequote(zName);
113779d5f63fSdrh 
113879d5f63fSdrh     /* Make sure the column name is unique.  If the name is not unique,
113979d5f63fSdrh     ** append a integer to the name so that it becomes unique.
114079d5f63fSdrh     */
11412564ef97Sdrh     nName = strlen(zName);
114279d5f63fSdrh     for(j=cnt=0; j<i; j++){
114379d5f63fSdrh       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
11442564ef97Sdrh         zName[nName] = 0;
11451e536953Sdanielk1977         zName = sqlite3MPrintf(db, "%z:%d", zName, ++cnt);
114679d5f63fSdrh         j = -1;
1147dd5b2fa5Sdrh         if( zName==0 ) break;
114879d5f63fSdrh       }
114979d5f63fSdrh     }
115091bb0eedSdrh     pCol->zName = zName;
1151e014a838Sdanielk1977 
115279d5f63fSdrh     /* Get the typename, type affinity, and collating sequence for the
115379d5f63fSdrh     ** column.
115479d5f63fSdrh     */
1155c43e8be8Sdrh     memset(&sNC, 0, sizeof(sNC));
1156b3bce662Sdanielk1977     sNC.pSrcList = pSelect->pSrc;
115717435752Sdrh     zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
1158290c1948Sdrh     pCol->zType = zType;
1159c60e9b82Sdanielk1977     pCol->affinity = sqlite3ExprAffinity(p);
1160b3bf556eSdanielk1977     pColl = sqlite3ExprCollSeq(pParse, p);
1161b3bf556eSdanielk1977     if( pColl ){
116217435752Sdrh       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
11630202b29eSdanielk1977     }
116422f70c32Sdrh   }
116522f70c32Sdrh   pTab->iPKey = -1;
116622f70c32Sdrh   return pTab;
116722f70c32Sdrh }
116822f70c32Sdrh 
116922f70c32Sdrh /*
11709b3187e1Sdrh ** Prepare a SELECT statement for processing by doing the following
11719b3187e1Sdrh ** things:
1172d8bc7086Sdrh **
11739b3187e1Sdrh **    (1)  Make sure VDBE cursor numbers have been assigned to every
11749b3187e1Sdrh **         element of the FROM clause.
11759b3187e1Sdrh **
11769b3187e1Sdrh **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
11779b3187e1Sdrh **         defines FROM clause.  When views appear in the FROM clause,
117863eb5f29Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
117963eb5f29Sdrh **         that implements the view.  A copy is made of the view's SELECT
118063eb5f29Sdrh **         statement so that we can freely modify or delete that statement
118163eb5f29Sdrh **         without worrying about messing up the presistent representation
118263eb5f29Sdrh **         of the view.
1183d8bc7086Sdrh **
11849b3187e1Sdrh **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
1185ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
1186ad2d8307Sdrh **
11879b3187e1Sdrh **    (4)  Scan the list of columns in the result set (pEList) looking
118854473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
118954473229Sdrh **         If found, expand each "*" to be every column in every table
119054473229Sdrh **         and TABLE.* to be every column in TABLE.
1191d8bc7086Sdrh **
1192d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
1193d8bc7086Sdrh ** in pParse and return non-zero.
1194d8bc7086Sdrh */
11959b3187e1Sdrh static int prepSelectStmt(Parse *pParse, Select *p){
119654473229Sdrh   int i, j, k, rc;
1197ad3cab52Sdrh   SrcList *pTabList;
1198daffd0e5Sdrh   ExprList *pEList;
1199290c1948Sdrh   struct SrcList_item *pFrom;
120017435752Sdrh   sqlite3 *db = pParse->db;
1201daffd0e5Sdrh 
120217435752Sdrh   if( p==0 || p->pSrc==0 || db->mallocFailed ){
12036f7adc8aSdrh     return 1;
12046f7adc8aSdrh   }
1205daffd0e5Sdrh   pTabList = p->pSrc;
1206daffd0e5Sdrh   pEList = p->pEList;
1207d8bc7086Sdrh 
12089b3187e1Sdrh   /* Make sure cursor numbers have been assigned to all entries in
12099b3187e1Sdrh   ** the FROM clause of the SELECT statement.
12109b3187e1Sdrh   */
12119b3187e1Sdrh   sqlite3SrcListAssignCursors(pParse, p->pSrc);
12129b3187e1Sdrh 
12139b3187e1Sdrh   /* Look up every table named in the FROM clause of the select.  If
12149b3187e1Sdrh   ** an entry of the FROM clause is a subquery instead of a table or view,
12159b3187e1Sdrh   ** then create a transient table structure to describe the subquery.
1216d8bc7086Sdrh   */
1217290c1948Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1218f0113000Sdanielk1977     Table *pTab;
12199b3187e1Sdrh     if( pFrom->pTab!=0 ){
12209b3187e1Sdrh       /* This statement has already been prepared.  There is no need
12219b3187e1Sdrh       ** to go further. */
12229b3187e1Sdrh       assert( i==0 );
1223d8bc7086Sdrh       return 0;
1224d8bc7086Sdrh     }
1225290c1948Sdrh     if( pFrom->zName==0 ){
122693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
122722f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
1228290c1948Sdrh       assert( pFrom->pSelect!=0 );
1229290c1948Sdrh       if( pFrom->zAlias==0 ){
123091bb0eedSdrh         pFrom->zAlias =
12311e536953Sdanielk1977           sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pFrom->pSelect);
1232ad2d8307Sdrh       }
1233ed8a3bb1Sdrh       assert( pFrom->pTab==0 );
1234290c1948Sdrh       pFrom->pTab = pTab =
1235290c1948Sdrh         sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
123622f70c32Sdrh       if( pTab==0 ){
1237daffd0e5Sdrh         return 1;
1238daffd0e5Sdrh       }
1239b9bb7c18Sdrh       /* The isEphem flag indicates that the Table structure has been
12405cf590c1Sdrh       ** dynamically allocated and may be freed at any time.  In other words,
12415cf590c1Sdrh       ** pTab is not pointing to a persistent table structure that defines
12425cf590c1Sdrh       ** part of the schema. */
1243b9bb7c18Sdrh       pTab->isEphem = 1;
124493758c8dSdanielk1977 #endif
124522f70c32Sdrh     }else{
1246a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
1247ed8a3bb1Sdrh       assert( pFrom->pTab==0 );
1248290c1948Sdrh       pFrom->pTab = pTab =
1249290c1948Sdrh         sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
1250a76b5dfcSdrh       if( pTab==0 ){
1251d8bc7086Sdrh         return 1;
1252d8bc7086Sdrh       }
1253ed8a3bb1Sdrh       pTab->nRef++;
125493626f48Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
125593626f48Sdanielk1977       if( pTab->pSelect || IsVirtual(pTab) ){
125663eb5f29Sdrh         /* We reach here if the named table is a really a view */
12574adee20fSdanielk1977         if( sqlite3ViewGetColumnNames(pParse, pTab) ){
1258417be79cSdrh           return 1;
1259417be79cSdrh         }
1260290c1948Sdrh         /* If pFrom->pSelect!=0 it means we are dealing with a
126163eb5f29Sdrh         ** view within a view.  The SELECT structure has already been
126263eb5f29Sdrh         ** copied by the outer view so we can skip the copy step here
126363eb5f29Sdrh         ** in the inner view.
126463eb5f29Sdrh         */
1265290c1948Sdrh         if( pFrom->pSelect==0 ){
126617435752Sdrh           pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
1267a76b5dfcSdrh         }
1268d8bc7086Sdrh       }
126993758c8dSdanielk1977 #endif
127022f70c32Sdrh     }
127163eb5f29Sdrh   }
1272d8bc7086Sdrh 
1273ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
1274ad2d8307Sdrh   */
1275ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
1276ad2d8307Sdrh 
12777c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
127854473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
127954473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
12807c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
12817c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
12827c917d19Sdrh   ** each one to the list of all columns in all tables.
128354473229Sdrh   **
128454473229Sdrh   ** The first loop just checks to see if there are any "*" operators
128554473229Sdrh   ** that need expanding.
1286d8bc7086Sdrh   */
12877c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
128854473229Sdrh     Expr *pE = pEList->a[k].pExpr;
128954473229Sdrh     if( pE->op==TK_ALL ) break;
129054473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
129154473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
12927c917d19Sdrh   }
129354473229Sdrh   rc = 0;
12947c917d19Sdrh   if( k<pEList->nExpr ){
129554473229Sdrh     /*
129654473229Sdrh     ** If we get here it means the result set contains one or more "*"
129754473229Sdrh     ** operators that need to be expanded.  Loop through each expression
129854473229Sdrh     ** in the result set and expand them one by one.
129954473229Sdrh     */
13007c917d19Sdrh     struct ExprList_item *a = pEList->a;
13017c917d19Sdrh     ExprList *pNew = 0;
1302d70dc52dSdrh     int flags = pParse->db->flags;
1303d70dc52dSdrh     int longNames = (flags & SQLITE_FullColNames)!=0 &&
1304d70dc52dSdrh                       (flags & SQLITE_ShortColNames)==0;
1305d70dc52dSdrh 
13067c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
130754473229Sdrh       Expr *pE = a[k].pExpr;
130854473229Sdrh       if( pE->op!=TK_ALL &&
130954473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
131054473229Sdrh         /* This particular expression does not need to be expanded.
131154473229Sdrh         */
131217435752Sdrh         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
1313261919ccSdanielk1977         if( pNew ){
13147c917d19Sdrh           pNew->a[pNew->nExpr-1].zName = a[k].zName;
1315261919ccSdanielk1977         }else{
1316261919ccSdanielk1977           rc = 1;
1317261919ccSdanielk1977         }
13187c917d19Sdrh         a[k].pExpr = 0;
13197c917d19Sdrh         a[k].zName = 0;
13207c917d19Sdrh       }else{
132154473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
132254473229Sdrh         ** expanded. */
132354473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
1324cf55b7aeSdrh         char *zTName;            /* text of name of TABLE */
132554473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
132617435752Sdrh           zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
132754473229Sdrh         }else{
1328cf55b7aeSdrh           zTName = 0;
132954473229Sdrh         }
1330290c1948Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1331290c1948Sdrh           Table *pTab = pFrom->pTab;
1332290c1948Sdrh           char *zTabName = pFrom->zAlias;
133354473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
133454473229Sdrh             zTabName = pTab->zName;
133554473229Sdrh           }
1336cf55b7aeSdrh           if( zTName && (zTabName==0 || zTabName[0]==0 ||
1337cf55b7aeSdrh                  sqlite3StrICmp(zTName, zTabName)!=0) ){
133854473229Sdrh             continue;
133954473229Sdrh           }
134054473229Sdrh           tableSeen = 1;
1341d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
1342f0113000Sdanielk1977             Expr *pExpr, *pRight;
1343ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
1344ad2d8307Sdrh 
1345034ca14fSdanielk1977             /* If a column is marked as 'hidden' (currently only possible
1346034ca14fSdanielk1977             ** for virtual tables), do not include it in the expanded
1347034ca14fSdanielk1977             ** result-set list.
1348034ca14fSdanielk1977             */
1349034ca14fSdanielk1977             if( IsHiddenColumn(&pTab->aCol[j]) ){
1350034ca14fSdanielk1977               assert(IsVirtual(pTab));
1351034ca14fSdanielk1977               continue;
1352034ca14fSdanielk1977             }
1353034ca14fSdanielk1977 
135491bb0eedSdrh             if( i>0 ){
135591bb0eedSdrh               struct SrcList_item *pLeft = &pTabList->a[i-1];
135661dfc31dSdrh               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
135791bb0eedSdrh                         columnIndex(pLeft->pTab, zName)>=0 ){
1358ad2d8307Sdrh                 /* In a NATURAL join, omit the join columns from the
1359ad2d8307Sdrh                 ** table on the right */
1360ad2d8307Sdrh                 continue;
1361ad2d8307Sdrh               }
136261dfc31dSdrh               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
1363ad2d8307Sdrh                 /* In a join with a USING clause, omit columns in the
1364ad2d8307Sdrh                 ** using clause from the table on the right. */
1365ad2d8307Sdrh                 continue;
1366ad2d8307Sdrh               }
136791bb0eedSdrh             }
1368a1644fd8Sdanielk1977             pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
136922f70c32Sdrh             if( pRight==0 ) break;
13701e536953Sdanielk1977             setQuotedToken(pParse, &pRight->token, zName);
1371d70dc52dSdrh             if( zTabName && (longNames || pTabList->nSrc>1) ){
1372a1644fd8Sdanielk1977               Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
1373a1644fd8Sdanielk1977               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
137422f70c32Sdrh               if( pExpr==0 ) break;
13751e536953Sdanielk1977               setQuotedToken(pParse, &pLeft->token, zTabName);
13761e536953Sdanielk1977               setToken(&pExpr->span,
13771e536953Sdanielk1977                   sqlite3MPrintf(db, "%s.%s", zTabName, zName));
13786977fea8Sdrh               pExpr->span.dyn = 1;
13796977fea8Sdrh               pExpr->token.z = 0;
13806977fea8Sdrh               pExpr->token.n = 0;
13816977fea8Sdrh               pExpr->token.dyn = 0;
138222f70c32Sdrh             }else{
138322f70c32Sdrh               pExpr = pRight;
13846977fea8Sdrh               pExpr->span = pExpr->token;
1385f3b863edSdanielk1977               pExpr->span.dyn = 0;
138622f70c32Sdrh             }
1387d70dc52dSdrh             if( longNames ){
138817435752Sdrh               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
1389d70dc52dSdrh             }else{
139017435752Sdrh               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
1391d8bc7086Sdrh             }
1392d8bc7086Sdrh           }
1393d70dc52dSdrh         }
139454473229Sdrh         if( !tableSeen ){
1395cf55b7aeSdrh           if( zTName ){
1396cf55b7aeSdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
1397f5db2d3eSdrh           }else{
13984adee20fSdanielk1977             sqlite3ErrorMsg(pParse, "no tables specified");
1399f5db2d3eSdrh           }
140054473229Sdrh           rc = 1;
140154473229Sdrh         }
140217435752Sdrh         sqlite3_free(zTName);
14037c917d19Sdrh       }
14047c917d19Sdrh     }
14054adee20fSdanielk1977     sqlite3ExprListDelete(pEList);
14067c917d19Sdrh     p->pEList = pNew;
1407d8bc7086Sdrh   }
1408e5c941b8Sdrh   if( p->pEList && p->pEList->nExpr>SQLITE_MAX_COLUMN ){
1409e5c941b8Sdrh     sqlite3ErrorMsg(pParse, "too many columns in result set");
1410e5c941b8Sdrh     rc = SQLITE_ERROR;
1411e5c941b8Sdrh   }
141217435752Sdrh   if( db->mallocFailed ){
1413f3b863edSdanielk1977     rc = SQLITE_NOMEM;
1414f3b863edSdanielk1977   }
141554473229Sdrh   return rc;
1416d8bc7086Sdrh }
1417d8bc7086Sdrh 
141893758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1419ff78bd2fSdrh /*
1420d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with
1421d8bc7086Sdrh ** columns in a result.  For each ORDER BY expression, the opcode of
1422967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of
1423d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable
1424d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter.
1425d8bc7086Sdrh **
1426d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first.  A match
1427d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT.
1428d8bc7086Sdrh **
1429d8bc7086Sdrh ** Any entry that does not match is flagged as an error.  The number
1430d8bc7086Sdrh ** of errors is returned.
1431d8bc7086Sdrh */
1432d8bc7086Sdrh static int matchOrderbyToColumn(
1433d8bc7086Sdrh   Parse *pParse,          /* A place to leave error messages */
1434d8bc7086Sdrh   Select *pSelect,        /* Match to result columns of this SELECT */
1435d8bc7086Sdrh   ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
1436e4de1febSdrh   int iTable,             /* Insert this value in iTable */
1437d8bc7086Sdrh   int mustComplete        /* If TRUE all ORDER BYs must match */
1438d8bc7086Sdrh ){
1439d8bc7086Sdrh   int nErr = 0;
1440d8bc7086Sdrh   int i, j;
1441d8bc7086Sdrh   ExprList *pEList;
144217435752Sdrh   sqlite3 *db = pParse->db;
1443d8bc7086Sdrh 
1444daffd0e5Sdrh   if( pSelect==0 || pOrderBy==0 ) return 1;
1445d8bc7086Sdrh   if( mustComplete ){
1446d8bc7086Sdrh     for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1447d8bc7086Sdrh   }
14489b3187e1Sdrh   if( prepSelectStmt(pParse, pSelect) ){
1449d8bc7086Sdrh     return 1;
1450d8bc7086Sdrh   }
1451d8bc7086Sdrh   if( pSelect->pPrior ){
145292cd52f5Sdrh     if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
145392cd52f5Sdrh       return 1;
145492cd52f5Sdrh     }
1455d8bc7086Sdrh   }
1456d8bc7086Sdrh   pEList = pSelect->pEList;
1457d8bc7086Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
145894ccde58Sdrh     struct ExprList_item *pItem;
1459d8bc7086Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
1460e4de1febSdrh     int iCol = -1;
146194ccde58Sdrh     char *zLabel;
146294ccde58Sdrh 
1463d8bc7086Sdrh     if( pOrderBy->a[i].done ) continue;
14644adee20fSdanielk1977     if( sqlite3ExprIsInteger(pE, &iCol) ){
1465e4de1febSdrh       if( iCol<=0 || iCol>pEList->nExpr ){
14664adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
1467da93d238Sdrh           "ORDER BY position %d should be between 1 and %d",
1468e4de1febSdrh           iCol, pEList->nExpr);
1469e4de1febSdrh         nErr++;
1470e4de1febSdrh         break;
1471e4de1febSdrh       }
1472fcb78a49Sdrh       if( !mustComplete ) continue;
1473e4de1febSdrh       iCol--;
1474e4de1febSdrh     }
147517435752Sdrh     if( iCol<0 && (zLabel = sqlite3NameFromToken(db, &pE->token))!=0 ){
147694ccde58Sdrh       for(j=0, pItem=pEList->a; j<pEList->nExpr; j++, pItem++){
147794ccde58Sdrh         char *zName;
14785ea2df91Sdrh         int isMatch;
147994ccde58Sdrh         if( pItem->zName ){
148017435752Sdrh           zName = sqlite3DbStrDup(db, pItem->zName);
148194ccde58Sdrh         }else{
148217435752Sdrh           zName = sqlite3NameFromToken(db, &pItem->pExpr->token);
148394ccde58Sdrh         }
14845ea2df91Sdrh         isMatch = zName && sqlite3StrICmp(zName, zLabel)==0;
148517435752Sdrh         sqlite3_free(zName);
14865ea2df91Sdrh         if( isMatch ){
1487e4de1febSdrh           iCol = j;
148894ccde58Sdrh           break;
148994ccde58Sdrh         }
1490d8bc7086Sdrh       }
149117435752Sdrh       sqlite3_free(zLabel);
1492d8bc7086Sdrh     }
1493e4de1febSdrh     if( iCol>=0 ){
1494967e8b73Sdrh       pE->op = TK_COLUMN;
1495e4de1febSdrh       pE->iColumn = iCol;
1496d8bc7086Sdrh       pE->iTable = iTable;
1497a58fdfb1Sdanielk1977       pE->iAgg = -1;
1498d8bc7086Sdrh       pOrderBy->a[i].done = 1;
149994ccde58Sdrh     }else if( mustComplete ){
15004adee20fSdanielk1977       sqlite3ErrorMsg(pParse,
1501da93d238Sdrh         "ORDER BY term number %d does not match any result column", i+1);
1502d8bc7086Sdrh       nErr++;
1503d8bc7086Sdrh       break;
1504d8bc7086Sdrh     }
1505d8bc7086Sdrh   }
1506d8bc7086Sdrh   return nErr;
1507d8bc7086Sdrh }
150893758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */
1509d8bc7086Sdrh 
1510d8bc7086Sdrh /*
1511d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1512d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1513d8bc7086Sdrh */
15144adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1515d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1516d8bc7086Sdrh   if( v==0 ){
15174adee20fSdanielk1977     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1518d8bc7086Sdrh   }
1519d8bc7086Sdrh   return v;
1520d8bc7086Sdrh }
1521d8bc7086Sdrh 
152215007a99Sdrh 
1523d8bc7086Sdrh /*
15247b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
1525ec7429aeSdrh ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
15267b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
1527a2dc3b1aSdanielk1977 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1528a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute
1529a2dc3b1aSdanielk1977 ** the limit and offset.  If there is no limit and/or offset, then
1530a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative.
15317b58daeaSdrh **
1532d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if
1533ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset.  iLimit and
15347b58daeaSdrh ** iOffset should have been preset to appropriate default values
15357b58daeaSdrh ** (usually but not always -1) prior to calling this routine.
1536ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
15377b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
15387b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
15397b58daeaSdrh ** SELECT statements.
15407b58daeaSdrh */
1541ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
154202afc861Sdrh   Vdbe *v = 0;
154302afc861Sdrh   int iLimit = 0;
154415007a99Sdrh   int iOffset;
154515007a99Sdrh   int addr1, addr2;
154615007a99Sdrh 
15477b58daeaSdrh   /*
15487b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
15497b58daeaSdrh   ** contraversy about what the correct behavior should be.
15507b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
15517b58daeaSdrh   ** no rows.
15527b58daeaSdrh   */
1553a2dc3b1aSdanielk1977   if( p->pLimit ){
155415007a99Sdrh     p->iLimit = iLimit = pParse->nMem;
1555d59ba6ceSdrh     pParse->nMem += 2;
155615007a99Sdrh     v = sqlite3GetVdbe(pParse);
15577b58daeaSdrh     if( v==0 ) return;
1558a2dc3b1aSdanielk1977     sqlite3ExprCode(pParse, p->pLimit);
1559a2dc3b1aSdanielk1977     sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
15601e4eaeb5Sdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iLimit, 1);
1561ad6d9460Sdrh     VdbeComment((v, "# LIMIT counter"));
156215007a99Sdrh     sqlite3VdbeAddOp(v, OP_IfMemZero, iLimit, iBreak);
15631e4eaeb5Sdanielk1977     sqlite3VdbeAddOp(v, OP_MemLoad, iLimit, 0);
15647b58daeaSdrh   }
1565a2dc3b1aSdanielk1977   if( p->pOffset ){
156615007a99Sdrh     p->iOffset = iOffset = pParse->nMem++;
156715007a99Sdrh     v = sqlite3GetVdbe(pParse);
15687b58daeaSdrh     if( v==0 ) return;
1569a2dc3b1aSdanielk1977     sqlite3ExprCode(pParse, p->pOffset);
1570a2dc3b1aSdanielk1977     sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
157115007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iOffset, p->pLimit==0);
1572ad6d9460Sdrh     VdbeComment((v, "# OFFSET counter"));
157315007a99Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iOffset, 0);
157415007a99Sdrh     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
157515007a99Sdrh     sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
157615007a99Sdrh     sqlite3VdbeJumpHere(v, addr1);
1577d59ba6ceSdrh     if( p->pLimit ){
1578d59ba6ceSdrh       sqlite3VdbeAddOp(v, OP_Add, 0, 0);
1579d59ba6ceSdrh     }
15807b58daeaSdrh   }
1581d59ba6ceSdrh   if( p->pLimit ){
158215007a99Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iLimit, 0);
158315007a99Sdrh     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
158415007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemInt, -1, iLimit+1);
158515007a99Sdrh     addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
158615007a99Sdrh     sqlite3VdbeJumpHere(v, addr1);
158715007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iLimit+1, 1);
1588d59ba6ceSdrh     VdbeComment((v, "# LIMIT+OFFSET"));
158915007a99Sdrh     sqlite3VdbeJumpHere(v, addr2);
1590d59ba6ceSdrh   }
15917b58daeaSdrh }
15927b58daeaSdrh 
15937b58daeaSdrh /*
15940342b1f5Sdrh ** Allocate a virtual index to use for sorting.
1595d3d39e93Sdrh */
15964db38a70Sdrh static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
15970342b1f5Sdrh   if( pOrderBy ){
1598dc1bdc4fSdanielk1977     int addr;
15999d2985c7Sdrh     assert( pOrderBy->iECursor==0 );
16009d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
1601b9bb7c18Sdrh     addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenEphemeral,
16029d2985c7Sdrh                             pOrderBy->iECursor, pOrderBy->nExpr+1);
1603b9bb7c18Sdrh     assert( p->addrOpenEphm[2] == -1 );
1604b9bb7c18Sdrh     p->addrOpenEphm[2] = addr;
1605736c22b8Sdrh   }
1606dc1bdc4fSdanielk1977 }
1607dc1bdc4fSdanielk1977 
1608b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1609fbc4ee7bSdrh /*
1610fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
1611fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
1612fbc4ee7bSdrh ** the column has no default collating sequence.
1613fbc4ee7bSdrh **
1614fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
1615fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
1616fbc4ee7bSdrh */
1617dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1618fbc4ee7bSdrh   CollSeq *pRet;
1619dc1bdc4fSdanielk1977   if( p->pPrior ){
1620dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1621fbc4ee7bSdrh   }else{
1622fbc4ee7bSdrh     pRet = 0;
1623dc1bdc4fSdanielk1977   }
1624fbc4ee7bSdrh   if( pRet==0 ){
1625dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1626dc1bdc4fSdanielk1977   }
1627dc1bdc4fSdanielk1977   return pRet;
1628d3d39e93Sdrh }
1629b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1630d3d39e93Sdrh 
1631b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1632d3d39e93Sdrh /*
163382c3d636Sdrh ** This routine is called to process a query that is really the union
163482c3d636Sdrh ** or intersection of two or more separate queries.
1635c926afbcSdrh **
1636e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1637e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1638e78e8284Sdrh ** in which case this routine will be called recursively.
1639e78e8284Sdrh **
1640e78e8284Sdrh ** The results of the total query are to be written into a destination
1641e78e8284Sdrh ** of type eDest with parameter iParm.
1642e78e8284Sdrh **
1643e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1644e78e8284Sdrh **
1645e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1646e78e8284Sdrh **
1647e78e8284Sdrh ** This statement is parsed up as follows:
1648e78e8284Sdrh **
1649e78e8284Sdrh **     SELECT c FROM t3
1650e78e8284Sdrh **      |
1651e78e8284Sdrh **      `----->  SELECT b FROM t2
1652e78e8284Sdrh **                |
16534b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1654e78e8284Sdrh **
1655e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1656e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1657e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1658e78e8284Sdrh **
1659e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1660e78e8284Sdrh ** individual selects always group from left to right.
166182c3d636Sdrh */
166284ac9d02Sdanielk1977 static int multiSelect(
1663fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
1664fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
1665fbc4ee7bSdrh   int eDest,            /* \___  Store query results as specified */
1666fbc4ee7bSdrh   int iParm,            /* /     by these two parameters.         */
166784ac9d02Sdanielk1977   char *aff             /* If eDest is SRT_Union, the affinity string */
166884ac9d02Sdanielk1977 ){
166984ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
167010e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
167110e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
16728cdbf836Sdrh   int nCol;             /* Number of columns in the result set */
16730342b1f5Sdrh   ExprList *pOrderBy;   /* The ORDER BY clause on p */
16740342b1f5Sdrh   int aSetP2[2];        /* Set P2 value of these op to number of columns */
16750342b1f5Sdrh   int nSetP2 = 0;       /* Number of slots in aSetP2[] used */
167682c3d636Sdrh 
16777b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1678fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
167982c3d636Sdrh   */
168084ac9d02Sdanielk1977   if( p==0 || p->pPrior==0 ){
168184ac9d02Sdanielk1977     rc = 1;
168284ac9d02Sdanielk1977     goto multi_select_end;
168384ac9d02Sdanielk1977   }
1684d8bc7086Sdrh   pPrior = p->pPrior;
16850342b1f5Sdrh   assert( pPrior->pRightmost!=pPrior );
16860342b1f5Sdrh   assert( pPrior->pRightmost==p->pRightmost );
1687d8bc7086Sdrh   if( pPrior->pOrderBy ){
16884adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1689da93d238Sdrh       selectOpName(p->op));
169084ac9d02Sdanielk1977     rc = 1;
169184ac9d02Sdanielk1977     goto multi_select_end;
169282c3d636Sdrh   }
1693a2dc3b1aSdanielk1977   if( pPrior->pLimit ){
16944adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
16957b58daeaSdrh       selectOpName(p->op));
169684ac9d02Sdanielk1977     rc = 1;
169784ac9d02Sdanielk1977     goto multi_select_end;
16987b58daeaSdrh   }
169982c3d636Sdrh 
1700d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
1701d8bc7086Sdrh   */
17024adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
170384ac9d02Sdanielk1977   if( v==0 ){
170484ac9d02Sdanielk1977     rc = 1;
170584ac9d02Sdanielk1977     goto multi_select_end;
170684ac9d02Sdanielk1977   }
1707d8bc7086Sdrh 
17081cc3d75fSdrh   /* Create the destination temporary table if necessary
17091cc3d75fSdrh   */
1710b9bb7c18Sdrh   if( eDest==SRT_EphemTab ){
1711b4964b72Sdanielk1977     assert( p->pEList );
17120342b1f5Sdrh     assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1713b9bb7c18Sdrh     aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 0);
17141cc3d75fSdrh     eDest = SRT_Table;
17151cc3d75fSdrh   }
17161cc3d75fSdrh 
1717f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1718d8bc7086Sdrh   */
17190342b1f5Sdrh   pOrderBy = p->pOrderBy;
172082c3d636Sdrh   switch( p->op ){
1721f46f905aSdrh     case TK_ALL: {
17220342b1f5Sdrh       if( pOrderBy==0 ){
1723ec7429aeSdrh         int addr = 0;
1724a2dc3b1aSdanielk1977         assert( !pPrior->pLimit );
1725a2dc3b1aSdanielk1977         pPrior->pLimit = p->pLimit;
1726a2dc3b1aSdanielk1977         pPrior->pOffset = p->pOffset;
1727b3bce662Sdanielk1977         rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
1728ad68cb6bSdanielk1977         p->pLimit = 0;
1729ad68cb6bSdanielk1977         p->pOffset = 0;
173084ac9d02Sdanielk1977         if( rc ){
173184ac9d02Sdanielk1977           goto multi_select_end;
173284ac9d02Sdanielk1977         }
1733f46f905aSdrh         p->pPrior = 0;
17347b58daeaSdrh         p->iLimit = pPrior->iLimit;
17357b58daeaSdrh         p->iOffset = pPrior->iOffset;
1736ec7429aeSdrh         if( p->iLimit>=0 ){
1737ec7429aeSdrh           addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0);
1738ec7429aeSdrh           VdbeComment((v, "# Jump ahead if LIMIT reached"));
1739ec7429aeSdrh         }
1740b3bce662Sdanielk1977         rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
1741f46f905aSdrh         p->pPrior = pPrior;
174284ac9d02Sdanielk1977         if( rc ){
174384ac9d02Sdanielk1977           goto multi_select_end;
174484ac9d02Sdanielk1977         }
1745ec7429aeSdrh         if( addr ){
1746ec7429aeSdrh           sqlite3VdbeJumpHere(v, addr);
1747ec7429aeSdrh         }
1748f46f905aSdrh         break;
1749f46f905aSdrh       }
1750f46f905aSdrh       /* For UNION ALL ... ORDER BY fall through to the next case */
1751f46f905aSdrh     }
175282c3d636Sdrh     case TK_EXCEPT:
175382c3d636Sdrh     case TK_UNION: {
1754d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1755742f947bSdanielk1977       int op = 0;      /* One of the SRT_ operations to apply to self */
1756d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
1757a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
1758dc1bdc4fSdanielk1977       int addr;
175982c3d636Sdrh 
1760d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
17610342b1f5Sdrh       if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
1762d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1763c926afbcSdrh         ** right.
1764d8bc7086Sdrh         */
176582c3d636Sdrh         unionTab = iParm;
176682c3d636Sdrh       }else{
1767d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1768d8bc7086Sdrh         ** intermediate results.
1769d8bc7086Sdrh         */
177082c3d636Sdrh         unionTab = pParse->nTab++;
17710342b1f5Sdrh         if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){
177284ac9d02Sdanielk1977           rc = 1;
177384ac9d02Sdanielk1977           goto multi_select_end;
1774d8bc7086Sdrh         }
1775b9bb7c18Sdrh         addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, unionTab, 0);
17760342b1f5Sdrh         if( priorOp==SRT_Table ){
17770342b1f5Sdrh           assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
17780342b1f5Sdrh           aSetP2[nSetP2++] = addr;
17790342b1f5Sdrh         }else{
1780b9bb7c18Sdrh           assert( p->addrOpenEphm[0] == -1 );
1781b9bb7c18Sdrh           p->addrOpenEphm[0] = addr;
1782b9bb7c18Sdrh           p->pRightmost->usesEphm = 1;
1783dc1bdc4fSdanielk1977         }
17840342b1f5Sdrh         createSortingIndex(pParse, p, pOrderBy);
178584ac9d02Sdanielk1977         assert( p->pEList );
1786d8bc7086Sdrh       }
1787d8bc7086Sdrh 
1788d8bc7086Sdrh       /* Code the SELECT statements to our left
1789d8bc7086Sdrh       */
1790b3bce662Sdanielk1977       assert( !pPrior->pOrderBy );
1791b3bce662Sdanielk1977       rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
179284ac9d02Sdanielk1977       if( rc ){
179384ac9d02Sdanielk1977         goto multi_select_end;
179484ac9d02Sdanielk1977       }
1795d8bc7086Sdrh 
1796d8bc7086Sdrh       /* Code the current SELECT statement
1797d8bc7086Sdrh       */
1798d8bc7086Sdrh       switch( p->op ){
1799d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
1800d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
1801d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
1802d8bc7086Sdrh       }
180382c3d636Sdrh       p->pPrior = 0;
1804c926afbcSdrh       p->pOrderBy = 0;
18054b14b4d7Sdrh       p->disallowOrderBy = pOrderBy!=0;
1806a2dc3b1aSdanielk1977       pLimit = p->pLimit;
1807a2dc3b1aSdanielk1977       p->pLimit = 0;
1808a2dc3b1aSdanielk1977       pOffset = p->pOffset;
1809a2dc3b1aSdanielk1977       p->pOffset = 0;
1810b3bce662Sdanielk1977       rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
18115bd1bf2eSdrh       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
18125bd1bf2eSdrh       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
18135bd1bf2eSdrh       sqlite3ExprListDelete(p->pOrderBy);
181482c3d636Sdrh       p->pPrior = pPrior;
1815c926afbcSdrh       p->pOrderBy = pOrderBy;
1816a2dc3b1aSdanielk1977       sqlite3ExprDelete(p->pLimit);
1817a2dc3b1aSdanielk1977       p->pLimit = pLimit;
1818a2dc3b1aSdanielk1977       p->pOffset = pOffset;
1819be5fd490Sdrh       p->iLimit = -1;
1820be5fd490Sdrh       p->iOffset = -1;
182184ac9d02Sdanielk1977       if( rc ){
182284ac9d02Sdanielk1977         goto multi_select_end;
182384ac9d02Sdanielk1977       }
182484ac9d02Sdanielk1977 
1825d8bc7086Sdrh 
1826d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1827d8bc7086Sdrh       ** it is that we currently need.
1828d8bc7086Sdrh       */
1829c926afbcSdrh       if( eDest!=priorOp || unionTab!=iParm ){
18306b56344dSdrh         int iCont, iBreak, iStart;
183182c3d636Sdrh         assert( p->pEList );
183241202ccaSdrh         if( eDest==SRT_Callback ){
183392378253Sdrh           Select *pFirst = p;
183492378253Sdrh           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
183592378253Sdrh           generateColumnNames(pParse, 0, pFirst->pEList);
183641202ccaSdrh         }
18374adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
18384adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
1839ec7429aeSdrh         computeLimitRegisters(pParse, p, iBreak);
18404adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
18414adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
184238640e15Sdrh         rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
18430342b1f5Sdrh                              pOrderBy, -1, eDest, iParm,
184484ac9d02Sdanielk1977                              iCont, iBreak, 0);
184584ac9d02Sdanielk1977         if( rc ){
184684ac9d02Sdanielk1977           rc = 1;
184784ac9d02Sdanielk1977           goto multi_select_end;
184884ac9d02Sdanielk1977         }
18494adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
18504adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
18514adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
18524adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
185382c3d636Sdrh       }
185482c3d636Sdrh       break;
185582c3d636Sdrh     }
185682c3d636Sdrh     case TK_INTERSECT: {
185782c3d636Sdrh       int tab1, tab2;
18586b56344dSdrh       int iCont, iBreak, iStart;
1859a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset;
1860dc1bdc4fSdanielk1977       int addr;
186182c3d636Sdrh 
1862d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
18636206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
1864d8bc7086Sdrh       ** by allocating the tables we will need.
1865d8bc7086Sdrh       */
186682c3d636Sdrh       tab1 = pParse->nTab++;
186782c3d636Sdrh       tab2 = pParse->nTab++;
18680342b1f5Sdrh       if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){
186984ac9d02Sdanielk1977         rc = 1;
187084ac9d02Sdanielk1977         goto multi_select_end;
1871d8bc7086Sdrh       }
18720342b1f5Sdrh       createSortingIndex(pParse, p, pOrderBy);
1873dc1bdc4fSdanielk1977 
1874b9bb7c18Sdrh       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab1, 0);
1875b9bb7c18Sdrh       assert( p->addrOpenEphm[0] == -1 );
1876b9bb7c18Sdrh       p->addrOpenEphm[0] = addr;
1877b9bb7c18Sdrh       p->pRightmost->usesEphm = 1;
187884ac9d02Sdanielk1977       assert( p->pEList );
1879d8bc7086Sdrh 
1880d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1881d8bc7086Sdrh       */
1882b3bce662Sdanielk1977       rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
188384ac9d02Sdanielk1977       if( rc ){
188484ac9d02Sdanielk1977         goto multi_select_end;
188584ac9d02Sdanielk1977       }
1886d8bc7086Sdrh 
1887d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1888d8bc7086Sdrh       */
1889b9bb7c18Sdrh       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab2, 0);
1890b9bb7c18Sdrh       assert( p->addrOpenEphm[1] == -1 );
1891b9bb7c18Sdrh       p->addrOpenEphm[1] = addr;
189282c3d636Sdrh       p->pPrior = 0;
1893a2dc3b1aSdanielk1977       pLimit = p->pLimit;
1894a2dc3b1aSdanielk1977       p->pLimit = 0;
1895a2dc3b1aSdanielk1977       pOffset = p->pOffset;
1896a2dc3b1aSdanielk1977       p->pOffset = 0;
1897b3bce662Sdanielk1977       rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
189882c3d636Sdrh       p->pPrior = pPrior;
1899a2dc3b1aSdanielk1977       sqlite3ExprDelete(p->pLimit);
1900a2dc3b1aSdanielk1977       p->pLimit = pLimit;
1901a2dc3b1aSdanielk1977       p->pOffset = pOffset;
190284ac9d02Sdanielk1977       if( rc ){
190384ac9d02Sdanielk1977         goto multi_select_end;
190484ac9d02Sdanielk1977       }
1905d8bc7086Sdrh 
1906d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1907d8bc7086Sdrh       ** tables.
1908d8bc7086Sdrh       */
190982c3d636Sdrh       assert( p->pEList );
191041202ccaSdrh       if( eDest==SRT_Callback ){
191192378253Sdrh         Select *pFirst = p;
191292378253Sdrh         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
191392378253Sdrh         generateColumnNames(pParse, 0, pFirst->pEList);
191441202ccaSdrh       }
19154adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
19164adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
1917ec7429aeSdrh       computeLimitRegisters(pParse, p, iBreak);
19184adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
19194a9f241cSdrh       iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0);
19204adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
192138640e15Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
19220342b1f5Sdrh                              pOrderBy, -1, eDest, iParm,
192384ac9d02Sdanielk1977                              iCont, iBreak, 0);
192484ac9d02Sdanielk1977       if( rc ){
192584ac9d02Sdanielk1977         rc = 1;
192684ac9d02Sdanielk1977         goto multi_select_end;
192784ac9d02Sdanielk1977       }
19284adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
19294adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
19304adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
19314adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
19324adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
193382c3d636Sdrh       break;
193482c3d636Sdrh     }
193582c3d636Sdrh   }
19368cdbf836Sdrh 
19378cdbf836Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
19388cdbf836Sdrh   ** in their result sets.
19398cdbf836Sdrh   */
194082c3d636Sdrh   assert( p->pEList && pPrior->pEList );
194182c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
19424adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
1943da93d238Sdrh       " do not have the same number of result columns", selectOpName(p->op));
194484ac9d02Sdanielk1977     rc = 1;
194584ac9d02Sdanielk1977     goto multi_select_end;
19462282792aSdrh   }
194784ac9d02Sdanielk1977 
19488cdbf836Sdrh   /* Set the number of columns in temporary tables
19498cdbf836Sdrh   */
19508cdbf836Sdrh   nCol = p->pEList->nExpr;
19510342b1f5Sdrh   while( nSetP2 ){
19520342b1f5Sdrh     sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
19538cdbf836Sdrh   }
19548cdbf836Sdrh 
1955fbc4ee7bSdrh   /* Compute collating sequences used by either the ORDER BY clause or
1956fbc4ee7bSdrh   ** by any temporary tables needed to implement the compound select.
1957fbc4ee7bSdrh   ** Attach the KeyInfo structure to all temporary tables.  Invoke the
1958fbc4ee7bSdrh   ** ORDER BY processing if there is an ORDER BY clause.
19598cdbf836Sdrh   **
19608cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
19618cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
19628cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
19638cdbf836Sdrh   ** no temp tables are required.
1964fbc4ee7bSdrh   */
1965b9bb7c18Sdrh   if( pOrderBy || p->usesEphm ){
1966fbc4ee7bSdrh     int i;                        /* Loop counter */
1967fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
19680342b1f5Sdrh     Select *pLoop;                /* For looping through SELECT statements */
19691e31e0b2Sdrh     int nKeyCol;                  /* Number of entries in pKeyInfo->aCol[] */
1970f68d7d17Sdrh     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
1971f68d7d17Sdrh     CollSeq **aCopy;              /* A copy of pKeyInfo->aColl[] */
1972fbc4ee7bSdrh 
19730342b1f5Sdrh     assert( p->pRightmost==p );
19741e31e0b2Sdrh     nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0);
197517435752Sdrh     pKeyInfo = sqlite3DbMallocZero(pParse->db,
197617435752Sdrh                        sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1));
1977dc1bdc4fSdanielk1977     if( !pKeyInfo ){
1978dc1bdc4fSdanielk1977       rc = SQLITE_NOMEM;
1979dc1bdc4fSdanielk1977       goto multi_select_end;
1980dc1bdc4fSdanielk1977     }
1981dc1bdc4fSdanielk1977 
198214db2665Sdanielk1977     pKeyInfo->enc = ENC(pParse->db);
1983dc1bdc4fSdanielk1977     pKeyInfo->nField = nCol;
1984dc1bdc4fSdanielk1977 
19850342b1f5Sdrh     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
19860342b1f5Sdrh       *apColl = multiSelectCollSeq(pParse, p, i);
19870342b1f5Sdrh       if( 0==*apColl ){
19880342b1f5Sdrh         *apColl = pParse->db->pDfltColl;
1989dc1bdc4fSdanielk1977       }
1990dc1bdc4fSdanielk1977     }
1991dc1bdc4fSdanielk1977 
19920342b1f5Sdrh     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
19930342b1f5Sdrh       for(i=0; i<2; i++){
1994b9bb7c18Sdrh         int addr = pLoop->addrOpenEphm[i];
19950342b1f5Sdrh         if( addr<0 ){
19960342b1f5Sdrh           /* If [0] is unused then [1] is also unused.  So we can
19970342b1f5Sdrh           ** always safely abort as soon as the first unused slot is found */
1998b9bb7c18Sdrh           assert( pLoop->addrOpenEphm[1]<0 );
19990342b1f5Sdrh           break;
20000342b1f5Sdrh         }
20010342b1f5Sdrh         sqlite3VdbeChangeP2(v, addr, nCol);
20020342b1f5Sdrh         sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO);
20030ee5a1e7Sdrh         pLoop->addrOpenEphm[i] = -1;
20040342b1f5Sdrh       }
2005dc1bdc4fSdanielk1977     }
2006dc1bdc4fSdanielk1977 
20070342b1f5Sdrh     if( pOrderBy ){
20080342b1f5Sdrh       struct ExprList_item *pOTerm = pOrderBy->a;
20094efc083fSdrh       int nOrderByExpr = pOrderBy->nExpr;
20100342b1f5Sdrh       int addr;
20114db38a70Sdrh       u8 *pSortOrder;
20120342b1f5Sdrh 
2013f68d7d17Sdrh       /* Reuse the same pKeyInfo for the ORDER BY as was used above for
2014f68d7d17Sdrh       ** the compound select statements.  Except we have to change out the
2015f68d7d17Sdrh       ** pKeyInfo->aColl[] values.  Some of the aColl[] values will be
2016f68d7d17Sdrh       ** reused when constructing the pKeyInfo for the ORDER BY, so make
2017f68d7d17Sdrh       ** a copy.  Sufficient space to hold both the nCol entries for
2018f68d7d17Sdrh       ** the compound select and the nOrderbyExpr entries for the ORDER BY
2019f68d7d17Sdrh       ** was allocated above.  But we need to move the compound select
2020f68d7d17Sdrh       ** entries out of the way before constructing the ORDER BY entries.
2021f68d7d17Sdrh       ** Move the compound select entries into aCopy[] where they can be
2022f68d7d17Sdrh       ** accessed and reused when constructing the ORDER BY entries.
2023f68d7d17Sdrh       ** Because nCol might be greater than or less than nOrderByExpr
2024f68d7d17Sdrh       ** we have to use memmove() when doing the copy.
2025f68d7d17Sdrh       */
20261e31e0b2Sdrh       aCopy = &pKeyInfo->aColl[nOrderByExpr];
20274efc083fSdrh       pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
2028f68d7d17Sdrh       memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
2029f68d7d17Sdrh 
20300342b1f5Sdrh       apColl = pKeyInfo->aColl;
20314efc083fSdrh       for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
20320342b1f5Sdrh         Expr *pExpr = pOTerm->pExpr;
20338b4c40d8Sdrh         if( (pExpr->flags & EP_ExpCollate) ){
20348b4c40d8Sdrh           assert( pExpr->pColl!=0 );
20358b4c40d8Sdrh           *apColl = pExpr->pColl;
203684ac9d02Sdanielk1977         }else{
20370342b1f5Sdrh           *apColl = aCopy[pExpr->iColumn];
203884ac9d02Sdanielk1977         }
20394db38a70Sdrh         *pSortOrder = pOTerm->sortOrder;
204084ac9d02Sdanielk1977       }
20410342b1f5Sdrh       assert( p->pRightmost==p );
2042b9bb7c18Sdrh       assert( p->addrOpenEphm[2]>=0 );
2043b9bb7c18Sdrh       addr = p->addrOpenEphm[2];
2044a670b226Sdanielk1977       sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2);
20454efc083fSdrh       pKeyInfo->nField = nOrderByExpr;
20464db38a70Sdrh       sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
20474db38a70Sdrh       pKeyInfo = 0;
2048cdd536f0Sdrh       generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
2049dc1bdc4fSdanielk1977     }
2050dc1bdc4fSdanielk1977 
205117435752Sdrh     sqlite3_free(pKeyInfo);
2052dc1bdc4fSdanielk1977   }
2053dc1bdc4fSdanielk1977 
2054dc1bdc4fSdanielk1977 multi_select_end:
205584ac9d02Sdanielk1977   return rc;
20562282792aSdrh }
2057b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
20582282792aSdrh 
2059b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
206017435752Sdrh /* Forward Declarations */
206117435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*);
206217435752Sdrh static void substSelect(sqlite3*, Select *, int, ExprList *);
206317435752Sdrh 
20642282792aSdrh /*
2065832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
20666a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
206784e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
20686a3ea0e6Sdrh ** unchanged.)
2069832508b7Sdrh **
2070832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
2071832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
2072832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
2073832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
2074832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
2075832508b7Sdrh ** of the subquery rather the result set of the subquery.
2076832508b7Sdrh */
207717435752Sdrh static void substExpr(
207817435752Sdrh   sqlite3 *db,        /* Report malloc errors to this connection */
207917435752Sdrh   Expr *pExpr,        /* Expr in which substitution occurs */
208017435752Sdrh   int iTable,         /* Table to be substituted */
208117435752Sdrh   ExprList *pEList    /* Substitute expressions */
208217435752Sdrh ){
2083832508b7Sdrh   if( pExpr==0 ) return;
208450350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
208550350a15Sdrh     if( pExpr->iColumn<0 ){
208650350a15Sdrh       pExpr->op = TK_NULL;
208750350a15Sdrh     }else{
2088832508b7Sdrh       Expr *pNew;
208984e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
2090832508b7Sdrh       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
2091832508b7Sdrh       pNew = pEList->a[pExpr->iColumn].pExpr;
2092832508b7Sdrh       assert( pNew!=0 );
2093832508b7Sdrh       pExpr->op = pNew->op;
2094d94a6698Sdrh       assert( pExpr->pLeft==0 );
209517435752Sdrh       pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
2096d94a6698Sdrh       assert( pExpr->pRight==0 );
209717435752Sdrh       pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
2098d94a6698Sdrh       assert( pExpr->pList==0 );
209917435752Sdrh       pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
2100832508b7Sdrh       pExpr->iTable = pNew->iTable;
2101fbbe005aSdanielk1977       pExpr->pTab = pNew->pTab;
2102832508b7Sdrh       pExpr->iColumn = pNew->iColumn;
2103832508b7Sdrh       pExpr->iAgg = pNew->iAgg;
210417435752Sdrh       sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
210517435752Sdrh       sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
210617435752Sdrh       pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
2107a1cb183dSdanielk1977       pExpr->flags = pNew->flags;
210850350a15Sdrh     }
2109832508b7Sdrh   }else{
211017435752Sdrh     substExpr(db, pExpr->pLeft, iTable, pEList);
211117435752Sdrh     substExpr(db, pExpr->pRight, iTable, pEList);
211217435752Sdrh     substSelect(db, pExpr->pSelect, iTable, pEList);
211317435752Sdrh     substExprList(db, pExpr->pList, iTable, pEList);
2114832508b7Sdrh   }
2115832508b7Sdrh }
211617435752Sdrh static void substExprList(
211717435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
211817435752Sdrh   ExprList *pList,     /* List to scan and in which to make substitutes */
211917435752Sdrh   int iTable,          /* Table to be substituted */
212017435752Sdrh   ExprList *pEList     /* Substitute values */
212117435752Sdrh ){
2122832508b7Sdrh   int i;
2123832508b7Sdrh   if( pList==0 ) return;
2124832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
212517435752Sdrh     substExpr(db, pList->a[i].pExpr, iTable, pEList);
2126832508b7Sdrh   }
2127832508b7Sdrh }
212817435752Sdrh static void substSelect(
212917435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
213017435752Sdrh   Select *p,           /* SELECT statement in which to make substitutions */
213117435752Sdrh   int iTable,          /* Table to be replaced */
213217435752Sdrh   ExprList *pEList     /* Substitute values */
213317435752Sdrh ){
2134b3bce662Sdanielk1977   if( !p ) return;
213517435752Sdrh   substExprList(db, p->pEList, iTable, pEList);
213617435752Sdrh   substExprList(db, p->pGroupBy, iTable, pEList);
213717435752Sdrh   substExprList(db, p->pOrderBy, iTable, pEList);
213817435752Sdrh   substExpr(db, p->pHaving, iTable, pEList);
213917435752Sdrh   substExpr(db, p->pWhere, iTable, pEList);
214017435752Sdrh   substSelect(db, p->pPrior, iTable, pEList);
2141b3bce662Sdanielk1977 }
2142b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_VIEW) */
2143832508b7Sdrh 
2144b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
2145832508b7Sdrh /*
21461350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
21471350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
21481350b030Sdrh ** occurs.
21491350b030Sdrh **
21501350b030Sdrh ** To understand the concept of flattening, consider the following
21511350b030Sdrh ** query:
21521350b030Sdrh **
21531350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
21541350b030Sdrh **
21551350b030Sdrh ** The default way of implementing this query is to execute the
21561350b030Sdrh ** subquery first and store the results in a temporary table, then
21571350b030Sdrh ** run the outer query on that temporary table.  This requires two
21581350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
21591350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
2160832508b7Sdrh ** optimized.
21611350b030Sdrh **
2162832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
21631350b030Sdrh ** a single flat select, like this:
21641350b030Sdrh **
21651350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
21661350b030Sdrh **
21671350b030Sdrh ** The code generated for this simpification gives the same result
2168832508b7Sdrh ** but only has to scan the data once.  And because indices might
2169832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
2170832508b7Sdrh ** avoided.
21711350b030Sdrh **
2172832508b7Sdrh ** Flattening is only attempted if all of the following are true:
21731350b030Sdrh **
2174832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
21751350b030Sdrh **
2176832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
2177832508b7Sdrh **
21788af4d3acSdrh **   (3)  The subquery is not the right operand of a left outer join, or
21798af4d3acSdrh **        the subquery is not itself a join.  (Ticket #306)
2180832508b7Sdrh **
2181832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
2182832508b7Sdrh **
2183832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
2184832508b7Sdrh **        aggregates.
2185832508b7Sdrh **
2186832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
2187832508b7Sdrh **        DISTINCT.
2188832508b7Sdrh **
218908192d5fSdrh **   (7)  The subquery has a FROM clause.
219008192d5fSdrh **
2191df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
2192df199a25Sdrh **
2193df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
2194df199a25Sdrh **        aggregates.
2195df199a25Sdrh **
2196df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
2197df199a25Sdrh **        use LIMIT.
2198df199a25Sdrh **
2199174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
2200174b6195Sdrh **
22013fc673e6Sdrh **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
22023fc673e6Sdrh **        subquery has no WHERE clause.  (added by ticket #350)
22033fc673e6Sdrh **
2204ac83963aSdrh **  (13)  The subquery and outer query do not both use LIMIT
2205ac83963aSdrh **
2206ac83963aSdrh **  (14)  The subquery does not use OFFSET
2207ac83963aSdrh **
2208ad91c6cdSdrh **  (15)  The outer query is not part of a compound select or the
2209ad91c6cdSdrh **        subquery does not have both an ORDER BY and a LIMIT clause.
2210ad91c6cdSdrh **        (See ticket #2339)
2211ad91c6cdSdrh **
2212832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
2213832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
2214832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
2215832508b7Sdrh **
2216665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
2217832508b7Sdrh ** If flattening is attempted this routine returns 1.
2218832508b7Sdrh **
2219832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
2220832508b7Sdrh ** the subquery before this routine runs.
22211350b030Sdrh */
22228c74a8caSdrh static int flattenSubquery(
222317435752Sdrh   sqlite3 *db,         /* Database connection */
22248c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
22258c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
22268c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
22278c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
22288c74a8caSdrh ){
22290bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
2230ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
2231ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
22320bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
22336a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
223491bb0eedSdrh   int i;              /* Loop counter */
223591bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
223691bb0eedSdrh   struct SrcList_item *pSubitem;   /* The subquery */
22371350b030Sdrh 
2238832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
2239832508b7Sdrh   */
2240832508b7Sdrh   if( p==0 ) return 0;
2241832508b7Sdrh   pSrc = p->pSrc;
2242ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
224391bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
224491bb0eedSdrh   pSub = pSubitem->pSelect;
2245832508b7Sdrh   assert( pSub!=0 );
2246ac83963aSdrh   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
2247ac83963aSdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
2248832508b7Sdrh   pSubSrc = pSub->pSrc;
2249832508b7Sdrh   assert( pSubSrc );
2250ac83963aSdrh   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
2251ac83963aSdrh   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
2252ac83963aSdrh   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
2253ac83963aSdrh   ** became arbitrary expressions, we were forced to add restrictions (13)
2254ac83963aSdrh   ** and (14). */
2255ac83963aSdrh   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
2256ac83963aSdrh   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
2257ad91c6cdSdrh   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
2258ad91c6cdSdrh     return 0;                                            /* Restriction (15) */
2259ad91c6cdSdrh   }
2260ac83963aSdrh   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
2261ac83963aSdrh   if( (pSub->isDistinct || pSub->pLimit)
2262ac83963aSdrh          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
2263df199a25Sdrh      return 0;
2264df199a25Sdrh   }
2265ac83963aSdrh   if( p->isDistinct && subqueryIsAgg ) return 0;         /* Restriction (6)  */
2266ac83963aSdrh   if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){
2267ac83963aSdrh      return 0;                                           /* Restriction (11) */
2268ac83963aSdrh   }
2269832508b7Sdrh 
22708af4d3acSdrh   /* Restriction 3:  If the subquery is a join, make sure the subquery is
22718af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
22728af4d3acSdrh   ** is not allowed:
22738af4d3acSdrh   **
22748af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
22758af4d3acSdrh   **
22768af4d3acSdrh   ** If we flatten the above, we would get
22778af4d3acSdrh   **
22788af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
22798af4d3acSdrh   **
22808af4d3acSdrh   ** which is not at all the same thing.
22818af4d3acSdrh   */
228261dfc31dSdrh   if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){
22838af4d3acSdrh     return 0;
22848af4d3acSdrh   }
22858af4d3acSdrh 
22863fc673e6Sdrh   /* Restriction 12:  If the subquery is the right operand of a left outer
22873fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
22883fc673e6Sdrh   ** An examples of why this is not allowed:
22893fc673e6Sdrh   **
22903fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
22913fc673e6Sdrh   **
22923fc673e6Sdrh   ** If we flatten the above, we would get
22933fc673e6Sdrh   **
22943fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
22953fc673e6Sdrh   **
22963fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
22973fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
22983fc673e6Sdrh   */
229961dfc31dSdrh   if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){
23003fc673e6Sdrh     return 0;
23013fc673e6Sdrh   }
23023fc673e6Sdrh 
23030bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
230463eb5f29Sdrh   ** iFrom-th entry of the FROM clause in the outer query.
2305832508b7Sdrh   */
2306c31c2eb8Sdrh 
2307c31c2eb8Sdrh   /* Move all of the FROM elements of the subquery into the
2308c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
2309c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
2310c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
2311c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
2312c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
2313c31c2eb8Sdrh   ** elements we are now copying in.
2314c31c2eb8Sdrh   */
231591bb0eedSdrh   iParent = pSubitem->iCursor;
2316c31c2eb8Sdrh   {
2317c31c2eb8Sdrh     int nSubSrc = pSubSrc->nSrc;
231891bb0eedSdrh     int jointype = pSubitem->jointype;
2319c31c2eb8Sdrh 
2320a04a34ffSdanielk1977     sqlite3DeleteTable(pSubitem->pTab);
232117435752Sdrh     sqlite3_free(pSubitem->zDatabase);
232217435752Sdrh     sqlite3_free(pSubitem->zName);
232317435752Sdrh     sqlite3_free(pSubitem->zAlias);
2324c31c2eb8Sdrh     if( nSubSrc>1 ){
2325c31c2eb8Sdrh       int extra = nSubSrc - 1;
2326c31c2eb8Sdrh       for(i=1; i<nSubSrc; i++){
232717435752Sdrh         pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0);
2328c31c2eb8Sdrh       }
2329c31c2eb8Sdrh       p->pSrc = pSrc;
2330c31c2eb8Sdrh       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2331c31c2eb8Sdrh         pSrc->a[i] = pSrc->a[i-extra];
2332c31c2eb8Sdrh       }
2333c31c2eb8Sdrh     }
2334c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
2335c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
2336c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2337c31c2eb8Sdrh     }
233861dfc31dSdrh     pSrc->a[iFrom].jointype = jointype;
2339c31c2eb8Sdrh   }
2340c31c2eb8Sdrh 
2341c31c2eb8Sdrh   /* Now begin substituting subquery result set expressions for
2342c31c2eb8Sdrh   ** references to the iParent in the outer query.
2343c31c2eb8Sdrh   **
2344c31c2eb8Sdrh   ** Example:
2345c31c2eb8Sdrh   **
2346c31c2eb8Sdrh   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2347c31c2eb8Sdrh   **   \                     \_____________ subquery __________/          /
2348c31c2eb8Sdrh   **    \_____________________ outer query ______________________________/
2349c31c2eb8Sdrh   **
2350c31c2eb8Sdrh   ** We look at every expression in the outer query and every place we see
2351c31c2eb8Sdrh   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2352c31c2eb8Sdrh   */
2353832508b7Sdrh   pList = p->pEList;
2354832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
23556977fea8Sdrh     Expr *pExpr;
23566977fea8Sdrh     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
235717435752Sdrh       pList->a[i].zName =
235817435752Sdrh              sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
2359832508b7Sdrh     }
2360832508b7Sdrh   }
23611e536953Sdanielk1977   substExprList(db, p->pEList, iParent, pSub->pEList);
23621b2e0329Sdrh   if( isAgg ){
23631e536953Sdanielk1977     substExprList(db, p->pGroupBy, iParent, pSub->pEList);
23641e536953Sdanielk1977     substExpr(db, p->pHaving, iParent, pSub->pEList);
23651b2e0329Sdrh   }
2366174b6195Sdrh   if( pSub->pOrderBy ){
2367174b6195Sdrh     assert( p->pOrderBy==0 );
2368174b6195Sdrh     p->pOrderBy = pSub->pOrderBy;
2369174b6195Sdrh     pSub->pOrderBy = 0;
2370174b6195Sdrh   }else if( p->pOrderBy ){
23711e536953Sdanielk1977     substExprList(db, p->pOrderBy, iParent, pSub->pEList);
2372174b6195Sdrh   }
2373832508b7Sdrh   if( pSub->pWhere ){
237417435752Sdrh     pWhere = sqlite3ExprDup(db, pSub->pWhere);
2375832508b7Sdrh   }else{
2376832508b7Sdrh     pWhere = 0;
2377832508b7Sdrh   }
2378832508b7Sdrh   if( subqueryIsAgg ){
2379832508b7Sdrh     assert( p->pHaving==0 );
23801b2e0329Sdrh     p->pHaving = p->pWhere;
23811b2e0329Sdrh     p->pWhere = pWhere;
23821e536953Sdanielk1977     substExpr(db, p->pHaving, iParent, pSub->pEList);
238317435752Sdrh     p->pHaving = sqlite3ExprAnd(db, p->pHaving,
238417435752Sdrh                                 sqlite3ExprDup(db, pSub->pHaving));
23851b2e0329Sdrh     assert( p->pGroupBy==0 );
238617435752Sdrh     p->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
2387832508b7Sdrh   }else{
23881e536953Sdanielk1977     substExpr(db, p->pWhere, iParent, pSub->pEList);
238917435752Sdrh     p->pWhere = sqlite3ExprAnd(db, p->pWhere, pWhere);
2390832508b7Sdrh   }
2391c31c2eb8Sdrh 
2392c31c2eb8Sdrh   /* The flattened query is distinct if either the inner or the
2393c31c2eb8Sdrh   ** outer query is distinct.
2394c31c2eb8Sdrh   */
2395832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
23968c74a8caSdrh 
2397a58fdfb1Sdanielk1977   /*
2398a58fdfb1Sdanielk1977   ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2399ac83963aSdrh   **
2400ac83963aSdrh   ** One is tempted to try to add a and b to combine the limits.  But this
2401ac83963aSdrh   ** does not work if either limit is negative.
2402a58fdfb1Sdanielk1977   */
2403a2dc3b1aSdanielk1977   if( pSub->pLimit ){
2404a2dc3b1aSdanielk1977     p->pLimit = pSub->pLimit;
2405a2dc3b1aSdanielk1977     pSub->pLimit = 0;
2406df199a25Sdrh   }
24078c74a8caSdrh 
2408c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
2409c31c2eb8Sdrh   ** success.
2410c31c2eb8Sdrh   */
24114adee20fSdanielk1977   sqlite3SelectDelete(pSub);
2412832508b7Sdrh   return 1;
24131350b030Sdrh }
2414b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */
24151350b030Sdrh 
24161350b030Sdrh /*
24179562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it
24189562b551Sdrh ** is a simple min() or max() query.  If it is and this query can be
24199562b551Sdrh ** satisfied using a single seek to the beginning or end of an index,
2420e78e8284Sdrh ** then generate the code for this SELECT and return 1.  If this is not a
24219562b551Sdrh ** simple min() or max() query, then return 0;
24229562b551Sdrh **
24239562b551Sdrh ** A simply min() or max() query looks like this:
24249562b551Sdrh **
24259562b551Sdrh **    SELECT min(a) FROM table;
24269562b551Sdrh **    SELECT max(a) FROM table;
24279562b551Sdrh **
24289562b551Sdrh ** The query may have only a single table in its FROM argument.  There
24299562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
24309562b551Sdrh ** be the min() or max() of a single column of the table.  The column
24319562b551Sdrh ** in the min() or max() function must be indexed.
24329562b551Sdrh **
24334adee20fSdanielk1977 ** The parameters to this routine are the same as for sqlite3Select().
24349562b551Sdrh ** See the header comment on that routine for additional information.
24359562b551Sdrh */
24369562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
24379562b551Sdrh   Expr *pExpr;
24389562b551Sdrh   int iCol;
24399562b551Sdrh   Table *pTab;
24409562b551Sdrh   Index *pIdx;
24419562b551Sdrh   int base;
24429562b551Sdrh   Vdbe *v;
24439562b551Sdrh   int seekOp;
24446e17529eSdrh   ExprList *pEList, *pList, eList;
24459562b551Sdrh   struct ExprList_item eListItem;
24466e17529eSdrh   SrcList *pSrc;
2447ec7429aeSdrh   int brk;
2448da184236Sdanielk1977   int iDb;
24496e17529eSdrh 
24509562b551Sdrh   /* Check to see if this query is a simple min() or max() query.  Return
24519562b551Sdrh   ** zero if it is  not.
24529562b551Sdrh   */
24539562b551Sdrh   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
24546e17529eSdrh   pSrc = p->pSrc;
24556e17529eSdrh   if( pSrc->nSrc!=1 ) return 0;
24566e17529eSdrh   pEList = p->pEList;
24576e17529eSdrh   if( pEList->nExpr!=1 ) return 0;
24586e17529eSdrh   pExpr = pEList->a[0].pExpr;
24599562b551Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
24606e17529eSdrh   pList = pExpr->pList;
24616e17529eSdrh   if( pList==0 || pList->nExpr!=1 ) return 0;
24626977fea8Sdrh   if( pExpr->token.n!=3 ) return 0;
24632646da7eSdrh   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
24640bce8354Sdrh     seekOp = OP_Rewind;
24652646da7eSdrh   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
24660bce8354Sdrh     seekOp = OP_Last;
24670bce8354Sdrh   }else{
24680bce8354Sdrh     return 0;
24690bce8354Sdrh   }
24706e17529eSdrh   pExpr = pList->a[0].pExpr;
24719562b551Sdrh   if( pExpr->op!=TK_COLUMN ) return 0;
24729562b551Sdrh   iCol = pExpr->iColumn;
24736e17529eSdrh   pTab = pSrc->a[0].pTab;
24749562b551Sdrh 
2475a41c7497Sdanielk1977   /* This optimization cannot be used with virtual tables. */
2476a41c7497Sdanielk1977   if( IsVirtual(pTab) ) return 0;
2477c00da105Sdanielk1977 
24789562b551Sdrh   /* If we get to here, it means the query is of the correct form.
247917f71934Sdrh   ** Check to make sure we have an index and make pIdx point to the
248017f71934Sdrh   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
248117f71934Sdrh   ** key column, no index is necessary so set pIdx to NULL.  If no
248217f71934Sdrh   ** usable index is found, return 0.
24839562b551Sdrh   */
24849562b551Sdrh   if( iCol<0 ){
24859562b551Sdrh     pIdx = 0;
24869562b551Sdrh   }else{
2487dc1bdc4fSdanielk1977     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
2488206f3d96Sdrh     if( pColl==0 ) return 0;
24899562b551Sdrh     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
24909562b551Sdrh       assert( pIdx->nColumn>=1 );
2491b3bf556eSdanielk1977       if( pIdx->aiColumn[0]==iCol &&
2492b3bf556eSdanielk1977           0==sqlite3StrICmp(pIdx->azColl[0], pColl->zName) ){
2493b3bf556eSdanielk1977         break;
2494b3bf556eSdanielk1977       }
24959562b551Sdrh     }
24969562b551Sdrh     if( pIdx==0 ) return 0;
24979562b551Sdrh   }
24989562b551Sdrh 
2499e5f50722Sdrh   /* Identify column types if we will be using the callback.  This
25009562b551Sdrh   ** step is skipped if the output is going to a table or a memory cell.
2501e5f50722Sdrh   ** The column names have already been generated in the calling function.
25029562b551Sdrh   */
25034adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
25049562b551Sdrh   if( v==0 ) return 0;
25059562b551Sdrh 
25060c37e630Sdrh   /* If the output is destined for a temporary table, open that table.
25070c37e630Sdrh   */
2508b9bb7c18Sdrh   if( eDest==SRT_EphemTab ){
2509b9bb7c18Sdrh     sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 1);
25100c37e630Sdrh   }
25110c37e630Sdrh 
251217f71934Sdrh   /* Generating code to find the min or the max.  Basically all we have
251317f71934Sdrh   ** to do is find the first or the last entry in the chosen index.  If
251417f71934Sdrh   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
251517f71934Sdrh   ** or last entry in the main table.
25169562b551Sdrh   */
2517da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2518b9bb7c18Sdrh   assert( iDb>=0 || pTab->isEphem );
2519da184236Sdanielk1977   sqlite3CodeVerifySchema(pParse, iDb);
2520c00da105Sdanielk1977   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
25216e17529eSdrh   base = pSrc->a[0].iCursor;
2522ec7429aeSdrh   brk = sqlite3VdbeMakeLabel(v);
2523ec7429aeSdrh   computeLimitRegisters(pParse, p, brk);
25246e17529eSdrh   if( pSrc->a[0].pSelect==0 ){
2525c00da105Sdanielk1977     sqlite3OpenTable(pParse, base, iDb, pTab, OP_OpenRead);
25266e17529eSdrh   }
25279562b551Sdrh   if( pIdx==0 ){
25284adee20fSdanielk1977     sqlite3VdbeAddOp(v, seekOp, base, 0);
25299562b551Sdrh   }else{
25303719d7f9Sdanielk1977     /* Even though the cursor used to open the index here is closed
25313719d7f9Sdanielk1977     ** as soon as a single value has been read from it, allocate it
25323719d7f9Sdanielk1977     ** using (pParse->nTab++) to prevent the cursor id from being
25333719d7f9Sdanielk1977     ** reused. This is important for statements of the form
25343719d7f9Sdanielk1977     ** "INSERT INTO x SELECT max() FROM x".
25353719d7f9Sdanielk1977     */
25363719d7f9Sdanielk1977     int iIdx;
2537b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
25383719d7f9Sdanielk1977     iIdx = pParse->nTab++;
2539da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
2540da184236Sdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
25413719d7f9Sdanielk1977     sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
2542b3bf556eSdanielk1977         (char*)pKey, P3_KEYINFO_HANDOFF);
25439eb516c0Sdrh     if( seekOp==OP_Rewind ){
2544f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
25451af3fdb4Sdrh       sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
25461af3fdb4Sdrh       seekOp = OP_MoveGt;
25479eb516c0Sdrh     }
2548309be024Sdrh     if( pIdx->aSortOrder[0]==SQLITE_SO_DESC ){
2549309be024Sdrh       /* Ticket #2514: invert the seek operator if we are using
2550309be024Sdrh       ** a descending index. */
2551309be024Sdrh       if( seekOp==OP_Last ){
2552309be024Sdrh         seekOp = OP_Rewind;
2553309be024Sdrh       }else{
2554309be024Sdrh         assert( seekOp==OP_MoveGt );
2555309be024Sdrh         seekOp = OP_MoveLt;
2556309be024Sdrh       }
2557309be024Sdrh     }
25583719d7f9Sdanielk1977     sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
2559f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
25603719d7f9Sdanielk1977     sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
25617cf6e4deSdrh     sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
25629562b551Sdrh   }
25635cf8e8c7Sdrh   eList.nExpr = 1;
25645cf8e8c7Sdrh   memset(&eListItem, 0, sizeof(eListItem));
25655cf8e8c7Sdrh   eList.a = &eListItem;
25665cf8e8c7Sdrh   eList.a[0].pExpr = pExpr;
2567ec7429aeSdrh   selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0);
2568ec7429aeSdrh   sqlite3VdbeResolveLabel(v, brk);
25694adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Close, base, 0);
25706e17529eSdrh 
25719562b551Sdrh   return 1;
25729562b551Sdrh }
25739562b551Sdrh 
25749562b551Sdrh /*
2575290c1948Sdrh ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement.  Return
2576290c1948Sdrh ** the number of errors seen.
2577290c1948Sdrh **
2578290c1948Sdrh ** An ORDER BY or GROUP BY is a list of expressions.  If any expression
2579290c1948Sdrh ** is an integer constant, then that expression is replaced by the
2580290c1948Sdrh ** corresponding entry in the result set.
2581290c1948Sdrh */
2582290c1948Sdrh static int processOrderGroupBy(
2583b3bce662Sdanielk1977   NameContext *pNC,     /* Name context of the SELECT statement. */
2584290c1948Sdrh   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
2585290c1948Sdrh   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
2586290c1948Sdrh ){
2587290c1948Sdrh   int i;
2588b3bce662Sdanielk1977   ExprList *pEList = pNC->pEList;     /* The result set of the SELECT */
2589b3bce662Sdanielk1977   Parse *pParse = pNC->pParse;     /* The result set of the SELECT */
2590b3bce662Sdanielk1977   assert( pEList );
2591b3bce662Sdanielk1977 
2592290c1948Sdrh   if( pOrderBy==0 ) return 0;
2593e5c941b8Sdrh   if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){
2594e5c941b8Sdrh     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
2595e5c941b8Sdrh     return 1;
2596e5c941b8Sdrh   }
2597290c1948Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
2598290c1948Sdrh     int iCol;
2599290c1948Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
2600b3bce662Sdanielk1977     if( sqlite3ExprIsInteger(pE, &iCol) ){
2601b3bce662Sdanielk1977       if( iCol>0 && iCol<=pEList->nExpr ){
26028b4c40d8Sdrh         CollSeq *pColl = pE->pColl;
26038b4c40d8Sdrh         int flags = pE->flags & EP_ExpCollate;
2604290c1948Sdrh         sqlite3ExprDelete(pE);
260517435752Sdrh         pE = sqlite3ExprDup(pParse->db, pEList->a[iCol-1].pExpr);
260617435752Sdrh         pOrderBy->a[i].pExpr = pE;
26078b4c40d8Sdrh         if( pColl && flags ){
26088b4c40d8Sdrh           pE->pColl = pColl;
26098b4c40d8Sdrh           pE->flags |= flags;
26108b4c40d8Sdrh         }
2611b3bce662Sdanielk1977       }else{
2612290c1948Sdrh         sqlite3ErrorMsg(pParse,
2613290c1948Sdrh            "%s BY column number %d out of range - should be "
2614290c1948Sdrh            "between 1 and %d", zType, iCol, pEList->nExpr);
2615290c1948Sdrh         return 1;
2616290c1948Sdrh       }
2617290c1948Sdrh     }
2618b3bce662Sdanielk1977     if( sqlite3ExprResolveNames(pNC, pE) ){
2619b3bce662Sdanielk1977       return 1;
2620b3bce662Sdanielk1977     }
2621290c1948Sdrh   }
2622290c1948Sdrh   return 0;
2623290c1948Sdrh }
2624290c1948Sdrh 
2625290c1948Sdrh /*
2626b3bce662Sdanielk1977 ** This routine resolves any names used in the result set of the
2627b3bce662Sdanielk1977 ** supplied SELECT statement. If the SELECT statement being resolved
2628b3bce662Sdanielk1977 ** is a sub-select, then pOuterNC is a pointer to the NameContext
2629b3bce662Sdanielk1977 ** of the parent SELECT.
2630b3bce662Sdanielk1977 */
2631b3bce662Sdanielk1977 int sqlite3SelectResolve(
2632b3bce662Sdanielk1977   Parse *pParse,         /* The parser context */
2633b3bce662Sdanielk1977   Select *p,             /* The SELECT statement being coded. */
2634b3bce662Sdanielk1977   NameContext *pOuterNC  /* The outer name context. May be NULL. */
2635b3bce662Sdanielk1977 ){
2636b3bce662Sdanielk1977   ExprList *pEList;          /* Result set. */
2637b3bce662Sdanielk1977   int i;                     /* For-loop variable used in multiple places */
2638b3bce662Sdanielk1977   NameContext sNC;           /* Local name-context */
263913449892Sdrh   ExprList *pGroupBy;        /* The group by clause */
2640b3bce662Sdanielk1977 
2641b3bce662Sdanielk1977   /* If this routine has run before, return immediately. */
2642b3bce662Sdanielk1977   if( p->isResolved ){
2643b3bce662Sdanielk1977     assert( !pOuterNC );
2644b3bce662Sdanielk1977     return SQLITE_OK;
2645b3bce662Sdanielk1977   }
2646b3bce662Sdanielk1977   p->isResolved = 1;
2647b3bce662Sdanielk1977 
2648b3bce662Sdanielk1977   /* If there have already been errors, do nothing. */
2649b3bce662Sdanielk1977   if( pParse->nErr>0 ){
2650b3bce662Sdanielk1977     return SQLITE_ERROR;
2651b3bce662Sdanielk1977   }
2652b3bce662Sdanielk1977 
2653b3bce662Sdanielk1977   /* Prepare the select statement. This call will allocate all cursors
2654b3bce662Sdanielk1977   ** required to handle the tables and subqueries in the FROM clause.
2655b3bce662Sdanielk1977   */
2656b3bce662Sdanielk1977   if( prepSelectStmt(pParse, p) ){
2657b3bce662Sdanielk1977     return SQLITE_ERROR;
2658b3bce662Sdanielk1977   }
2659b3bce662Sdanielk1977 
2660a2dc3b1aSdanielk1977   /* Resolve the expressions in the LIMIT and OFFSET clauses. These
2661a2dc3b1aSdanielk1977   ** are not allowed to refer to any names, so pass an empty NameContext.
2662a2dc3b1aSdanielk1977   */
2663ffe07b2dSdrh   memset(&sNC, 0, sizeof(sNC));
2664b3bce662Sdanielk1977   sNC.pParse = pParse;
2665a2dc3b1aSdanielk1977   if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2666a2dc3b1aSdanielk1977       sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2667a2dc3b1aSdanielk1977     return SQLITE_ERROR;
2668a2dc3b1aSdanielk1977   }
2669a2dc3b1aSdanielk1977 
2670a2dc3b1aSdanielk1977   /* Set up the local name-context to pass to ExprResolveNames() to
2671a2dc3b1aSdanielk1977   ** resolve the expression-list.
2672a2dc3b1aSdanielk1977   */
2673a2dc3b1aSdanielk1977   sNC.allowAgg = 1;
2674a2dc3b1aSdanielk1977   sNC.pSrcList = p->pSrc;
2675a2dc3b1aSdanielk1977   sNC.pNext = pOuterNC;
2676b3bce662Sdanielk1977 
2677b3bce662Sdanielk1977   /* Resolve names in the result set. */
2678b3bce662Sdanielk1977   pEList = p->pEList;
2679b3bce662Sdanielk1977   if( !pEList ) return SQLITE_ERROR;
2680b3bce662Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
2681b3bce662Sdanielk1977     Expr *pX = pEList->a[i].pExpr;
2682b3bce662Sdanielk1977     if( sqlite3ExprResolveNames(&sNC, pX) ){
2683b3bce662Sdanielk1977       return SQLITE_ERROR;
2684b3bce662Sdanielk1977     }
2685b3bce662Sdanielk1977   }
2686b3bce662Sdanielk1977 
2687b3bce662Sdanielk1977   /* If there are no aggregate functions in the result-set, and no GROUP BY
2688b3bce662Sdanielk1977   ** expression, do not allow aggregates in any of the other expressions.
2689b3bce662Sdanielk1977   */
2690b3bce662Sdanielk1977   assert( !p->isAgg );
269113449892Sdrh   pGroupBy = p->pGroupBy;
269213449892Sdrh   if( pGroupBy || sNC.hasAgg ){
2693b3bce662Sdanielk1977     p->isAgg = 1;
2694b3bce662Sdanielk1977   }else{
2695b3bce662Sdanielk1977     sNC.allowAgg = 0;
2696b3bce662Sdanielk1977   }
2697b3bce662Sdanielk1977 
2698b3bce662Sdanielk1977   /* If a HAVING clause is present, then there must be a GROUP BY clause.
2699b3bce662Sdanielk1977   */
270013449892Sdrh   if( p->pHaving && !pGroupBy ){
2701b3bce662Sdanielk1977     sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2702b3bce662Sdanielk1977     return SQLITE_ERROR;
2703b3bce662Sdanielk1977   }
2704b3bce662Sdanielk1977 
2705b3bce662Sdanielk1977   /* Add the expression list to the name-context before parsing the
2706b3bce662Sdanielk1977   ** other expressions in the SELECT statement. This is so that
2707b3bce662Sdanielk1977   ** expressions in the WHERE clause (etc.) can refer to expressions by
2708b3bce662Sdanielk1977   ** aliases in the result set.
2709b3bce662Sdanielk1977   **
2710b3bce662Sdanielk1977   ** Minor point: If this is the case, then the expression will be
2711b3bce662Sdanielk1977   ** re-evaluated for each reference to it.
2712b3bce662Sdanielk1977   */
2713b3bce662Sdanielk1977   sNC.pEList = p->pEList;
2714b3bce662Sdanielk1977   if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2715994c80afSdrh      sqlite3ExprResolveNames(&sNC, p->pHaving) ){
2716b3bce662Sdanielk1977     return SQLITE_ERROR;
2717b3bce662Sdanielk1977   }
2718994c80afSdrh   if( p->pPrior==0 ){
2719994c80afSdrh     if( processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
2720994c80afSdrh         processOrderGroupBy(&sNC, pGroupBy, "GROUP") ){
2721994c80afSdrh       return SQLITE_ERROR;
2722994c80afSdrh     }
2723994c80afSdrh   }
2724b3bce662Sdanielk1977 
27251e536953Sdanielk1977   if( pParse->db->mallocFailed ){
27269afe689eSdanielk1977     return SQLITE_NOMEM;
27279afe689eSdanielk1977   }
27289afe689eSdanielk1977 
272913449892Sdrh   /* Make sure the GROUP BY clause does not contain aggregate functions.
273013449892Sdrh   */
273113449892Sdrh   if( pGroupBy ){
273213449892Sdrh     struct ExprList_item *pItem;
273313449892Sdrh 
273413449892Sdrh     for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
273513449892Sdrh       if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
273613449892Sdrh         sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
273713449892Sdrh             "the GROUP BY clause");
273813449892Sdrh         return SQLITE_ERROR;
273913449892Sdrh       }
274013449892Sdrh     }
274113449892Sdrh   }
274213449892Sdrh 
2743f6bbe022Sdrh   /* If this is one SELECT of a compound, be sure to resolve names
2744f6bbe022Sdrh   ** in the other SELECTs.
2745f6bbe022Sdrh   */
2746f6bbe022Sdrh   if( p->pPrior ){
2747f6bbe022Sdrh     return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC);
2748f6bbe022Sdrh   }else{
2749b3bce662Sdanielk1977     return SQLITE_OK;
2750b3bce662Sdanielk1977   }
2751f6bbe022Sdrh }
2752b3bce662Sdanielk1977 
2753b3bce662Sdanielk1977 /*
275413449892Sdrh ** Reset the aggregate accumulator.
275513449892Sdrh **
275613449892Sdrh ** The aggregate accumulator is a set of memory cells that hold
275713449892Sdrh ** intermediate results while calculating an aggregate.  This
275813449892Sdrh ** routine simply stores NULLs in all of those memory cells.
2759b3bce662Sdanielk1977 */
276013449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
276113449892Sdrh   Vdbe *v = pParse->pVdbe;
276213449892Sdrh   int i;
2763c99130fdSdrh   struct AggInfo_func *pFunc;
276413449892Sdrh   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
276513449892Sdrh     return;
276613449892Sdrh   }
276713449892Sdrh   for(i=0; i<pAggInfo->nColumn; i++){
2768d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0);
276913449892Sdrh   }
2770c99130fdSdrh   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
2771d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0);
2772c99130fdSdrh     if( pFunc->iDistinct>=0 ){
2773c99130fdSdrh       Expr *pE = pFunc->pExpr;
2774c99130fdSdrh       if( pE->pList==0 || pE->pList->nExpr!=1 ){
2775c99130fdSdrh         sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
2776c99130fdSdrh            "by an expression");
2777c99130fdSdrh         pFunc->iDistinct = -1;
2778c99130fdSdrh       }else{
2779c99130fdSdrh         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
2780b9bb7c18Sdrh         sqlite3VdbeOp3(v, OP_OpenEphemeral, pFunc->iDistinct, 0,
2781c99130fdSdrh                           (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
2782c99130fdSdrh       }
2783c99130fdSdrh     }
278413449892Sdrh   }
2785b3bce662Sdanielk1977 }
2786b3bce662Sdanielk1977 
2787b3bce662Sdanielk1977 /*
278813449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function
278913449892Sdrh ** in the AggInfo structure.
2790b3bce662Sdanielk1977 */
279113449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
279213449892Sdrh   Vdbe *v = pParse->pVdbe;
279313449892Sdrh   int i;
279413449892Sdrh   struct AggInfo_func *pF;
279513449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
2796a10a34b8Sdrh     ExprList *pList = pF->pExpr->pList;
2797a10a34b8Sdrh     sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0,
2798a10a34b8Sdrh                       (void*)pF->pFunc, P3_FUNCDEF);
2799b3bce662Sdanielk1977   }
280013449892Sdrh }
280113449892Sdrh 
280213449892Sdrh /*
280313449892Sdrh ** Update the accumulator memory cells for an aggregate based on
280413449892Sdrh ** the current cursor position.
280513449892Sdrh */
280613449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
280713449892Sdrh   Vdbe *v = pParse->pVdbe;
280813449892Sdrh   int i;
280913449892Sdrh   struct AggInfo_func *pF;
281013449892Sdrh   struct AggInfo_col *pC;
281113449892Sdrh 
281213449892Sdrh   pAggInfo->directMode = 1;
281313449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
281413449892Sdrh     int nArg;
2815c99130fdSdrh     int addrNext = 0;
281613449892Sdrh     ExprList *pList = pF->pExpr->pList;
281713449892Sdrh     if( pList ){
281813449892Sdrh       nArg = pList->nExpr;
281913449892Sdrh       sqlite3ExprCodeExprList(pParse, pList);
282013449892Sdrh     }else{
282113449892Sdrh       nArg = 0;
282213449892Sdrh     }
2823c99130fdSdrh     if( pF->iDistinct>=0 ){
2824c99130fdSdrh       addrNext = sqlite3VdbeMakeLabel(v);
2825c99130fdSdrh       assert( nArg==1 );
2826f8875400Sdrh       codeDistinct(v, pF->iDistinct, addrNext, 1);
2827c99130fdSdrh     }
282813449892Sdrh     if( pF->pFunc->needCollSeq ){
282913449892Sdrh       CollSeq *pColl = 0;
283013449892Sdrh       struct ExprList_item *pItem;
283113449892Sdrh       int j;
283243617e9aSdrh       assert( pList!=0 );  /* pList!=0 if pF->pFunc->needCollSeq is true */
283343617e9aSdrh       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
283413449892Sdrh         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
283513449892Sdrh       }
283613449892Sdrh       if( !pColl ){
283713449892Sdrh         pColl = pParse->db->pDfltColl;
283813449892Sdrh       }
283913449892Sdrh       sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
284013449892Sdrh     }
284113449892Sdrh     sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF);
2842c99130fdSdrh     if( addrNext ){
2843c99130fdSdrh       sqlite3VdbeResolveLabel(v, addrNext);
2844c99130fdSdrh     }
284513449892Sdrh   }
284613449892Sdrh   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
28475774b806Sdrh     sqlite3ExprCode(pParse, pC->pExpr);
284813449892Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1);
284913449892Sdrh   }
285013449892Sdrh   pAggInfo->directMode = 0;
285113449892Sdrh }
285213449892Sdrh 
2853b3bce662Sdanielk1977 
2854b3bce662Sdanielk1977 /*
28559bb61fe7Sdrh ** Generate code for the given SELECT statement.
28569bb61fe7Sdrh **
2857fef5208cSdrh ** The results are distributed in various ways depending on the
2858fef5208cSdrh ** value of eDest and iParm.
2859fef5208cSdrh **
2860fef5208cSdrh **     eDest Value       Result
2861fef5208cSdrh **     ------------    -------------------------------------------
2862fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
2863fef5208cSdrh **
2864fef5208cSdrh **     SRT_Mem         Store first result in memory cell iParm
2865fef5208cSdrh **
2866e014a838Sdanielk1977 **     SRT_Set         Store results as keys of table iParm.
2867fef5208cSdrh **
286882c3d636Sdrh **     SRT_Union       Store results as a key in a temporary table iParm
286982c3d636Sdrh **
28704b11c6d3Sjplyon **     SRT_Except      Remove results from the temporary table iParm.
2871c4a3c779Sdrh **
2872c4a3c779Sdrh **     SRT_Table       Store results in temporary table iParm
28739bb61fe7Sdrh **
2874e78e8284Sdrh ** The table above is incomplete.  Additional eDist value have be added
2875e78e8284Sdrh ** since this comment was written.  See the selectInnerLoop() function for
2876e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings.
2877e78e8284Sdrh **
28789bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
28799bb61fe7Sdrh ** encountered, then an appropriate error message is left in
28809bb61fe7Sdrh ** pParse->zErrMsg.
28819bb61fe7Sdrh **
28829bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
28839bb61fe7Sdrh ** calling function needs to do that.
28841b2e0329Sdrh **
28851b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
28861b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
28871b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
28881b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
28891b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
28901b2e0329Sdrh ** can be changed.
2891e78e8284Sdrh **
2892e78e8284Sdrh ** Example 1:   The meaning of the pParent parameter.
2893e78e8284Sdrh **
2894e78e8284Sdrh **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2895e78e8284Sdrh **    \                      \_______ subquery _______/        /
2896e78e8284Sdrh **     \                                                      /
2897e78e8284Sdrh **      \____________________ outer query ___________________/
2898e78e8284Sdrh **
2899e78e8284Sdrh ** This routine is called for the outer query first.   For that call,
2900e78e8284Sdrh ** pParent will be NULL.  During the processing of the outer query, this
2901e78e8284Sdrh ** routine is called recursively to handle the subquery.  For the recursive
2902e78e8284Sdrh ** call, pParent will point to the outer query.  Because the subquery is
2903e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will
2904e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.)
29059bb61fe7Sdrh */
29064adee20fSdanielk1977 int sqlite3Select(
2907cce7d176Sdrh   Parse *pParse,         /* The parser context */
29089bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
2909e78e8284Sdrh   int eDest,             /* How to dispose of the results */
2910e78e8284Sdrh   int iParm,             /* A parameter used by the eDest disposal method */
2911832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
2912832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
291384ac9d02Sdanielk1977   int *pParentAgg,       /* True if pParent uses aggregate functions */
2914b3bce662Sdanielk1977   char *aff              /* If eDest is SRT_Union, the affinity string */
2915cce7d176Sdrh ){
291613449892Sdrh   int i, j;              /* Loop counters */
291713449892Sdrh   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
291813449892Sdrh   Vdbe *v;               /* The virtual machine under construction */
2919b3bce662Sdanielk1977   int isAgg;             /* True for select lists like "count(*)" */
2920a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
2921ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
29229bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
29239bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
29242282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
29252282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
292619a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
292719a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
29281d83f052Sdrh   int rc = 1;            /* Value to return from this function */
2929b9bb7c18Sdrh   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
293013449892Sdrh   AggInfo sAggInfo;      /* Information used by aggregate queries */
2931ec7429aeSdrh   int iEnd;              /* Address of the end of the query */
293217435752Sdrh   sqlite3 *db;           /* The database connection */
29339bb61fe7Sdrh 
293417435752Sdrh   db = pParse->db;
293517435752Sdrh   if( p==0 || db->mallocFailed || pParse->nErr ){
29366f7adc8aSdrh     return 1;
29376f7adc8aSdrh   }
29384adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
293913449892Sdrh   memset(&sAggInfo, 0, sizeof(sAggInfo));
2940daffd0e5Sdrh 
2941b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
294282c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
294382c3d636Sdrh   */
294482c3d636Sdrh   if( p->pPrior ){
29450342b1f5Sdrh     if( p->pRightmost==0 ){
29460342b1f5Sdrh       Select *pLoop;
29470325d873Sdrh       int cnt = 0;
29480325d873Sdrh       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
29490342b1f5Sdrh         pLoop->pRightmost = p;
29500342b1f5Sdrh       }
29510325d873Sdrh       if( SQLITE_MAX_COMPOUND_SELECT>0 && cnt>SQLITE_MAX_COMPOUND_SELECT ){
29520325d873Sdrh         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
29530325d873Sdrh         return 1;
29540325d873Sdrh       }
29550342b1f5Sdrh     }
295684ac9d02Sdanielk1977     return multiSelect(pParse, p, eDest, iParm, aff);
295782c3d636Sdrh   }
2958b7f9164eSdrh #endif
295982c3d636Sdrh 
2960b3bce662Sdanielk1977   pOrderBy = p->pOrderBy;
296113449892Sdrh   if( IgnorableOrderby(eDest) ){
2962b3bce662Sdanielk1977     p->pOrderBy = 0;
2963b3bce662Sdanielk1977   }
2964b3bce662Sdanielk1977   if( sqlite3SelectResolve(pParse, p, 0) ){
2965b3bce662Sdanielk1977     goto select_end;
2966b3bce662Sdanielk1977   }
2967b3bce662Sdanielk1977   p->pOrderBy = pOrderBy;
2968b3bce662Sdanielk1977 
296982c3d636Sdrh   /* Make local copies of the parameters for this query.
297082c3d636Sdrh   */
29719bb61fe7Sdrh   pTabList = p->pSrc;
29729bb61fe7Sdrh   pWhere = p->pWhere;
29732282792aSdrh   pGroupBy = p->pGroupBy;
29742282792aSdrh   pHaving = p->pHaving;
2975b3bce662Sdanielk1977   isAgg = p->isAgg;
297619a775c2Sdrh   isDistinct = p->isDistinct;
2977b3bce662Sdanielk1977   pEList = p->pEList;
2978b3bce662Sdanielk1977   if( pEList==0 ) goto select_end;
29799bb61fe7Sdrh 
29809bb61fe7Sdrh   /*
29819bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
29829bb61fe7Sdrh   ** errors before this routine starts.
29839bb61fe7Sdrh   */
29841d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
2985cce7d176Sdrh 
29862282792aSdrh   /* If writing to memory or generating a set
29872282792aSdrh   ** only a single column may be output.
298819a775c2Sdrh   */
298993758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
2990e305f43fSdrh   if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){
29911d83f052Sdrh     goto select_end;
299219a775c2Sdrh   }
299393758c8dSdanielk1977 #endif
299419a775c2Sdrh 
2995c926afbcSdrh   /* ORDER BY is ignored for some destinations.
29962282792aSdrh   */
299713449892Sdrh   if( IgnorableOrderby(eDest) ){
2998acd4c695Sdrh     pOrderBy = 0;
29992282792aSdrh   }
30002282792aSdrh 
3001d820cb1bSdrh   /* Begin generating code.
3002d820cb1bSdrh   */
30034adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
3004d820cb1bSdrh   if( v==0 ) goto select_end;
3005d820cb1bSdrh 
3006d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
3007d820cb1bSdrh   */
300851522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3009ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
3010742f947bSdanielk1977     const char *zSavedAuthContext = 0;
3011c31c2eb8Sdrh     int needRestoreContext;
301213449892Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
3013c31c2eb8Sdrh 
30141787ccabSdanielk1977     if( pItem->pSelect==0 || pItem->isPopulated ) continue;
301513449892Sdrh     if( pItem->zName!=0 ){
30165cf590c1Sdrh       zSavedAuthContext = pParse->zAuthContext;
301713449892Sdrh       pParse->zAuthContext = pItem->zName;
3018c31c2eb8Sdrh       needRestoreContext = 1;
3019c31c2eb8Sdrh     }else{
3020c31c2eb8Sdrh       needRestoreContext = 0;
30215cf590c1Sdrh     }
3022*e6a58a4eSdanielk1977 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
3023fc976065Sdanielk1977     /* Increment Parse.nHeight by the height of the largest expression
3024fc976065Sdanielk1977     ** tree refered to by this, the parent select. The child select
3025fc976065Sdanielk1977     ** may contain expression trees of at most
3026fc976065Sdanielk1977     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
3027fc976065Sdanielk1977     ** more conservative than necessary, but much easier than enforcing
3028fc976065Sdanielk1977     ** an exact limit.
3029fc976065Sdanielk1977     */
3030fc976065Sdanielk1977     pParse->nHeight += sqlite3SelectExprHeight(p);
3031fc976065Sdanielk1977 #endif
3032b9bb7c18Sdrh     sqlite3Select(pParse, pItem->pSelect, SRT_EphemTab,
303313449892Sdrh                  pItem->iCursor, p, i, &isAgg, 0);
3034*e6a58a4eSdanielk1977 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
3035fc976065Sdanielk1977     pParse->nHeight -= sqlite3SelectExprHeight(p);
3036fc976065Sdanielk1977 #endif
3037c31c2eb8Sdrh     if( needRestoreContext ){
30385cf590c1Sdrh       pParse->zAuthContext = zSavedAuthContext;
30395cf590c1Sdrh     }
3040832508b7Sdrh     pTabList = p->pSrc;
3041832508b7Sdrh     pWhere = p->pWhere;
304213449892Sdrh     if( !IgnorableOrderby(eDest) ){
3043832508b7Sdrh       pOrderBy = p->pOrderBy;
3044acd4c695Sdrh     }
3045832508b7Sdrh     pGroupBy = p->pGroupBy;
3046832508b7Sdrh     pHaving = p->pHaving;
3047832508b7Sdrh     isDistinct = p->isDistinct;
30481b2e0329Sdrh   }
304951522cd3Sdrh #endif
30501b2e0329Sdrh 
30516e17529eSdrh   /* Check for the special case of a min() or max() function by itself
30526e17529eSdrh   ** in the result set.
30536e17529eSdrh   */
30546e17529eSdrh   if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
30556e17529eSdrh     rc = 0;
30566e17529eSdrh     goto select_end;
30576e17529eSdrh   }
30586e17529eSdrh 
30591b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
30601b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
30611b2e0329Sdrh   */
3062b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
30631b2e0329Sdrh   if( pParent && pParentAgg &&
306417435752Sdrh       flattenSubquery(db, pParent, parentTab, *pParentAgg, isAgg) ){
30651b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
3066b3bce662Sdanielk1977     goto select_end;
30671b2e0329Sdrh   }
3068b7f9164eSdrh #endif
3069832508b7Sdrh 
30708b4c40d8Sdrh   /* If there is an ORDER BY clause, then this sorting
30718b4c40d8Sdrh   ** index might end up being unused if the data can be
30729d2985c7Sdrh   ** extracted in pre-sorted order.  If that is the case, then the
3073b9bb7c18Sdrh   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
30749d2985c7Sdrh   ** we figure out that the sorting index is not needed.  The addrSortIndex
30759d2985c7Sdrh   ** variable is used to facilitate that change.
30767cedc8d4Sdanielk1977   */
30777cedc8d4Sdanielk1977   if( pOrderBy ){
30780342b1f5Sdrh     KeyInfo *pKeyInfo;
30797cedc8d4Sdanielk1977     if( pParse->nErr ){
30807cedc8d4Sdanielk1977       goto select_end;
30817cedc8d4Sdanielk1977     }
30820342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
30839d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
3084b9bb7c18Sdrh     p->addrOpenEphm[2] = addrSortIndex =
30851e31e0b2Sdrh       sqlite3VdbeOp3(v, OP_OpenEphemeral, pOrderBy->iECursor, pOrderBy->nExpr+2,                     (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
30869d2985c7Sdrh   }else{
30879d2985c7Sdrh     addrSortIndex = -1;
30887cedc8d4Sdanielk1977   }
30897cedc8d4Sdanielk1977 
30902d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
30912d0794e3Sdrh   */
3092b9bb7c18Sdrh   if( eDest==SRT_EphemTab ){
3093b9bb7c18Sdrh     sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, pEList->nExpr);
30942d0794e3Sdrh   }
30952d0794e3Sdrh 
3096f42bacc2Sdrh   /* Set the limiter.
3097f42bacc2Sdrh   */
3098f42bacc2Sdrh   iEnd = sqlite3VdbeMakeLabel(v);
3099f42bacc2Sdrh   computeLimitRegisters(pParse, p, iEnd);
3100f42bacc2Sdrh 
3101dece1a84Sdrh   /* Open a virtual index to use for the distinct set.
3102cce7d176Sdrh   */
310319a775c2Sdrh   if( isDistinct ){
31040342b1f5Sdrh     KeyInfo *pKeyInfo;
3105832508b7Sdrh     distinct = pParse->nTab++;
31060342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
3107b9bb7c18Sdrh     sqlite3VdbeOp3(v, OP_OpenEphemeral, distinct, 0,
31080342b1f5Sdrh                         (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
3109832508b7Sdrh   }else{
3110832508b7Sdrh     distinct = -1;
3111efb7251dSdrh   }
3112832508b7Sdrh 
311313449892Sdrh   /* Aggregate and non-aggregate queries are handled differently */
311413449892Sdrh   if( !isAgg && pGroupBy==0 ){
311513449892Sdrh     /* This case is for non-aggregate queries
311613449892Sdrh     ** Begin the database scan
3117832508b7Sdrh     */
311813449892Sdrh     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy);
31191d83f052Sdrh     if( pWInfo==0 ) goto select_end;
3120cce7d176Sdrh 
3121b9bb7c18Sdrh     /* If sorting index that was created by a prior OP_OpenEphemeral
3122b9bb7c18Sdrh     ** instruction ended up not being needed, then change the OP_OpenEphemeral
31239d2985c7Sdrh     ** into an OP_Noop.
31249d2985c7Sdrh     */
31259d2985c7Sdrh     if( addrSortIndex>=0 && pOrderBy==0 ){
3126f8875400Sdrh       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
3127b9bb7c18Sdrh       p->addrOpenEphm[2] = -1;
31289d2985c7Sdrh     }
31299d2985c7Sdrh 
313013449892Sdrh     /* Use the standard inner loop
3131cce7d176Sdrh     */
3132df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
313384ac9d02Sdanielk1977                     iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
31341d83f052Sdrh        goto select_end;
3135cce7d176Sdrh     }
31362282792aSdrh 
3137cce7d176Sdrh     /* End the database scan loop.
3138cce7d176Sdrh     */
31394adee20fSdanielk1977     sqlite3WhereEnd(pWInfo);
314013449892Sdrh   }else{
314113449892Sdrh     /* This is the processing for aggregate queries */
314213449892Sdrh     NameContext sNC;    /* Name context for processing aggregate information */
314313449892Sdrh     int iAMem;          /* First Mem address for storing current GROUP BY */
314413449892Sdrh     int iBMem;          /* First Mem address for previous GROUP BY */
314513449892Sdrh     int iUseFlag;       /* Mem address holding flag indicating that at least
314613449892Sdrh                         ** one row of the input to the aggregator has been
314713449892Sdrh                         ** processed */
314813449892Sdrh     int iAbortFlag;     /* Mem address which causes query abort if positive */
314913449892Sdrh     int groupBySort;    /* Rows come from source in GROUP BY order */
3150cce7d176Sdrh 
315113449892Sdrh 
315213449892Sdrh     /* The following variables hold addresses or labels for parts of the
315313449892Sdrh     ** virtual machine program we are putting together */
315413449892Sdrh     int addrOutputRow;      /* Start of subroutine that outputs a result row */
315513449892Sdrh     int addrSetAbort;       /* Set the abort flag and return */
315613449892Sdrh     int addrInitializeLoop; /* Start of code that initializes the input loop */
315713449892Sdrh     int addrTopOfLoop;      /* Top of the input loop */
315813449892Sdrh     int addrGroupByChange;  /* Code that runs when any GROUP BY term changes */
315913449892Sdrh     int addrProcessRow;     /* Code to process a single input row */
316013449892Sdrh     int addrEnd;            /* End of all processing */
3161b9bb7c18Sdrh     int addrSortingIdx;     /* The OP_OpenEphemeral for the sorting index */
3162e313382eSdrh     int addrReset;          /* Subroutine for resetting the accumulator */
316313449892Sdrh 
316413449892Sdrh     addrEnd = sqlite3VdbeMakeLabel(v);
316513449892Sdrh 
316613449892Sdrh     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
316713449892Sdrh     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
316813449892Sdrh     ** SELECT statement.
31692282792aSdrh     */
317013449892Sdrh     memset(&sNC, 0, sizeof(sNC));
317113449892Sdrh     sNC.pParse = pParse;
317213449892Sdrh     sNC.pSrcList = pTabList;
317313449892Sdrh     sNC.pAggInfo = &sAggInfo;
317413449892Sdrh     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
31759d2985c7Sdrh     sAggInfo.pGroupBy = pGroupBy;
317613449892Sdrh     if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){
31771d83f052Sdrh       goto select_end;
31782282792aSdrh     }
317913449892Sdrh     if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){
318013449892Sdrh       goto select_end;
31812282792aSdrh     }
318213449892Sdrh     if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
318313449892Sdrh       goto select_end;
318413449892Sdrh     }
318513449892Sdrh     sAggInfo.nAccumulator = sAggInfo.nColumn;
318613449892Sdrh     for(i=0; i<sAggInfo.nFunc; i++){
318713449892Sdrh       if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
318813449892Sdrh         goto select_end;
318913449892Sdrh       }
319013449892Sdrh     }
319117435752Sdrh     if( db->mallocFailed ) goto select_end;
319213449892Sdrh 
319313449892Sdrh     /* Processing for aggregates with GROUP BY is very different and
319413449892Sdrh     ** much more complex tha aggregates without a GROUP BY.
319513449892Sdrh     */
319613449892Sdrh     if( pGroupBy ){
319713449892Sdrh       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
319813449892Sdrh 
319913449892Sdrh       /* Create labels that we will be needing
320013449892Sdrh       */
320113449892Sdrh 
320213449892Sdrh       addrInitializeLoop = sqlite3VdbeMakeLabel(v);
320313449892Sdrh       addrGroupByChange = sqlite3VdbeMakeLabel(v);
320413449892Sdrh       addrProcessRow = sqlite3VdbeMakeLabel(v);
320513449892Sdrh 
320613449892Sdrh       /* If there is a GROUP BY clause we might need a sorting index to
320713449892Sdrh       ** implement it.  Allocate that sorting index now.  If it turns out
3208b9bb7c18Sdrh       ** that we do not need it after all, the OpenEphemeral instruction
320913449892Sdrh       ** will be converted into a Noop.
321013449892Sdrh       */
321113449892Sdrh       sAggInfo.sortingIdx = pParse->nTab++;
321213449892Sdrh       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
321313449892Sdrh       addrSortingIdx =
3214b9bb7c18Sdrh           sqlite3VdbeOp3(v, OP_OpenEphemeral, sAggInfo.sortingIdx,
321513449892Sdrh                          sAggInfo.nSortingColumn,
321613449892Sdrh                          (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
321713449892Sdrh 
321813449892Sdrh       /* Initialize memory locations used by GROUP BY aggregate processing
321913449892Sdrh       */
322013449892Sdrh       iUseFlag = pParse->nMem++;
322113449892Sdrh       iAbortFlag = pParse->nMem++;
322213449892Sdrh       iAMem = pParse->nMem;
322313449892Sdrh       pParse->nMem += pGroupBy->nExpr;
322413449892Sdrh       iBMem = pParse->nMem;
322513449892Sdrh       pParse->nMem += pGroupBy->nExpr;
3226d654be80Sdrh       sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag);
3227de29e3e9Sdrh       VdbeComment((v, "# clear abort flag"));
3228d654be80Sdrh       sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag);
3229de29e3e9Sdrh       VdbeComment((v, "# indicate accumulator empty"));
323013449892Sdrh       sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop);
323113449892Sdrh 
323213449892Sdrh       /* Generate a subroutine that outputs a single row of the result
323313449892Sdrh       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
323413449892Sdrh       ** is less than or equal to zero, the subroutine is a no-op.  If
323513449892Sdrh       ** the processing calls for the query to abort, this subroutine
323613449892Sdrh       ** increments the iAbortFlag memory location before returning in
323713449892Sdrh       ** order to signal the caller to abort.
323813449892Sdrh       */
323913449892Sdrh       addrSetAbort = sqlite3VdbeCurrentAddr(v);
3240de29e3e9Sdrh       sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag);
3241de29e3e9Sdrh       VdbeComment((v, "# set abort flag"));
324213449892Sdrh       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
324313449892Sdrh       addrOutputRow = sqlite3VdbeCurrentAddr(v);
324413449892Sdrh       sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2);
3245de29e3e9Sdrh       VdbeComment((v, "# Groupby result generator entry point"));
324613449892Sdrh       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
324713449892Sdrh       finalizeAggFunctions(pParse, &sAggInfo);
324813449892Sdrh       if( pHaving ){
324913449892Sdrh         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1);
325013449892Sdrh       }
325113449892Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
325213449892Sdrh                            distinct, eDest, iParm,
325313449892Sdrh                            addrOutputRow+1, addrSetAbort, aff);
325413449892Sdrh       if( rc ){
325513449892Sdrh         goto select_end;
325613449892Sdrh       }
325713449892Sdrh       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
3258de29e3e9Sdrh       VdbeComment((v, "# end groupby result generator"));
325913449892Sdrh 
3260e313382eSdrh       /* Generate a subroutine that will reset the group-by accumulator
3261e313382eSdrh       */
3262e313382eSdrh       addrReset = sqlite3VdbeCurrentAddr(v);
3263e313382eSdrh       resetAccumulator(pParse, &sAggInfo);
3264e313382eSdrh       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
3265e313382eSdrh 
326613449892Sdrh       /* Begin a loop that will extract all source rows in GROUP BY order.
326713449892Sdrh       ** This might involve two separate loops with an OP_Sort in between, or
326813449892Sdrh       ** it might be a single loop that uses an index to extract information
326913449892Sdrh       ** in the right order to begin with.
327013449892Sdrh       */
327113449892Sdrh       sqlite3VdbeResolveLabel(v, addrInitializeLoop);
3272e313382eSdrh       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
327313449892Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy);
32745360ad34Sdrh       if( pWInfo==0 ) goto select_end;
327513449892Sdrh       if( pGroupBy==0 ){
327613449892Sdrh         /* The optimizer is able to deliver rows in group by order so
3277b9bb7c18Sdrh         ** we do not have to sort.  The OP_OpenEphemeral table will be
327813449892Sdrh         ** cancelled later because we still need to use the pKeyInfo
327913449892Sdrh         */
328013449892Sdrh         pGroupBy = p->pGroupBy;
328113449892Sdrh         groupBySort = 0;
328213449892Sdrh       }else{
328313449892Sdrh         /* Rows are coming out in undetermined order.  We have to push
328413449892Sdrh         ** each row into a sorting index, terminate the first loop,
328513449892Sdrh         ** then loop over the sorting index in order to get the output
328613449892Sdrh         ** in sorted order
328713449892Sdrh         */
328813449892Sdrh         groupBySort = 1;
328913449892Sdrh         sqlite3ExprCodeExprList(pParse, pGroupBy);
329013449892Sdrh         sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0);
329113449892Sdrh         j = pGroupBy->nExpr+1;
329213449892Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
329313449892Sdrh           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
329413449892Sdrh           if( pCol->iSorterColumn<j ) continue;
3295945498f3Sdrh           sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn, pCol->iTable);
329613449892Sdrh           j++;
329713449892Sdrh         }
329813449892Sdrh         sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0);
329913449892Sdrh         sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0);
330013449892Sdrh         sqlite3WhereEnd(pWInfo);
330197571957Sdrh         sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
3302de29e3e9Sdrh         VdbeComment((v, "# GROUP BY sort"));
330313449892Sdrh         sAggInfo.useSortingIdx = 1;
330413449892Sdrh       }
330513449892Sdrh 
330613449892Sdrh       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
330713449892Sdrh       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
330813449892Sdrh       ** Then compare the current GROUP BY terms against the GROUP BY terms
330913449892Sdrh       ** from the previous row currently stored in a0, a1, a2...
331013449892Sdrh       */
331113449892Sdrh       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
331213449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
331313449892Sdrh         if( groupBySort ){
331413449892Sdrh           sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j);
331513449892Sdrh         }else{
331613449892Sdrh           sAggInfo.directMode = 1;
331713449892Sdrh           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr);
331813449892Sdrh         }
331913449892Sdrh         sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1);
332013449892Sdrh       }
332113449892Sdrh       for(j=pGroupBy->nExpr-1; j>=0; j--){
332213449892Sdrh         if( j<pGroupBy->nExpr-1 ){
332313449892Sdrh           sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0);
332413449892Sdrh         }
332513449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0);
332613449892Sdrh         if( j==0 ){
3327e313382eSdrh           sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow);
332813449892Sdrh         }else{
33294f686238Sdrh           sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange);
333013449892Sdrh         }
333113449892Sdrh         sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ);
333213449892Sdrh       }
333313449892Sdrh 
333413449892Sdrh       /* Generate code that runs whenever the GROUP BY changes.
333513449892Sdrh       ** Change in the GROUP BY are detected by the previous code
333613449892Sdrh       ** block.  If there were no changes, this block is skipped.
333713449892Sdrh       **
333813449892Sdrh       ** This code copies current group by terms in b0,b1,b2,...
333913449892Sdrh       ** over to a0,a1,a2.  It then calls the output subroutine
334013449892Sdrh       ** and resets the aggregate accumulator registers in preparation
334113449892Sdrh       ** for the next GROUP BY batch.
334213449892Sdrh       */
334313449892Sdrh       sqlite3VdbeResolveLabel(v, addrGroupByChange);
334413449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
3345d654be80Sdrh         sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j);
334613449892Sdrh       }
334713449892Sdrh       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
3348de29e3e9Sdrh       VdbeComment((v, "# output one row"));
334913449892Sdrh       sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd);
3350de29e3e9Sdrh       VdbeComment((v, "# check abort flag"));
3351e313382eSdrh       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
3352de29e3e9Sdrh       VdbeComment((v, "# reset accumulator"));
335313449892Sdrh 
335413449892Sdrh       /* Update the aggregate accumulators based on the content of
335513449892Sdrh       ** the current row
335613449892Sdrh       */
335713449892Sdrh       sqlite3VdbeResolveLabel(v, addrProcessRow);
335813449892Sdrh       updateAccumulator(pParse, &sAggInfo);
3359de29e3e9Sdrh       sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag);
3360de29e3e9Sdrh       VdbeComment((v, "# indicate data in accumulator"));
336113449892Sdrh 
336213449892Sdrh       /* End of the loop
336313449892Sdrh       */
336413449892Sdrh       if( groupBySort ){
336513449892Sdrh         sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
336613449892Sdrh       }else{
336713449892Sdrh         sqlite3WhereEnd(pWInfo);
3368f8875400Sdrh         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
336913449892Sdrh       }
337013449892Sdrh 
337113449892Sdrh       /* Output the final row of result
337213449892Sdrh       */
337313449892Sdrh       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
3374de29e3e9Sdrh       VdbeComment((v, "# output final row"));
337513449892Sdrh 
337613449892Sdrh     } /* endif pGroupBy */
337713449892Sdrh     else {
337813449892Sdrh       /* This case runs if the aggregate has no GROUP BY clause.  The
337913449892Sdrh       ** processing is much simpler since there is only a single row
338013449892Sdrh       ** of output.
338113449892Sdrh       */
338213449892Sdrh       resetAccumulator(pParse, &sAggInfo);
338313449892Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
33845360ad34Sdrh       if( pWInfo==0 ) goto select_end;
338513449892Sdrh       updateAccumulator(pParse, &sAggInfo);
338613449892Sdrh       sqlite3WhereEnd(pWInfo);
338713449892Sdrh       finalizeAggFunctions(pParse, &sAggInfo);
338813449892Sdrh       pOrderBy = 0;
33895774b806Sdrh       if( pHaving ){
33905774b806Sdrh         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1);
33915774b806Sdrh       }
339213449892Sdrh       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
339313449892Sdrh                       eDest, iParm, addrEnd, addrEnd, aff);
339413449892Sdrh     }
339513449892Sdrh     sqlite3VdbeResolveLabel(v, addrEnd);
339613449892Sdrh 
339713449892Sdrh   } /* endif aggregate query */
33982282792aSdrh 
3399cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
3400cce7d176Sdrh   ** and send them to the callback one by one.
3401cce7d176Sdrh   */
3402cce7d176Sdrh   if( pOrderBy ){
3403cdd536f0Sdrh     generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
3404cce7d176Sdrh   }
34056a535340Sdrh 
340693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
3407f620b4e2Sdrh   /* If this was a subquery, we have now converted the subquery into a
34081787ccabSdanielk1977   ** temporary table.  So set the SrcList_item.isPopulated flag to prevent
34091787ccabSdanielk1977   ** this subquery from being evaluated again and to force the use of
34101787ccabSdanielk1977   ** the temporary table.
3411f620b4e2Sdrh   */
3412f620b4e2Sdrh   if( pParent ){
3413f620b4e2Sdrh     assert( pParent->pSrc->nSrc>parentTab );
3414f620b4e2Sdrh     assert( pParent->pSrc->a[parentTab].pSelect==p );
34151787ccabSdanielk1977     pParent->pSrc->a[parentTab].isPopulated = 1;
3416f620b4e2Sdrh   }
341793758c8dSdanielk1977 #endif
3418f620b4e2Sdrh 
3419ec7429aeSdrh   /* Jump here to skip this query
3420ec7429aeSdrh   */
3421ec7429aeSdrh   sqlite3VdbeResolveLabel(v, iEnd);
3422ec7429aeSdrh 
34231d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
34241d83f052Sdrh   ** to indicate no errors.
34251d83f052Sdrh   */
34261d83f052Sdrh   rc = 0;
34271d83f052Sdrh 
34281d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
34291d83f052Sdrh   ** successful coding of the SELECT.
34301d83f052Sdrh   */
34311d83f052Sdrh select_end:
3432955de52cSdanielk1977 
3433955de52cSdanielk1977   /* Identify column names if we will be using them in a callback.  This
3434955de52cSdanielk1977   ** step is skipped if the output is going to some other destination.
3435955de52cSdanielk1977   */
3436955de52cSdanielk1977   if( rc==SQLITE_OK && eDest==SRT_Callback ){
3437955de52cSdanielk1977     generateColumnNames(pParse, pTabList, pEList);
3438955de52cSdanielk1977   }
3439955de52cSdanielk1977 
344017435752Sdrh   sqlite3_free(sAggInfo.aCol);
344117435752Sdrh   sqlite3_free(sAggInfo.aFunc);
34421d83f052Sdrh   return rc;
3443cce7d176Sdrh }
3444485f0039Sdrh 
344577a2a5e7Sdrh #if defined(SQLITE_DEBUG)
3446485f0039Sdrh /*
3447485f0039Sdrh *******************************************************************************
3448485f0039Sdrh ** The following code is used for testing and debugging only.  The code
3449485f0039Sdrh ** that follows does not appear in normal builds.
3450485f0039Sdrh **
3451485f0039Sdrh ** These routines are used to print out the content of all or part of a
3452485f0039Sdrh ** parse structures such as Select or Expr.  Such printouts are useful
3453485f0039Sdrh ** for helping to understand what is happening inside the code generator
3454485f0039Sdrh ** during the execution of complex SELECT statements.
3455485f0039Sdrh **
3456485f0039Sdrh ** These routine are not called anywhere from within the normal
3457485f0039Sdrh ** code base.  Then are intended to be called from within the debugger
3458485f0039Sdrh ** or from temporary "printf" statements inserted for debugging.
3459485f0039Sdrh */
3460485f0039Sdrh void sqlite3PrintExpr(Expr *p){
3461485f0039Sdrh   if( p->token.z && p->token.n>0 ){
3462485f0039Sdrh     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
3463485f0039Sdrh   }else{
3464485f0039Sdrh     sqlite3DebugPrintf("(%d", p->op);
3465485f0039Sdrh   }
3466485f0039Sdrh   if( p->pLeft ){
3467485f0039Sdrh     sqlite3DebugPrintf(" ");
3468485f0039Sdrh     sqlite3PrintExpr(p->pLeft);
3469485f0039Sdrh   }
3470485f0039Sdrh   if( p->pRight ){
3471485f0039Sdrh     sqlite3DebugPrintf(" ");
3472485f0039Sdrh     sqlite3PrintExpr(p->pRight);
3473485f0039Sdrh   }
3474485f0039Sdrh   sqlite3DebugPrintf(")");
3475485f0039Sdrh }
3476485f0039Sdrh void sqlite3PrintExprList(ExprList *pList){
3477485f0039Sdrh   int i;
3478485f0039Sdrh   for(i=0; i<pList->nExpr; i++){
3479485f0039Sdrh     sqlite3PrintExpr(pList->a[i].pExpr);
3480485f0039Sdrh     if( i<pList->nExpr-1 ){
3481485f0039Sdrh       sqlite3DebugPrintf(", ");
3482485f0039Sdrh     }
3483485f0039Sdrh   }
3484485f0039Sdrh }
3485485f0039Sdrh void sqlite3PrintSelect(Select *p, int indent){
3486485f0039Sdrh   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
3487485f0039Sdrh   sqlite3PrintExprList(p->pEList);
3488485f0039Sdrh   sqlite3DebugPrintf("\n");
3489485f0039Sdrh   if( p->pSrc ){
3490485f0039Sdrh     char *zPrefix;
3491485f0039Sdrh     int i;
3492485f0039Sdrh     zPrefix = "FROM";
3493485f0039Sdrh     for(i=0; i<p->pSrc->nSrc; i++){
3494485f0039Sdrh       struct SrcList_item *pItem = &p->pSrc->a[i];
3495485f0039Sdrh       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
3496485f0039Sdrh       zPrefix = "";
3497485f0039Sdrh       if( pItem->pSelect ){
3498485f0039Sdrh         sqlite3DebugPrintf("(\n");
3499485f0039Sdrh         sqlite3PrintSelect(pItem->pSelect, indent+10);
3500485f0039Sdrh         sqlite3DebugPrintf("%*s)", indent+8, "");
3501485f0039Sdrh       }else if( pItem->zName ){
3502485f0039Sdrh         sqlite3DebugPrintf("%s", pItem->zName);
3503485f0039Sdrh       }
3504485f0039Sdrh       if( pItem->pTab ){
3505485f0039Sdrh         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
3506485f0039Sdrh       }
3507485f0039Sdrh       if( pItem->zAlias ){
3508485f0039Sdrh         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
3509485f0039Sdrh       }
3510485f0039Sdrh       if( i<p->pSrc->nSrc-1 ){
3511485f0039Sdrh         sqlite3DebugPrintf(",");
3512485f0039Sdrh       }
3513485f0039Sdrh       sqlite3DebugPrintf("\n");
3514485f0039Sdrh     }
3515485f0039Sdrh   }
3516485f0039Sdrh   if( p->pWhere ){
3517485f0039Sdrh     sqlite3DebugPrintf("%*s WHERE ", indent, "");
3518485f0039Sdrh     sqlite3PrintExpr(p->pWhere);
3519485f0039Sdrh     sqlite3DebugPrintf("\n");
3520485f0039Sdrh   }
3521485f0039Sdrh   if( p->pGroupBy ){
3522485f0039Sdrh     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
3523485f0039Sdrh     sqlite3PrintExprList(p->pGroupBy);
3524485f0039Sdrh     sqlite3DebugPrintf("\n");
3525485f0039Sdrh   }
3526485f0039Sdrh   if( p->pHaving ){
3527485f0039Sdrh     sqlite3DebugPrintf("%*s HAVING ", indent, "");
3528485f0039Sdrh     sqlite3PrintExpr(p->pHaving);
3529485f0039Sdrh     sqlite3DebugPrintf("\n");
3530485f0039Sdrh   }
3531485f0039Sdrh   if( p->pOrderBy ){
3532485f0039Sdrh     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
3533485f0039Sdrh     sqlite3PrintExprList(p->pOrderBy);
3534485f0039Sdrh     sqlite3DebugPrintf("\n");
3535485f0039Sdrh   }
3536485f0039Sdrh }
3537485f0039Sdrh /* End of the structure debug printing code
3538485f0039Sdrh *****************************************************************************/
3539485f0039Sdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
3540