xref: /sqlite-3.40.0/src/select.c (revision 5bb3eb9b)
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*5bb3eb9bSdrh ** $Id: select.c,v 1.340 2007/05/04 13:15:56 drh Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19315555caSdrh 
20cce7d176Sdrh /*
21eda639e1Sdrh ** Delete all the content of a Select structure but do not deallocate
22eda639e1Sdrh ** the select structure itself.
23eda639e1Sdrh */
24f0113000Sdanielk1977 static void clearSelect(Select *p){
25eda639e1Sdrh   sqlite3ExprListDelete(p->pEList);
26eda639e1Sdrh   sqlite3SrcListDelete(p->pSrc);
27eda639e1Sdrh   sqlite3ExprDelete(p->pWhere);
28eda639e1Sdrh   sqlite3ExprListDelete(p->pGroupBy);
29eda639e1Sdrh   sqlite3ExprDelete(p->pHaving);
30eda639e1Sdrh   sqlite3ExprListDelete(p->pOrderBy);
31eda639e1Sdrh   sqlite3SelectDelete(p->pPrior);
32eda639e1Sdrh   sqlite3ExprDelete(p->pLimit);
33eda639e1Sdrh   sqlite3ExprDelete(p->pOffset);
34eda639e1Sdrh }
35eda639e1Sdrh 
36eda639e1Sdrh 
37eda639e1Sdrh /*
389bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that
399bb61fe7Sdrh ** structure.
40cce7d176Sdrh */
414adee20fSdanielk1977 Select *sqlite3SelectNew(
42daffd0e5Sdrh   ExprList *pEList,     /* which columns to include in the result */
43ad3cab52Sdrh   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
44daffd0e5Sdrh   Expr *pWhere,         /* the WHERE clause */
45daffd0e5Sdrh   ExprList *pGroupBy,   /* the GROUP BY clause */
46daffd0e5Sdrh   Expr *pHaving,        /* the HAVING clause */
47daffd0e5Sdrh   ExprList *pOrderBy,   /* the ORDER BY clause */
489bbca4c1Sdrh   int isDistinct,       /* true if the DISTINCT keyword is present */
49a2dc3b1aSdanielk1977   Expr *pLimit,         /* LIMIT value.  NULL means not used */
50a2dc3b1aSdanielk1977   Expr *pOffset         /* OFFSET value.  NULL means no offset */
519bb61fe7Sdrh ){
529bb61fe7Sdrh   Select *pNew;
53eda639e1Sdrh   Select standin;
549bb61fe7Sdrh   pNew = sqliteMalloc( sizeof(*pNew) );
55a2dc3b1aSdanielk1977   assert( !pOffset || pLimit );   /* Can't have OFFSET without LIMIT. */
56daffd0e5Sdrh   if( pNew==0 ){
57eda639e1Sdrh     pNew = &standin;
58eda639e1Sdrh     memset(pNew, 0, sizeof(*pNew));
59eda639e1Sdrh   }
60b733d037Sdrh   if( pEList==0 ){
614adee20fSdanielk1977     pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0);
62b733d037Sdrh   }
639bb61fe7Sdrh   pNew->pEList = pEList;
649bb61fe7Sdrh   pNew->pSrc = pSrc;
659bb61fe7Sdrh   pNew->pWhere = pWhere;
669bb61fe7Sdrh   pNew->pGroupBy = pGroupBy;
679bb61fe7Sdrh   pNew->pHaving = pHaving;
689bb61fe7Sdrh   pNew->pOrderBy = pOrderBy;
699bb61fe7Sdrh   pNew->isDistinct = isDistinct;
7082c3d636Sdrh   pNew->op = TK_SELECT;
718103b7d2Sdrh   assert( pOffset==0 || pLimit!=0 );
72a2dc3b1aSdanielk1977   pNew->pLimit = pLimit;
73a2dc3b1aSdanielk1977   pNew->pOffset = pOffset;
747b58daeaSdrh   pNew->iLimit = -1;
757b58daeaSdrh   pNew->iOffset = -1;
76b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
77b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
78b9bb7c18Sdrh   pNew->addrOpenEphm[2] = -1;
79eda639e1Sdrh   if( pNew==&standin) {
80eda639e1Sdrh     clearSelect(pNew);
81eda639e1Sdrh     pNew = 0;
82daffd0e5Sdrh   }
839bb61fe7Sdrh   return pNew;
849bb61fe7Sdrh }
859bb61fe7Sdrh 
869bb61fe7Sdrh /*
87eda639e1Sdrh ** Delete the given Select structure and all of its substructures.
88eda639e1Sdrh */
89eda639e1Sdrh void sqlite3SelectDelete(Select *p){
90eda639e1Sdrh   if( p ){
91eda639e1Sdrh     clearSelect(p);
92eda639e1Sdrh     sqliteFree(p);
93eda639e1Sdrh   }
94eda639e1Sdrh }
95eda639e1Sdrh 
96eda639e1Sdrh /*
9701f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
9801f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
9901f3f253Sdrh ** in terms of the following bit values:
10001f3f253Sdrh **
10101f3f253Sdrh **     JT_INNER
1023dec223cSdrh **     JT_CROSS
10301f3f253Sdrh **     JT_OUTER
10401f3f253Sdrh **     JT_NATURAL
10501f3f253Sdrh **     JT_LEFT
10601f3f253Sdrh **     JT_RIGHT
10701f3f253Sdrh **
10801f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
10901f3f253Sdrh **
11001f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
11101f3f253Sdrh ** a join type, but put an error in the pParse structure.
11201f3f253Sdrh */
1134adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
11401f3f253Sdrh   int jointype = 0;
11501f3f253Sdrh   Token *apAll[3];
11601f3f253Sdrh   Token *p;
1175719628aSdrh   static const struct {
118c182d163Sdrh     const char zKeyword[8];
119290c1948Sdrh     u8 nChar;
120290c1948Sdrh     u8 code;
12101f3f253Sdrh   } keywords[] = {
12201f3f253Sdrh     { "natural", 7, JT_NATURAL },
123195e6967Sdrh     { "left",    4, JT_LEFT|JT_OUTER },
124195e6967Sdrh     { "right",   5, JT_RIGHT|JT_OUTER },
125195e6967Sdrh     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
12601f3f253Sdrh     { "outer",   5, JT_OUTER },
12701f3f253Sdrh     { "inner",   5, JT_INNER },
1283dec223cSdrh     { "cross",   5, JT_INNER|JT_CROSS },
12901f3f253Sdrh   };
13001f3f253Sdrh   int i, j;
13101f3f253Sdrh   apAll[0] = pA;
13201f3f253Sdrh   apAll[1] = pB;
13301f3f253Sdrh   apAll[2] = pC;
134195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
13501f3f253Sdrh     p = apAll[i];
13601f3f253Sdrh     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
13701f3f253Sdrh       if( p->n==keywords[j].nChar
1382646da7eSdrh           && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
13901f3f253Sdrh         jointype |= keywords[j].code;
14001f3f253Sdrh         break;
14101f3f253Sdrh       }
14201f3f253Sdrh     }
14301f3f253Sdrh     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
14401f3f253Sdrh       jointype |= JT_ERROR;
14501f3f253Sdrh       break;
14601f3f253Sdrh     }
14701f3f253Sdrh   }
148ad2d8307Sdrh   if(
149ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
150195e6967Sdrh      (jointype & JT_ERROR)!=0
151ad2d8307Sdrh   ){
152ae29ffbeSdrh     const char *zSp1 = " ";
153ae29ffbeSdrh     const char *zSp2 = " ";
154ae29ffbeSdrh     if( pB==0 ){ zSp1++; }
155ae29ffbeSdrh     if( pC==0 ){ zSp2++; }
156ae29ffbeSdrh     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
157ae29ffbeSdrh        "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
15801f3f253Sdrh     jointype = JT_INNER;
159195e6967Sdrh   }else if( jointype & JT_RIGHT ){
1604adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
161da93d238Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported");
162195e6967Sdrh     jointype = JT_INNER;
16301f3f253Sdrh   }
16401f3f253Sdrh   return jointype;
16501f3f253Sdrh }
16601f3f253Sdrh 
16701f3f253Sdrh /*
168ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
169ad2d8307Sdrh ** is not contained in the table.
170ad2d8307Sdrh */
171ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
172ad2d8307Sdrh   int i;
173ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
1744adee20fSdanielk1977     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
175ad2d8307Sdrh   }
176ad2d8307Sdrh   return -1;
177ad2d8307Sdrh }
178ad2d8307Sdrh 
179ad2d8307Sdrh /*
18091bb0eedSdrh ** Set the value of a token to a '\000'-terminated string.
18191bb0eedSdrh */
18291bb0eedSdrh static void setToken(Token *p, const char *z){
1832646da7eSdrh   p->z = (u8*)z;
184261919ccSdanielk1977   p->n = z ? strlen(z) : 0;
18591bb0eedSdrh   p->dyn = 0;
18691bb0eedSdrh }
18791bb0eedSdrh 
188c182d163Sdrh /*
189c182d163Sdrh ** Create an expression node for an identifier with the name of zName
190c182d163Sdrh */
1919c41938fSdrh Expr *sqlite3CreateIdExpr(const char *zName){
192c182d163Sdrh   Token dummy;
193c182d163Sdrh   setToken(&dummy, zName);
194c182d163Sdrh   return sqlite3Expr(TK_ID, 0, 0, &dummy);
195c182d163Sdrh }
196c182d163Sdrh 
19791bb0eedSdrh 
19891bb0eedSdrh /*
199ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the
200ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2.
201ad2d8307Sdrh */
202ad2d8307Sdrh static void addWhereTerm(
203ad2d8307Sdrh   const char *zCol,        /* Name of the column */
204ad2d8307Sdrh   const Table *pTab1,      /* First table */
205030530deSdrh   const char *zAlias1,     /* Alias for first table.  May be NULL */
206ad2d8307Sdrh   const Table *pTab2,      /* Second table */
207030530deSdrh   const char *zAlias2,     /* Alias for second table.  May be NULL */
20822d6a53aSdrh   int iRightJoinTable,     /* VDBE cursor for the right table */
209ad2d8307Sdrh   Expr **ppExpr            /* Add the equality term to this expression */
210ad2d8307Sdrh ){
211ad2d8307Sdrh   Expr *pE1a, *pE1b, *pE1c;
212ad2d8307Sdrh   Expr *pE2a, *pE2b, *pE2c;
213ad2d8307Sdrh   Expr *pE;
214ad2d8307Sdrh 
2159c41938fSdrh   pE1a = sqlite3CreateIdExpr(zCol);
2169c41938fSdrh   pE2a = sqlite3CreateIdExpr(zCol);
217030530deSdrh   if( zAlias1==0 ){
218030530deSdrh     zAlias1 = pTab1->zName;
219030530deSdrh   }
2209c41938fSdrh   pE1b = sqlite3CreateIdExpr(zAlias1);
221030530deSdrh   if( zAlias2==0 ){
222030530deSdrh     zAlias2 = pTab2->zName;
223030530deSdrh   }
2249c41938fSdrh   pE2b = sqlite3CreateIdExpr(zAlias2);
225206f3d96Sdrh   pE1c = sqlite3ExprOrFree(TK_DOT, pE1b, pE1a, 0);
226206f3d96Sdrh   pE2c = sqlite3ExprOrFree(TK_DOT, pE2b, pE2a, 0);
227206f3d96Sdrh   pE = sqlite3ExprOrFree(TK_EQ, pE1c, pE2c, 0);
228206f3d96Sdrh   if( pE ){
2291f16230bSdrh     ExprSetProperty(pE, EP_FromJoin);
23022d6a53aSdrh     pE->iRightJoinTable = iRightJoinTable;
231206f3d96Sdrh   }
232206f3d96Sdrh   pE = sqlite3ExprAnd(*ppExpr, pE);
233206f3d96Sdrh   if( pE ){
234206f3d96Sdrh     *ppExpr = pE;
235206f3d96Sdrh   }
236ad2d8307Sdrh }
237ad2d8307Sdrh 
238ad2d8307Sdrh /*
2391f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
24022d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the
24122d6a53aSdrh ** expression.
2421cc093c2Sdrh **
243e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
2441cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
2451f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
2461f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
2471f16230bSdrh ** WHERE clause during join processing but we need to remember that they
2481f16230bSdrh ** originated in the ON or USING clause.
24922d6a53aSdrh **
25022d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the
25122d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not
25222d6a53aSdrh ** explicitly mentioned in the expression.  That information is needed
25322d6a53aSdrh ** for cases like this:
25422d6a53aSdrh **
25522d6a53aSdrh **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
25622d6a53aSdrh **
25722d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5
25822d6a53aSdrh ** term until after the t2 loop of the join.  In that way, a
25922d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
26022d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately
26122d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in
26222d6a53aSdrh ** the output, which is incorrect.
2631cc093c2Sdrh */
26422d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){
2651cc093c2Sdrh   while( p ){
2661f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
26722d6a53aSdrh     p->iRightJoinTable = iTable;
26822d6a53aSdrh     setJoinExpr(p->pLeft, iTable);
2691cc093c2Sdrh     p = p->pRight;
2701cc093c2Sdrh   }
2711cc093c2Sdrh }
2721cc093c2Sdrh 
2731cc093c2Sdrh /*
274ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
275ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
276ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
277ad2d8307Sdrh **
27891bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure.
27991bb0eedSdrh ** The left most table is the first entry in Select.pSrc.  The right-most
28091bb0eedSdrh ** table is the last entry.  The join operator is held in the entry to
28191bb0eedSdrh ** the left.  Thus entry 0 contains the join operator for the join between
28291bb0eedSdrh ** entries 0 and 1.  Any ON or USING clauses associated with the join are
28391bb0eedSdrh ** also attached to the left entry.
28491bb0eedSdrh **
285ad2d8307Sdrh ** This routine returns the number of errors encountered.
286ad2d8307Sdrh */
287ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
28891bb0eedSdrh   SrcList *pSrc;                  /* All tables in the FROM clause */
28991bb0eedSdrh   int i, j;                       /* Loop counters */
29091bb0eedSdrh   struct SrcList_item *pLeft;     /* Left table being joined */
29191bb0eedSdrh   struct SrcList_item *pRight;    /* Right table being joined */
292ad2d8307Sdrh 
29391bb0eedSdrh   pSrc = p->pSrc;
29491bb0eedSdrh   pLeft = &pSrc->a[0];
29591bb0eedSdrh   pRight = &pLeft[1];
29691bb0eedSdrh   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
29791bb0eedSdrh     Table *pLeftTab = pLeft->pTab;
29891bb0eedSdrh     Table *pRightTab = pRight->pTab;
29991bb0eedSdrh 
30091bb0eedSdrh     if( pLeftTab==0 || pRightTab==0 ) continue;
301ad2d8307Sdrh 
302ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
303ad2d8307Sdrh     ** every column that the two tables have in common.
304ad2d8307Sdrh     */
30561dfc31dSdrh     if( pRight->jointype & JT_NATURAL ){
30661dfc31dSdrh       if( pRight->pOn || pRight->pUsing ){
3074adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
308ad2d8307Sdrh            "an ON or USING clause", 0);
309ad2d8307Sdrh         return 1;
310ad2d8307Sdrh       }
31191bb0eedSdrh       for(j=0; j<pLeftTab->nCol; j++){
31291bb0eedSdrh         char *zName = pLeftTab->aCol[j].zName;
31391bb0eedSdrh         if( columnIndex(pRightTab, zName)>=0 ){
314030530deSdrh           addWhereTerm(zName, pLeftTab, pLeft->zAlias,
31522d6a53aSdrh                               pRightTab, pRight->zAlias,
31622d6a53aSdrh                               pRight->iCursor, &p->pWhere);
31722d6a53aSdrh 
318ad2d8307Sdrh         }
319ad2d8307Sdrh       }
320ad2d8307Sdrh     }
321ad2d8307Sdrh 
322ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
323ad2d8307Sdrh     */
32461dfc31dSdrh     if( pRight->pOn && pRight->pUsing ){
3254adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
326da93d238Sdrh         "clauses in the same join");
327ad2d8307Sdrh       return 1;
328ad2d8307Sdrh     }
329ad2d8307Sdrh 
330ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
33191bb0eedSdrh     ** an AND operator.
332ad2d8307Sdrh     */
33361dfc31dSdrh     if( pRight->pOn ){
33461dfc31dSdrh       setJoinExpr(pRight->pOn, pRight->iCursor);
33561dfc31dSdrh       p->pWhere = sqlite3ExprAnd(p->pWhere, pRight->pOn);
33661dfc31dSdrh       pRight->pOn = 0;
337ad2d8307Sdrh     }
338ad2d8307Sdrh 
339ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
340ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
341ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
342ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
343ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
344ad2d8307Sdrh     ** not contained in both tables to be joined.
345ad2d8307Sdrh     */
34661dfc31dSdrh     if( pRight->pUsing ){
34761dfc31dSdrh       IdList *pList = pRight->pUsing;
348ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
34991bb0eedSdrh         char *zName = pList->a[j].zName;
35091bb0eedSdrh         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
3514adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
35291bb0eedSdrh             "not present in both tables", zName);
353ad2d8307Sdrh           return 1;
354ad2d8307Sdrh         }
355030530deSdrh         addWhereTerm(zName, pLeftTab, pLeft->zAlias,
35622d6a53aSdrh                             pRightTab, pRight->zAlias,
35722d6a53aSdrh                             pRight->iCursor, &p->pWhere);
358ad2d8307Sdrh       }
359ad2d8307Sdrh     }
360ad2d8307Sdrh   }
361ad2d8307Sdrh   return 0;
362ad2d8307Sdrh }
363ad2d8307Sdrh 
364ad2d8307Sdrh /*
365c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
366c926afbcSdrh ** stack into the sorter.
367c926afbcSdrh */
368d59ba6ceSdrh static void pushOntoSorter(
369d59ba6ceSdrh   Parse *pParse,         /* Parser context */
370d59ba6ceSdrh   ExprList *pOrderBy,    /* The ORDER BY clause */
371d59ba6ceSdrh   Select *pSelect        /* The whole SELECT statement */
372d59ba6ceSdrh ){
373d59ba6ceSdrh   Vdbe *v = pParse->pVdbe;
374c182d163Sdrh   sqlite3ExprCodeExprList(pParse, pOrderBy);
3759d2985c7Sdrh   sqlite3VdbeAddOp(v, OP_Sequence, pOrderBy->iECursor, 0);
3764db38a70Sdrh   sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr + 1, 0);
3774db38a70Sdrh   sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0);
3789d2985c7Sdrh   sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iECursor, 0);
379d59ba6ceSdrh   if( pSelect->iLimit>=0 ){
38015007a99Sdrh     int addr1, addr2;
38115007a99Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_IfMemZero, pSelect->iLimit+1, 0);
38215007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemIncr, -1, pSelect->iLimit+1);
38315007a99Sdrh     addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
384d59ba6ceSdrh     sqlite3VdbeJumpHere(v, addr1);
385d59ba6ceSdrh     sqlite3VdbeAddOp(v, OP_Last, pOrderBy->iECursor, 0);
386d59ba6ceSdrh     sqlite3VdbeAddOp(v, OP_Delete, pOrderBy->iECursor, 0);
38715007a99Sdrh     sqlite3VdbeJumpHere(v, addr2);
388d59ba6ceSdrh     pSelect->iLimit = -1;
389d59ba6ceSdrh   }
390c926afbcSdrh }
391c926afbcSdrh 
392c926afbcSdrh /*
393ec7429aeSdrh ** Add code to implement the OFFSET
394ea48eb2eSdrh */
395ec7429aeSdrh static void codeOffset(
396bab39e13Sdrh   Vdbe *v,          /* Generate code into this VM */
397ea48eb2eSdrh   Select *p,        /* The SELECT statement being coded */
398ea48eb2eSdrh   int iContinue,    /* Jump here to skip the current record */
399ea48eb2eSdrh   int nPop          /* Number of times to pop stack when jumping */
400ea48eb2eSdrh ){
40113449892Sdrh   if( p->iOffset>=0 && iContinue!=0 ){
40215007a99Sdrh     int addr;
40315007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iOffset);
4043a129247Sdrh     addr = sqlite3VdbeAddOp(v, OP_IfMemNeg, p->iOffset, 0);
405ea48eb2eSdrh     if( nPop>0 ){
406ea48eb2eSdrh       sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
407ea48eb2eSdrh     }
408ea48eb2eSdrh     sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
409ad6d9460Sdrh     VdbeComment((v, "# skip OFFSET records"));
41015007a99Sdrh     sqlite3VdbeJumpHere(v, addr);
411ea48eb2eSdrh   }
412ea48eb2eSdrh }
413ea48eb2eSdrh 
414ea48eb2eSdrh /*
415c99130fdSdrh ** Add code that will check to make sure the top N elements of the
416c99130fdSdrh ** stack are distinct.  iTab is a sorting index that holds previously
417c99130fdSdrh ** seen combinations of the N values.  A new entry is made in iTab
418c99130fdSdrh ** if the current N values are new.
419c99130fdSdrh **
420f8875400Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the
421c99130fdSdrh ** stack if the top N elements are not distinct.
422c99130fdSdrh */
423c99130fdSdrh static void codeDistinct(
424c99130fdSdrh   Vdbe *v,           /* Generate code into this VM */
425c99130fdSdrh   int iTab,          /* A sorting index used to test for distinctness */
426c99130fdSdrh   int addrRepeat,    /* Jump to here if not distinct */
427f8875400Sdrh   int N              /* The top N elements of the stack must be distinct */
428c99130fdSdrh ){
429c99130fdSdrh   sqlite3VdbeAddOp(v, OP_MakeRecord, -N, 0);
430c99130fdSdrh   sqlite3VdbeAddOp(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3);
431f8875400Sdrh   sqlite3VdbeAddOp(v, OP_Pop, N+1, 0);
432c99130fdSdrh   sqlite3VdbeAddOp(v, OP_Goto, 0, addrRepeat);
433c99130fdSdrh   VdbeComment((v, "# skip indistinct records"));
434c99130fdSdrh   sqlite3VdbeAddOp(v, OP_IdxInsert, iTab, 0);
435c99130fdSdrh }
436c99130fdSdrh 
437c99130fdSdrh 
438c99130fdSdrh /*
4392282792aSdrh ** This routine generates the code for the inside of the inner loop
4402282792aSdrh ** of a SELECT.
44182c3d636Sdrh **
44238640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
44338640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
44438640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
44538640e15Sdrh ** datatypes for each column.
4462282792aSdrh */
4472282792aSdrh static int selectInnerLoop(
4482282792aSdrh   Parse *pParse,          /* The parser context */
449df199a25Sdrh   Select *p,              /* The complete select statement being coded */
4502282792aSdrh   ExprList *pEList,       /* List of values being extracted */
45182c3d636Sdrh   int srcTab,             /* Pull data from this table */
452967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
4532282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
4542282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
4552282792aSdrh   int eDest,              /* How to dispose of the results */
4562282792aSdrh   int iParm,              /* An argument to the disposal method */
4572282792aSdrh   int iContinue,          /* Jump here to continue with next row */
45884ac9d02Sdanielk1977   int iBreak,             /* Jump here to break out of the inner loop */
45984ac9d02Sdanielk1977   char *aff               /* affinity string if eDest is SRT_Union */
4602282792aSdrh ){
4612282792aSdrh   Vdbe *v = pParse->pVdbe;
4622282792aSdrh   int i;
463ea48eb2eSdrh   int hasDistinct;        /* True if the DISTINCT keyword is present */
46438640e15Sdrh 
465daffd0e5Sdrh   if( v==0 ) return 0;
46638640e15Sdrh   assert( pEList!=0 );
4672282792aSdrh 
468df199a25Sdrh   /* If there was a LIMIT clause on the SELECT statement, then do the check
469df199a25Sdrh   ** to see if this row should be output.
470df199a25Sdrh   */
471eda639e1Sdrh   hasDistinct = distinct>=0 && pEList->nExpr>0;
472ea48eb2eSdrh   if( pOrderBy==0 && !hasDistinct ){
473ec7429aeSdrh     codeOffset(v, p, iContinue, 0);
474df199a25Sdrh   }
475df199a25Sdrh 
476967e8b73Sdrh   /* Pull the requested columns.
4772282792aSdrh   */
47838640e15Sdrh   if( nColumn>0 ){
479967e8b73Sdrh     for(i=0; i<nColumn; i++){
4804adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
48182c3d636Sdrh     }
48238640e15Sdrh   }else{
48338640e15Sdrh     nColumn = pEList->nExpr;
484c182d163Sdrh     sqlite3ExprCodeExprList(pParse, pEList);
48582c3d636Sdrh   }
4862282792aSdrh 
487daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
488daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
489daffd0e5Sdrh   ** part of the result.
4902282792aSdrh   */
491ea48eb2eSdrh   if( hasDistinct ){
492f8875400Sdrh     assert( pEList!=0 );
493f8875400Sdrh     assert( pEList->nExpr==nColumn );
494f8875400Sdrh     codeDistinct(v, distinct, iContinue, nColumn);
495ea48eb2eSdrh     if( pOrderBy==0 ){
496ec7429aeSdrh       codeOffset(v, p, iContinue, nColumn);
497ea48eb2eSdrh     }
4982282792aSdrh   }
49982c3d636Sdrh 
500c926afbcSdrh   switch( eDest ){
50182c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
50282c3d636Sdrh     ** table iParm.
5032282792aSdrh     */
50413449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
505c926afbcSdrh     case SRT_Union: {
506f8875400Sdrh       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
50713449892Sdrh       if( aff ){
50884ac9d02Sdanielk1977         sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
50913449892Sdrh       }
510f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0);
511c926afbcSdrh       break;
512c926afbcSdrh     }
51382c3d636Sdrh 
51482c3d636Sdrh     /* Construct a record from the query result, but instead of
51582c3d636Sdrh     ** saving that record, use it as a key to delete elements from
51682c3d636Sdrh     ** the temporary table iParm.
51782c3d636Sdrh     */
518c926afbcSdrh     case SRT_Except: {
5190bd1f4eaSdrh       int addr;
520f8875400Sdrh       addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
52184ac9d02Sdanielk1977       sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
5224adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
5234adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
524c926afbcSdrh       break;
525c926afbcSdrh     }
5265338a5f7Sdanielk1977 #endif
5275338a5f7Sdanielk1977 
5285338a5f7Sdanielk1977     /* Store the result as data using a unique key.
5295338a5f7Sdanielk1977     */
5305338a5f7Sdanielk1977     case SRT_Table:
531b9bb7c18Sdrh     case SRT_EphemTab: {
5325338a5f7Sdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
5335338a5f7Sdanielk1977       if( pOrderBy ){
534d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
5355338a5f7Sdanielk1977       }else{
536f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
5375338a5f7Sdanielk1977         sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
538e4d90813Sdrh         sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
5395338a5f7Sdanielk1977       }
5405338a5f7Sdanielk1977       break;
5415338a5f7Sdanielk1977     }
5422282792aSdrh 
54393758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
5442282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
5452282792aSdrh     ** then there should be a single item on the stack.  Write this
5462282792aSdrh     ** item into the set table with bogus data.
5472282792aSdrh     */
548c926afbcSdrh     case SRT_Set: {
5494adee20fSdanielk1977       int addr1 = sqlite3VdbeCurrentAddr(v);
55052b36cabSdrh       int addr2;
551e014a838Sdanielk1977 
552967e8b73Sdrh       assert( nColumn==1 );
5534adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
5544adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
5554adee20fSdanielk1977       addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
5566c1426fdSdrh       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr,(iParm>>16)&0xff);
557c926afbcSdrh       if( pOrderBy ){
558de941c60Sdrh         /* At first glance you would think we could optimize out the
559de941c60Sdrh         ** ORDER BY in this case since the order of entries in the set
560de941c60Sdrh         ** does not matter.  But there might be a LIMIT clause, in which
561de941c60Sdrh         ** case the order does matter */
562d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
563c926afbcSdrh       }else{
5646c1426fdSdrh         sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
565f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
566c926afbcSdrh       }
567d654be80Sdrh       sqlite3VdbeJumpHere(v, addr2);
568c926afbcSdrh       break;
569c926afbcSdrh     }
57082c3d636Sdrh 
571504b6989Sdrh     /* If any row exist in the result set, record that fact and abort.
572ec7429aeSdrh     */
573ec7429aeSdrh     case SRT_Exists: {
574ec7429aeSdrh       sqlite3VdbeAddOp(v, OP_MemInt, 1, iParm);
575ec7429aeSdrh       sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
576ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
577ec7429aeSdrh       break;
578ec7429aeSdrh     }
579ec7429aeSdrh 
5802282792aSdrh     /* If this is a scalar select that is part of an expression, then
5812282792aSdrh     ** store the results in the appropriate memory cell and break out
5822282792aSdrh     ** of the scan loop.
5832282792aSdrh     */
584c926afbcSdrh     case SRT_Mem: {
585967e8b73Sdrh       assert( nColumn==1 );
586c926afbcSdrh       if( pOrderBy ){
587d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
588c926afbcSdrh       }else{
5894adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
590ec7429aeSdrh         /* The LIMIT clause will jump out of the loop for us */
591c926afbcSdrh       }
592c926afbcSdrh       break;
593c926afbcSdrh     }
59493758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
5952282792aSdrh 
596c182d163Sdrh     /* Send the data to the callback function or to a subroutine.  In the
597c182d163Sdrh     ** case of a subroutine, the subroutine itself is responsible for
598c182d163Sdrh     ** popping the data from the stack.
599f46f905aSdrh     */
600c182d163Sdrh     case SRT_Subroutine:
6019d2985c7Sdrh     case SRT_Callback: {
602f46f905aSdrh       if( pOrderBy ){
603ce665cf6Sdrh         sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
604d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
605c182d163Sdrh       }else if( eDest==SRT_Subroutine ){
6064adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
607c182d163Sdrh       }else{
608c182d163Sdrh         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
609ac82fcf5Sdrh       }
610142e30dfSdrh       break;
611142e30dfSdrh     }
612142e30dfSdrh 
6136a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER)
614d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
615d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
616d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
617d7489c39Sdrh     ** about the actual results of the select.
618d7489c39Sdrh     */
619c926afbcSdrh     default: {
620f46f905aSdrh       assert( eDest==SRT_Discard );
6214adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
622c926afbcSdrh       break;
623c926afbcSdrh     }
62493758c8dSdanielk1977 #endif
625c926afbcSdrh   }
626ec7429aeSdrh 
627ec7429aeSdrh   /* Jump to the end of the loop if the LIMIT is reached.
628ec7429aeSdrh   */
629ec7429aeSdrh   if( p->iLimit>=0 && pOrderBy==0 ){
63015007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
631ec7429aeSdrh     sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, iBreak);
632ec7429aeSdrh   }
63382c3d636Sdrh   return 0;
63482c3d636Sdrh }
63582c3d636Sdrh 
63682c3d636Sdrh /*
637dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records
638dece1a84Sdrh ** the collating sequence for each expression in that expression list.
639dece1a84Sdrh **
6400342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
6410342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to
6420342b1f5Sdrh ** implement that clause.  If the ExprList is the result set of a SELECT
6430342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual
6440342b1f5Sdrh ** index to implement a DISTINCT test.
6450342b1f5Sdrh **
646dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
647dece1a84Sdrh ** function is responsible for seeing that this structure is eventually
648dece1a84Sdrh ** freed.  Add the KeyInfo structure to the P3 field of an opcode using
649dece1a84Sdrh ** P3_KEYINFO_HANDOFF is the usual way of dealing with this.
650dece1a84Sdrh */
651dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
652dece1a84Sdrh   sqlite3 *db = pParse->db;
653dece1a84Sdrh   int nExpr;
654dece1a84Sdrh   KeyInfo *pInfo;
655dece1a84Sdrh   struct ExprList_item *pItem;
656dece1a84Sdrh   int i;
657dece1a84Sdrh 
658dece1a84Sdrh   nExpr = pList->nExpr;
659dece1a84Sdrh   pInfo = sqliteMalloc( sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
660dece1a84Sdrh   if( pInfo ){
6612646da7eSdrh     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
662dece1a84Sdrh     pInfo->nField = nExpr;
66314db2665Sdanielk1977     pInfo->enc = ENC(db);
664dece1a84Sdrh     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
665dece1a84Sdrh       CollSeq *pColl;
666dece1a84Sdrh       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
667dece1a84Sdrh       if( !pColl ){
668dece1a84Sdrh         pColl = db->pDfltColl;
669dece1a84Sdrh       }
670dece1a84Sdrh       pInfo->aColl[i] = pColl;
671dece1a84Sdrh       pInfo->aSortOrder[i] = pItem->sortOrder;
672dece1a84Sdrh     }
673dece1a84Sdrh   }
674dece1a84Sdrh   return pInfo;
675dece1a84Sdrh }
676dece1a84Sdrh 
677dece1a84Sdrh 
678dece1a84Sdrh /*
679d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
680d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
681d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
682d8bc7086Sdrh ** routine generates the code needed to do that.
683d8bc7086Sdrh */
684c926afbcSdrh static void generateSortTail(
685cdd536f0Sdrh   Parse *pParse,   /* Parsing context */
686c926afbcSdrh   Select *p,       /* The SELECT statement */
687c926afbcSdrh   Vdbe *v,         /* Generate code into this VDBE */
688c926afbcSdrh   int nColumn,     /* Number of columns of data */
689c926afbcSdrh   int eDest,       /* Write the sorted results here */
690c926afbcSdrh   int iParm        /* Optional parameter associated with eDest */
691c926afbcSdrh ){
6920342b1f5Sdrh   int brk = sqlite3VdbeMakeLabel(v);
6930342b1f5Sdrh   int cont = sqlite3VdbeMakeLabel(v);
694d8bc7086Sdrh   int addr;
6950342b1f5Sdrh   int iTab;
69661fc595fSdrh   int pseudoTab = 0;
6970342b1f5Sdrh   ExprList *pOrderBy = p->pOrderBy;
698ffbc3088Sdrh 
6999d2985c7Sdrh   iTab = pOrderBy->iECursor;
700cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
701cdd536f0Sdrh     pseudoTab = pParse->nTab++;
702cdd536f0Sdrh     sqlite3VdbeAddOp(v, OP_OpenPseudo, pseudoTab, 0);
703cdd536f0Sdrh     sqlite3VdbeAddOp(v, OP_SetNumColumns, pseudoTab, nColumn);
704cdd536f0Sdrh   }
7050342b1f5Sdrh   addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk);
706ec7429aeSdrh   codeOffset(v, p, cont, 0);
707cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
708cdd536f0Sdrh     sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
709cdd536f0Sdrh   }
7104db38a70Sdrh   sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1);
711c926afbcSdrh   switch( eDest ){
712c926afbcSdrh     case SRT_Table:
713b9bb7c18Sdrh     case SRT_EphemTab: {
714f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
7154adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
716e4d90813Sdrh       sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
717c926afbcSdrh       break;
718c926afbcSdrh     }
71993758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
720c926afbcSdrh     case SRT_Set: {
721c926afbcSdrh       assert( nColumn==1 );
7224adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
7234adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
7244adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
7256c1426fdSdrh       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
726f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
727c926afbcSdrh       break;
728c926afbcSdrh     }
729c926afbcSdrh     case SRT_Mem: {
730c926afbcSdrh       assert( nColumn==1 );
7314adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
732ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
733c926afbcSdrh       break;
734c926afbcSdrh     }
73593758c8dSdanielk1977 #endif
736ce665cf6Sdrh     case SRT_Callback:
737ac82fcf5Sdrh     case SRT_Subroutine: {
738ac82fcf5Sdrh       int i;
739cdd536f0Sdrh       sqlite3VdbeAddOp(v, OP_Insert, pseudoTab, 0);
740ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
741cdd536f0Sdrh         sqlite3VdbeAddOp(v, OP_Column, pseudoTab, i);
742ac82fcf5Sdrh       }
743ce665cf6Sdrh       if( eDest==SRT_Callback ){
744ce665cf6Sdrh         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
745ce665cf6Sdrh       }else{
7464adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
747ce665cf6Sdrh       }
748ac82fcf5Sdrh       break;
749ac82fcf5Sdrh     }
750c926afbcSdrh     default: {
751f46f905aSdrh       /* Do nothing */
752c926afbcSdrh       break;
753c926afbcSdrh     }
754c926afbcSdrh   }
755ec7429aeSdrh 
756ec7429aeSdrh   /* Jump to the end of the loop when the LIMIT is reached
757ec7429aeSdrh   */
758ec7429aeSdrh   if( p->iLimit>=0 ){
75915007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
760ec7429aeSdrh     sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, brk);
761ec7429aeSdrh   }
762ec7429aeSdrh 
763ec7429aeSdrh   /* The bottom of the loop
764ec7429aeSdrh   */
7650342b1f5Sdrh   sqlite3VdbeResolveLabel(v, cont);
7660342b1f5Sdrh   sqlite3VdbeAddOp(v, OP_Next, iTab, addr);
7670342b1f5Sdrh   sqlite3VdbeResolveLabel(v, brk);
768cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
769cdd536f0Sdrh     sqlite3VdbeAddOp(v, OP_Close, pseudoTab, 0);
770cdd536f0Sdrh   }
771cdd536f0Sdrh 
772d8bc7086Sdrh }
773d8bc7086Sdrh 
774d8bc7086Sdrh /*
775517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
776517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
777e78e8284Sdrh **
778955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the
779955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The
780955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
781955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The
782955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is
783955de52cSdanielk1977 ** considered a column by this function.
784e78e8284Sdrh **
785955de52cSdanielk1977 **   SELECT col FROM tbl;
786955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl;
787955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl);
788955de52cSdanielk1977 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
789955de52cSdanielk1977 **
790955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL.
791fcb78a49Sdrh */
792955de52cSdanielk1977 static const char *columnType(
793955de52cSdanielk1977   NameContext *pNC,
794955de52cSdanielk1977   Expr *pExpr,
795955de52cSdanielk1977   const char **pzOriginDb,
796955de52cSdanielk1977   const char **pzOriginTab,
797955de52cSdanielk1977   const char **pzOriginCol
798955de52cSdanielk1977 ){
799955de52cSdanielk1977   char const *zType = 0;
800955de52cSdanielk1977   char const *zOriginDb = 0;
801955de52cSdanielk1977   char const *zOriginTab = 0;
802955de52cSdanielk1977   char const *zOriginCol = 0;
803517eb646Sdanielk1977   int j;
804b3bce662Sdanielk1977   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
8055338a5f7Sdanielk1977 
8065338a5f7Sdanielk1977   /* The TK_AS operator can only occur in ORDER BY, GROUP BY, HAVING,
8075338a5f7Sdanielk1977   ** and LIMIT clauses.  But pExpr originates in the result set of a
8085338a5f7Sdanielk1977   ** SELECT.  So pExpr can never contain an AS operator.
8095338a5f7Sdanielk1977   */
8105338a5f7Sdanielk1977   assert( pExpr->op!=TK_AS );
8115338a5f7Sdanielk1977 
81200e279d9Sdanielk1977   switch( pExpr->op ){
81330bcf5dbSdrh     case TK_AGG_COLUMN:
81400e279d9Sdanielk1977     case TK_COLUMN: {
815955de52cSdanielk1977       /* The expression is a column. Locate the table the column is being
816955de52cSdanielk1977       ** extracted from in NameContext.pSrcList. This table may be real
817955de52cSdanielk1977       ** database table or a subquery.
818955de52cSdanielk1977       */
819955de52cSdanielk1977       Table *pTab = 0;            /* Table structure column is extracted from */
820955de52cSdanielk1977       Select *pS = 0;             /* Select the column is extracted from */
821955de52cSdanielk1977       int iCol = pExpr->iColumn;  /* Index of column in pTab */
822b3bce662Sdanielk1977       while( pNC && !pTab ){
823b3bce662Sdanielk1977         SrcList *pTabList = pNC->pSrcList;
824b3bce662Sdanielk1977         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
825b3bce662Sdanielk1977         if( j<pTabList->nSrc ){
8266a3ea0e6Sdrh           pTab = pTabList->a[j].pTab;
827955de52cSdanielk1977           pS = pTabList->a[j].pSelect;
828b3bce662Sdanielk1977         }else{
829b3bce662Sdanielk1977           pNC = pNC->pNext;
830b3bce662Sdanielk1977         }
831b3bce662Sdanielk1977       }
832955de52cSdanielk1977 
8337e62779aSdrh       if( pTab==0 ){
8347e62779aSdrh         /* FIX ME:
8357e62779aSdrh         ** This can occurs if you have something like "SELECT new.x;" inside
8367e62779aSdrh         ** a trigger.  In other words, if you reference the special "new"
8377e62779aSdrh         ** table in the result set of a select.  We do not have a good way
8387e62779aSdrh         ** to find the actual table type, so call it "TEXT".  This is really
8397e62779aSdrh         ** something of a bug, but I do not know how to fix it.
8407e62779aSdrh         **
8417e62779aSdrh         ** This code does not produce the correct answer - it just prevents
8427e62779aSdrh         ** a segfault.  See ticket #1229.
8437e62779aSdrh         */
8447e62779aSdrh         zType = "TEXT";
8457e62779aSdrh         break;
8467e62779aSdrh       }
847955de52cSdanielk1977 
848b3bce662Sdanielk1977       assert( pTab );
849955de52cSdanielk1977       if( pS ){
850955de52cSdanielk1977         /* The "table" is actually a sub-select or a view in the FROM clause
851955de52cSdanielk1977         ** of the SELECT statement. Return the declaration type and origin
852955de52cSdanielk1977         ** data for the result-set column of the sub-select.
853955de52cSdanielk1977         */
854955de52cSdanielk1977         if( iCol>=0 && iCol<pS->pEList->nExpr ){
855955de52cSdanielk1977           /* If iCol is less than zero, then the expression requests the
856955de52cSdanielk1977           ** rowid of the sub-select or view. This expression is legal (see
857955de52cSdanielk1977           ** test case misc2.2.2) - it always evaluates to NULL.
858955de52cSdanielk1977           */
859955de52cSdanielk1977           NameContext sNC;
860955de52cSdanielk1977           Expr *p = pS->pEList->a[iCol].pExpr;
861955de52cSdanielk1977           sNC.pSrcList = pS->pSrc;
862955de52cSdanielk1977           sNC.pNext = 0;
863955de52cSdanielk1977           sNC.pParse = pNC->pParse;
864955de52cSdanielk1977           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
865955de52cSdanielk1977         }
8664b2688abSdanielk1977       }else if( pTab->pSchema ){
867955de52cSdanielk1977         /* A real table */
868955de52cSdanielk1977         assert( !pS );
869fcb78a49Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
870fcb78a49Sdrh         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
871fcb78a49Sdrh         if( iCol<0 ){
872fcb78a49Sdrh           zType = "INTEGER";
873955de52cSdanielk1977           zOriginCol = "rowid";
874fcb78a49Sdrh         }else{
875fcb78a49Sdrh           zType = pTab->aCol[iCol].zType;
876955de52cSdanielk1977           zOriginCol = pTab->aCol[iCol].zName;
877955de52cSdanielk1977         }
878955de52cSdanielk1977         zOriginTab = pTab->zName;
879955de52cSdanielk1977         if( pNC->pParse ){
880955de52cSdanielk1977           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
881955de52cSdanielk1977           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
882955de52cSdanielk1977         }
883fcb78a49Sdrh       }
88400e279d9Sdanielk1977       break;
885736c22b8Sdrh     }
88693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
88700e279d9Sdanielk1977     case TK_SELECT: {
888955de52cSdanielk1977       /* The expression is a sub-select. Return the declaration type and
889955de52cSdanielk1977       ** origin info for the single column in the result set of the SELECT
890955de52cSdanielk1977       ** statement.
891955de52cSdanielk1977       */
892b3bce662Sdanielk1977       NameContext sNC;
89300e279d9Sdanielk1977       Select *pS = pExpr->pSelect;
894955de52cSdanielk1977       Expr *p = pS->pEList->a[0].pExpr;
895955de52cSdanielk1977       sNC.pSrcList = pS->pSrc;
896b3bce662Sdanielk1977       sNC.pNext = pNC;
897955de52cSdanielk1977       sNC.pParse = pNC->pParse;
898955de52cSdanielk1977       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
89900e279d9Sdanielk1977       break;
900fcb78a49Sdrh     }
90193758c8dSdanielk1977 #endif
90200e279d9Sdanielk1977   }
90300e279d9Sdanielk1977 
904955de52cSdanielk1977   if( pzOriginDb ){
905955de52cSdanielk1977     assert( pzOriginTab && pzOriginCol );
906955de52cSdanielk1977     *pzOriginDb = zOriginDb;
907955de52cSdanielk1977     *pzOriginTab = zOriginTab;
908955de52cSdanielk1977     *pzOriginCol = zOriginCol;
909955de52cSdanielk1977   }
910517eb646Sdanielk1977   return zType;
911517eb646Sdanielk1977 }
912517eb646Sdanielk1977 
913517eb646Sdanielk1977 /*
914517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
915517eb646Sdanielk1977 ** in the result set.
916517eb646Sdanielk1977 */
917517eb646Sdanielk1977 static void generateColumnTypes(
918517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
919517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
920517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
921517eb646Sdanielk1977 ){
922517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
923517eb646Sdanielk1977   int i;
924b3bce662Sdanielk1977   NameContext sNC;
925b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
926955de52cSdanielk1977   sNC.pParse = pParse;
927517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
928517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
929955de52cSdanielk1977     const char *zOrigDb = 0;
930955de52cSdanielk1977     const char *zOrigTab = 0;
931955de52cSdanielk1977     const char *zOrigCol = 0;
932955de52cSdanielk1977     const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
933955de52cSdanielk1977 
9344b1ae99dSdanielk1977     /* The vdbe must make it's own copy of the column-type and other
9354b1ae99dSdanielk1977     ** column specific strings, in case the schema is reset before this
9364b1ae99dSdanielk1977     ** virtual machine is deleted.
937fbcd585fSdanielk1977     */
9384b1ae99dSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P3_TRANSIENT);
9394b1ae99dSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P3_TRANSIENT);
9404b1ae99dSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P3_TRANSIENT);
9414b1ae99dSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P3_TRANSIENT);
942fcb78a49Sdrh   }
943fcb78a49Sdrh }
944fcb78a49Sdrh 
945fcb78a49Sdrh /*
946fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
947fcb78a49Sdrh ** in the result set.  This information is used to provide the
948fcabd464Sdrh ** azCol[] values in the callback.
94982c3d636Sdrh */
950832508b7Sdrh static void generateColumnNames(
951832508b7Sdrh   Parse *pParse,      /* Parser context */
952ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
953832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
954832508b7Sdrh ){
955d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
9566a3ea0e6Sdrh   int i, j;
9579bb575fdSdrh   sqlite3 *db = pParse->db;
958fcabd464Sdrh   int fullNames, shortNames;
959fcabd464Sdrh 
960fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN
9613cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
9623cf86063Sdanielk1977   if( pParse->explain ){
96361de0d1bSdanielk1977     return;
9643cf86063Sdanielk1977   }
9655338a5f7Sdanielk1977 #endif
9663cf86063Sdanielk1977 
967d6502758Sdrh   assert( v!=0 );
9689e12800dSdanielk1977   if( pParse->colNamesSet || v==0 || sqlite3MallocFailed() ) return;
969d8bc7086Sdrh   pParse->colNamesSet = 1;
970fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
971fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
97222322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
97382c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
97482c3d636Sdrh     Expr *p;
9755a38705eSdrh     p = pEList->a[i].pExpr;
9765a38705eSdrh     if( p==0 ) continue;
97782c3d636Sdrh     if( pEList->a[i].zName ){
97882c3d636Sdrh       char *zName = pEList->a[i].zName;
979955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
98082c3d636Sdrh       continue;
98182c3d636Sdrh     }
982fa173a76Sdrh     if( p->op==TK_COLUMN && pTabList ){
9836a3ea0e6Sdrh       Table *pTab;
98497665873Sdrh       char *zCol;
9858aff1015Sdrh       int iCol = p->iColumn;
9866a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
9876a3ea0e6Sdrh       assert( j<pTabList->nSrc );
9886a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
9898aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
99097665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
991b1363206Sdrh       if( iCol<0 ){
99247a6db2bSdrh         zCol = "rowid";
993b1363206Sdrh       }else{
994b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
995b1363206Sdrh       }
996fcabd464Sdrh       if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
997955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
998fcabd464Sdrh       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
99982c3d636Sdrh         char *zName = 0;
100082c3d636Sdrh         char *zTab;
100182c3d636Sdrh 
10026a3ea0e6Sdrh         zTab = pTabList->a[j].zAlias;
1003fcabd464Sdrh         if( fullNames || zTab==0 ) zTab = pTab->zName;
1004f93339deSdrh         sqlite3SetString(&zName, zTab, ".", zCol, (char*)0);
1005955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P3_DYNAMIC);
100682c3d636Sdrh       }else{
1007955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
100882c3d636Sdrh       }
10096977fea8Sdrh     }else if( p->span.z && p->span.z[0] ){
1010955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
10113cf86063Sdanielk1977       /* sqlite3VdbeCompressSpace(v, addr); */
10121bee3d7bSdrh     }else{
10131bee3d7bSdrh       char zName[30];
10141bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
1015*5bb3eb9bSdrh       sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1);
1016955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0);
101782c3d636Sdrh     }
101882c3d636Sdrh   }
101976d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
10205080aaa7Sdrh }
102182c3d636Sdrh 
102293758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
102382c3d636Sdrh /*
1024d8bc7086Sdrh ** Name of the connection operator, used for error messages.
1025d8bc7086Sdrh */
1026d8bc7086Sdrh static const char *selectOpName(int id){
1027d8bc7086Sdrh   char *z;
1028d8bc7086Sdrh   switch( id ){
1029d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
1030d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
1031d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
1032d8bc7086Sdrh     default:           z = "UNION";       break;
1033d8bc7086Sdrh   }
1034d8bc7086Sdrh   return z;
1035d8bc7086Sdrh }
103693758c8dSdanielk1977 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1037d8bc7086Sdrh 
1038d8bc7086Sdrh /*
1039315555caSdrh ** Forward declaration
1040315555caSdrh */
10419b3187e1Sdrh static int prepSelectStmt(Parse*, Select*);
1042315555caSdrh 
1043315555caSdrh /*
104422f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
104522f70c32Sdrh ** the result set of that SELECT.
104622f70c32Sdrh */
10474adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
104822f70c32Sdrh   Table *pTab;
1049b733d037Sdrh   int i, j;
105022f70c32Sdrh   ExprList *pEList;
1051290c1948Sdrh   Column *aCol, *pCol;
105222f70c32Sdrh 
105392378253Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
10549b3187e1Sdrh   if( prepSelectStmt(pParse, pSelect) ){
105522f70c32Sdrh     return 0;
105622f70c32Sdrh   }
1057142bdf40Sdanielk1977   if( sqlite3SelectResolve(pParse, pSelect, 0) ){
1058142bdf40Sdanielk1977     return 0;
1059142bdf40Sdanielk1977   }
106022f70c32Sdrh   pTab = sqliteMalloc( sizeof(Table) );
106122f70c32Sdrh   if( pTab==0 ){
106222f70c32Sdrh     return 0;
106322f70c32Sdrh   }
1064ed8a3bb1Sdrh   pTab->nRef = 1;
106522f70c32Sdrh   pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
106622f70c32Sdrh   pEList = pSelect->pEList;
106722f70c32Sdrh   pTab->nCol = pEList->nExpr;
1068417be79cSdrh   assert( pTab->nCol>0 );
1069b733d037Sdrh   pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
1070290c1948Sdrh   for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
107179d5f63fSdrh     Expr *p, *pR;
1072517eb646Sdanielk1977     char *zType;
107391bb0eedSdrh     char *zName;
10742564ef97Sdrh     int nName;
1075b3bf556eSdanielk1977     CollSeq *pColl;
107679d5f63fSdrh     int cnt;
1077b3bce662Sdanielk1977     NameContext sNC;
107879d5f63fSdrh 
107979d5f63fSdrh     /* Get an appropriate name for the column
108079d5f63fSdrh     */
108179d5f63fSdrh     p = pEList->a[i].pExpr;
1082290c1948Sdrh     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
108391bb0eedSdrh     if( (zName = pEList->a[i].zName)!=0 ){
108479d5f63fSdrh       /* If the column contains an "AS <name>" phrase, use <name> as the name */
108591bb0eedSdrh       zName = sqliteStrDup(zName);
1086517eb646Sdanielk1977     }else if( p->op==TK_DOT
1087b733d037Sdrh               && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
108879d5f63fSdrh       /* For columns of the from A.B use B as the name */
108991bb0eedSdrh       zName = sqlite3MPrintf("%T", &pR->token);
1090b733d037Sdrh     }else if( p->span.z && p->span.z[0] ){
109179d5f63fSdrh       /* Use the original text of the column expression as its name */
109291bb0eedSdrh       zName = sqlite3MPrintf("%T", &p->span);
109322f70c32Sdrh     }else{
109479d5f63fSdrh       /* If all else fails, make up a name */
109591bb0eedSdrh       zName = sqlite3MPrintf("column%d", i+1);
109622f70c32Sdrh     }
109791bb0eedSdrh     sqlite3Dequote(zName);
10989e12800dSdanielk1977     if( sqlite3MallocFailed() ){
1099dd5b2fa5Sdrh       sqliteFree(zName);
1100a04a34ffSdanielk1977       sqlite3DeleteTable(pTab);
1101dd5b2fa5Sdrh       return 0;
1102dd5b2fa5Sdrh     }
110379d5f63fSdrh 
110479d5f63fSdrh     /* Make sure the column name is unique.  If the name is not unique,
110579d5f63fSdrh     ** append a integer to the name so that it becomes unique.
110679d5f63fSdrh     */
11072564ef97Sdrh     nName = strlen(zName);
110879d5f63fSdrh     for(j=cnt=0; j<i; j++){
110979d5f63fSdrh       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
11102564ef97Sdrh         zName[nName] = 0;
11112564ef97Sdrh         zName = sqlite3MPrintf("%z:%d", zName, ++cnt);
111279d5f63fSdrh         j = -1;
1113dd5b2fa5Sdrh         if( zName==0 ) break;
111479d5f63fSdrh       }
111579d5f63fSdrh     }
111691bb0eedSdrh     pCol->zName = zName;
1117e014a838Sdanielk1977 
111879d5f63fSdrh     /* Get the typename, type affinity, and collating sequence for the
111979d5f63fSdrh     ** column.
112079d5f63fSdrh     */
1121c43e8be8Sdrh     memset(&sNC, 0, sizeof(sNC));
1122b3bce662Sdanielk1977     sNC.pSrcList = pSelect->pSrc;
1123955de52cSdanielk1977     zType = sqliteStrDup(columnType(&sNC, p, 0, 0, 0));
1124290c1948Sdrh     pCol->zType = zType;
1125c60e9b82Sdanielk1977     pCol->affinity = sqlite3ExprAffinity(p);
1126b3bf556eSdanielk1977     pColl = sqlite3ExprCollSeq(pParse, p);
1127b3bf556eSdanielk1977     if( pColl ){
1128e7259296Sdanielk1977       pCol->zColl = sqliteStrDup(pColl->zName);
11290202b29eSdanielk1977     }
113022f70c32Sdrh   }
113122f70c32Sdrh   pTab->iPKey = -1;
113222f70c32Sdrh   return pTab;
113322f70c32Sdrh }
113422f70c32Sdrh 
113522f70c32Sdrh /*
11369b3187e1Sdrh ** Prepare a SELECT statement for processing by doing the following
11379b3187e1Sdrh ** things:
1138d8bc7086Sdrh **
11399b3187e1Sdrh **    (1)  Make sure VDBE cursor numbers have been assigned to every
11409b3187e1Sdrh **         element of the FROM clause.
11419b3187e1Sdrh **
11429b3187e1Sdrh **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
11439b3187e1Sdrh **         defines FROM clause.  When views appear in the FROM clause,
114463eb5f29Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
114563eb5f29Sdrh **         that implements the view.  A copy is made of the view's SELECT
114663eb5f29Sdrh **         statement so that we can freely modify or delete that statement
114763eb5f29Sdrh **         without worrying about messing up the presistent representation
114863eb5f29Sdrh **         of the view.
1149d8bc7086Sdrh **
11509b3187e1Sdrh **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
1151ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
1152ad2d8307Sdrh **
11539b3187e1Sdrh **    (4)  Scan the list of columns in the result set (pEList) looking
115454473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
115554473229Sdrh **         If found, expand each "*" to be every column in every table
115654473229Sdrh **         and TABLE.* to be every column in TABLE.
1157d8bc7086Sdrh **
1158d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
1159d8bc7086Sdrh ** in pParse and return non-zero.
1160d8bc7086Sdrh */
11619b3187e1Sdrh static int prepSelectStmt(Parse *pParse, Select *p){
116254473229Sdrh   int i, j, k, rc;
1163ad3cab52Sdrh   SrcList *pTabList;
1164daffd0e5Sdrh   ExprList *pEList;
1165290c1948Sdrh   struct SrcList_item *pFrom;
1166daffd0e5Sdrh 
11679e12800dSdanielk1977   if( p==0 || p->pSrc==0 || sqlite3MallocFailed() ){
11686f7adc8aSdrh     return 1;
11696f7adc8aSdrh   }
1170daffd0e5Sdrh   pTabList = p->pSrc;
1171daffd0e5Sdrh   pEList = p->pEList;
1172d8bc7086Sdrh 
11739b3187e1Sdrh   /* Make sure cursor numbers have been assigned to all entries in
11749b3187e1Sdrh   ** the FROM clause of the SELECT statement.
11759b3187e1Sdrh   */
11769b3187e1Sdrh   sqlite3SrcListAssignCursors(pParse, p->pSrc);
11779b3187e1Sdrh 
11789b3187e1Sdrh   /* Look up every table named in the FROM clause of the select.  If
11799b3187e1Sdrh   ** an entry of the FROM clause is a subquery instead of a table or view,
11809b3187e1Sdrh   ** then create a transient table structure to describe the subquery.
1181d8bc7086Sdrh   */
1182290c1948Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1183f0113000Sdanielk1977     Table *pTab;
11849b3187e1Sdrh     if( pFrom->pTab!=0 ){
11859b3187e1Sdrh       /* This statement has already been prepared.  There is no need
11869b3187e1Sdrh       ** to go further. */
11879b3187e1Sdrh       assert( i==0 );
1188d8bc7086Sdrh       return 0;
1189d8bc7086Sdrh     }
1190290c1948Sdrh     if( pFrom->zName==0 ){
119193758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
119222f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
1193290c1948Sdrh       assert( pFrom->pSelect!=0 );
1194290c1948Sdrh       if( pFrom->zAlias==0 ){
119591bb0eedSdrh         pFrom->zAlias =
119691bb0eedSdrh           sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
1197ad2d8307Sdrh       }
1198ed8a3bb1Sdrh       assert( pFrom->pTab==0 );
1199290c1948Sdrh       pFrom->pTab = pTab =
1200290c1948Sdrh         sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
120122f70c32Sdrh       if( pTab==0 ){
1202daffd0e5Sdrh         return 1;
1203daffd0e5Sdrh       }
1204b9bb7c18Sdrh       /* The isEphem flag indicates that the Table structure has been
12055cf590c1Sdrh       ** dynamically allocated and may be freed at any time.  In other words,
12065cf590c1Sdrh       ** pTab is not pointing to a persistent table structure that defines
12075cf590c1Sdrh       ** part of the schema. */
1208b9bb7c18Sdrh       pTab->isEphem = 1;
120993758c8dSdanielk1977 #endif
121022f70c32Sdrh     }else{
1211a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
1212ed8a3bb1Sdrh       assert( pFrom->pTab==0 );
1213290c1948Sdrh       pFrom->pTab = pTab =
1214290c1948Sdrh         sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
1215a76b5dfcSdrh       if( pTab==0 ){
1216d8bc7086Sdrh         return 1;
1217d8bc7086Sdrh       }
1218ed8a3bb1Sdrh       pTab->nRef++;
121993626f48Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
122093626f48Sdanielk1977       if( pTab->pSelect || IsVirtual(pTab) ){
122163eb5f29Sdrh         /* We reach here if the named table is a really a view */
12224adee20fSdanielk1977         if( sqlite3ViewGetColumnNames(pParse, pTab) ){
1223417be79cSdrh           return 1;
1224417be79cSdrh         }
1225290c1948Sdrh         /* If pFrom->pSelect!=0 it means we are dealing with a
122663eb5f29Sdrh         ** view within a view.  The SELECT structure has already been
122763eb5f29Sdrh         ** copied by the outer view so we can skip the copy step here
122863eb5f29Sdrh         ** in the inner view.
122963eb5f29Sdrh         */
1230290c1948Sdrh         if( pFrom->pSelect==0 ){
1231290c1948Sdrh           pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
1232a76b5dfcSdrh         }
1233d8bc7086Sdrh       }
123493758c8dSdanielk1977 #endif
123522f70c32Sdrh     }
123663eb5f29Sdrh   }
1237d8bc7086Sdrh 
1238ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
1239ad2d8307Sdrh   */
1240ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
1241ad2d8307Sdrh 
12427c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
124354473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
124454473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
12457c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
12467c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
12477c917d19Sdrh   ** each one to the list of all columns in all tables.
124854473229Sdrh   **
124954473229Sdrh   ** The first loop just checks to see if there are any "*" operators
125054473229Sdrh   ** that need expanding.
1251d8bc7086Sdrh   */
12527c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
125354473229Sdrh     Expr *pE = pEList->a[k].pExpr;
125454473229Sdrh     if( pE->op==TK_ALL ) break;
125554473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
125654473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
12577c917d19Sdrh   }
125854473229Sdrh   rc = 0;
12597c917d19Sdrh   if( k<pEList->nExpr ){
126054473229Sdrh     /*
126154473229Sdrh     ** If we get here it means the result set contains one or more "*"
126254473229Sdrh     ** operators that need to be expanded.  Loop through each expression
126354473229Sdrh     ** in the result set and expand them one by one.
126454473229Sdrh     */
12657c917d19Sdrh     struct ExprList_item *a = pEList->a;
12667c917d19Sdrh     ExprList *pNew = 0;
1267d70dc52dSdrh     int flags = pParse->db->flags;
1268d70dc52dSdrh     int longNames = (flags & SQLITE_FullColNames)!=0 &&
1269d70dc52dSdrh                       (flags & SQLITE_ShortColNames)==0;
1270d70dc52dSdrh 
12717c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
127254473229Sdrh       Expr *pE = a[k].pExpr;
127354473229Sdrh       if( pE->op!=TK_ALL &&
127454473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
127554473229Sdrh         /* This particular expression does not need to be expanded.
127654473229Sdrh         */
12774adee20fSdanielk1977         pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
1278261919ccSdanielk1977         if( pNew ){
12797c917d19Sdrh           pNew->a[pNew->nExpr-1].zName = a[k].zName;
1280261919ccSdanielk1977         }else{
1281261919ccSdanielk1977           rc = 1;
1282261919ccSdanielk1977         }
12837c917d19Sdrh         a[k].pExpr = 0;
12847c917d19Sdrh         a[k].zName = 0;
12857c917d19Sdrh       }else{
128654473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
128754473229Sdrh         ** expanded. */
128854473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
1289cf55b7aeSdrh         char *zTName;            /* text of name of TABLE */
129054473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
1291cf55b7aeSdrh           zTName = sqlite3NameFromToken(&pE->pLeft->token);
129254473229Sdrh         }else{
1293cf55b7aeSdrh           zTName = 0;
129454473229Sdrh         }
1295290c1948Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1296290c1948Sdrh           Table *pTab = pFrom->pTab;
1297290c1948Sdrh           char *zTabName = pFrom->zAlias;
129854473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
129954473229Sdrh             zTabName = pTab->zName;
130054473229Sdrh           }
1301cf55b7aeSdrh           if( zTName && (zTabName==0 || zTabName[0]==0 ||
1302cf55b7aeSdrh                  sqlite3StrICmp(zTName, zTabName)!=0) ){
130354473229Sdrh             continue;
130454473229Sdrh           }
130554473229Sdrh           tableSeen = 1;
1306d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
1307f0113000Sdanielk1977             Expr *pExpr, *pRight;
1308ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
1309ad2d8307Sdrh 
131091bb0eedSdrh             if( i>0 ){
131191bb0eedSdrh               struct SrcList_item *pLeft = &pTabList->a[i-1];
131261dfc31dSdrh               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
131391bb0eedSdrh                         columnIndex(pLeft->pTab, zName)>=0 ){
1314ad2d8307Sdrh                 /* In a NATURAL join, omit the join columns from the
1315ad2d8307Sdrh                 ** table on the right */
1316ad2d8307Sdrh                 continue;
1317ad2d8307Sdrh               }
131861dfc31dSdrh               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
1319ad2d8307Sdrh                 /* In a join with a USING clause, omit columns in the
1320ad2d8307Sdrh                 ** using clause from the table on the right. */
1321ad2d8307Sdrh                 continue;
1322ad2d8307Sdrh               }
132391bb0eedSdrh             }
13244adee20fSdanielk1977             pRight = sqlite3Expr(TK_ID, 0, 0, 0);
132522f70c32Sdrh             if( pRight==0 ) break;
132691bb0eedSdrh             setToken(&pRight->token, zName);
1327d70dc52dSdrh             if( zTabName && (longNames || pTabList->nSrc>1) ){
1328f0113000Sdanielk1977               Expr *pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
13294adee20fSdanielk1977               pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
133022f70c32Sdrh               if( pExpr==0 ) break;
133191bb0eedSdrh               setToken(&pLeft->token, zTabName);
133291bb0eedSdrh               setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
13336977fea8Sdrh               pExpr->span.dyn = 1;
13346977fea8Sdrh               pExpr->token.z = 0;
13356977fea8Sdrh               pExpr->token.n = 0;
13366977fea8Sdrh               pExpr->token.dyn = 0;
133722f70c32Sdrh             }else{
133822f70c32Sdrh               pExpr = pRight;
13396977fea8Sdrh               pExpr->span = pExpr->token;
134022f70c32Sdrh             }
1341d70dc52dSdrh             if( longNames ){
1342d70dc52dSdrh               pNew = sqlite3ExprListAppend(pNew, pExpr, &pExpr->span);
1343d70dc52dSdrh             }else{
134479d5f63fSdrh               pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token);
1345d8bc7086Sdrh             }
1346d8bc7086Sdrh           }
1347d70dc52dSdrh         }
134854473229Sdrh         if( !tableSeen ){
1349cf55b7aeSdrh           if( zTName ){
1350cf55b7aeSdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
1351f5db2d3eSdrh           }else{
13524adee20fSdanielk1977             sqlite3ErrorMsg(pParse, "no tables specified");
1353f5db2d3eSdrh           }
135454473229Sdrh           rc = 1;
135554473229Sdrh         }
1356cf55b7aeSdrh         sqliteFree(zTName);
13577c917d19Sdrh       }
13587c917d19Sdrh     }
13594adee20fSdanielk1977     sqlite3ExprListDelete(pEList);
13607c917d19Sdrh     p->pEList = pNew;
1361d8bc7086Sdrh   }
136254473229Sdrh   return rc;
1363d8bc7086Sdrh }
1364d8bc7086Sdrh 
136593758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1366ff78bd2fSdrh /*
1367d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with
1368d8bc7086Sdrh ** columns in a result.  For each ORDER BY expression, the opcode of
1369967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of
1370d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable
1371d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter.
1372d8bc7086Sdrh **
1373d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first.  A match
1374d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT.
1375d8bc7086Sdrh **
1376d8bc7086Sdrh ** Any entry that does not match is flagged as an error.  The number
1377d8bc7086Sdrh ** of errors is returned.
1378d8bc7086Sdrh */
1379d8bc7086Sdrh static int matchOrderbyToColumn(
1380d8bc7086Sdrh   Parse *pParse,          /* A place to leave error messages */
1381d8bc7086Sdrh   Select *pSelect,        /* Match to result columns of this SELECT */
1382d8bc7086Sdrh   ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
1383e4de1febSdrh   int iTable,             /* Insert this value in iTable */
1384d8bc7086Sdrh   int mustComplete        /* If TRUE all ORDER BYs must match */
1385d8bc7086Sdrh ){
1386d8bc7086Sdrh   int nErr = 0;
1387d8bc7086Sdrh   int i, j;
1388d8bc7086Sdrh   ExprList *pEList;
1389d8bc7086Sdrh 
1390daffd0e5Sdrh   if( pSelect==0 || pOrderBy==0 ) return 1;
1391d8bc7086Sdrh   if( mustComplete ){
1392d8bc7086Sdrh     for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1393d8bc7086Sdrh   }
13949b3187e1Sdrh   if( prepSelectStmt(pParse, pSelect) ){
1395d8bc7086Sdrh     return 1;
1396d8bc7086Sdrh   }
1397d8bc7086Sdrh   if( pSelect->pPrior ){
139892cd52f5Sdrh     if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
139992cd52f5Sdrh       return 1;
140092cd52f5Sdrh     }
1401d8bc7086Sdrh   }
1402d8bc7086Sdrh   pEList = pSelect->pEList;
1403d8bc7086Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
140494ccde58Sdrh     struct ExprList_item *pItem;
1405d8bc7086Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
1406e4de1febSdrh     int iCol = -1;
140794ccde58Sdrh     char *zLabel;
140894ccde58Sdrh 
1409d8bc7086Sdrh     if( pOrderBy->a[i].done ) continue;
14104adee20fSdanielk1977     if( sqlite3ExprIsInteger(pE, &iCol) ){
1411e4de1febSdrh       if( iCol<=0 || iCol>pEList->nExpr ){
14124adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
1413da93d238Sdrh           "ORDER BY position %d should be between 1 and %d",
1414e4de1febSdrh           iCol, pEList->nExpr);
1415e4de1febSdrh         nErr++;
1416e4de1febSdrh         break;
1417e4de1febSdrh       }
1418fcb78a49Sdrh       if( !mustComplete ) continue;
1419e4de1febSdrh       iCol--;
1420e4de1febSdrh     }
142194ccde58Sdrh     if( iCol<0 && (zLabel = sqlite3NameFromToken(&pE->token))!=0 ){
142294ccde58Sdrh       for(j=0, pItem=pEList->a; j<pEList->nExpr; j++, pItem++){
142394ccde58Sdrh         char *zName;
14245ea2df91Sdrh         int isMatch;
142594ccde58Sdrh         if( pItem->zName ){
142694ccde58Sdrh           zName = sqlite3StrDup(pItem->zName);
142794ccde58Sdrh         }else{
142894ccde58Sdrh           zName = sqlite3NameFromToken(&pItem->pExpr->token);
142994ccde58Sdrh         }
14305ea2df91Sdrh         isMatch = zName && sqlite3StrICmp(zName, zLabel)==0;
14315ea2df91Sdrh         sqliteFree(zName);
14325ea2df91Sdrh         if( isMatch ){
1433e4de1febSdrh           iCol = j;
143494ccde58Sdrh           break;
143594ccde58Sdrh         }
1436d8bc7086Sdrh       }
14376e142f54Sdrh       sqliteFree(zLabel);
1438d8bc7086Sdrh     }
1439e4de1febSdrh     if( iCol>=0 ){
1440967e8b73Sdrh       pE->op = TK_COLUMN;
1441e4de1febSdrh       pE->iColumn = iCol;
1442d8bc7086Sdrh       pE->iTable = iTable;
1443a58fdfb1Sdanielk1977       pE->iAgg = -1;
1444d8bc7086Sdrh       pOrderBy->a[i].done = 1;
144594ccde58Sdrh     }else if( mustComplete ){
14464adee20fSdanielk1977       sqlite3ErrorMsg(pParse,
1447da93d238Sdrh         "ORDER BY term number %d does not match any result column", i+1);
1448d8bc7086Sdrh       nErr++;
1449d8bc7086Sdrh       break;
1450d8bc7086Sdrh     }
1451d8bc7086Sdrh   }
1452d8bc7086Sdrh   return nErr;
1453d8bc7086Sdrh }
145493758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */
1455d8bc7086Sdrh 
1456d8bc7086Sdrh /*
1457d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1458d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1459d8bc7086Sdrh */
14604adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1461d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1462d8bc7086Sdrh   if( v==0 ){
14634adee20fSdanielk1977     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1464d8bc7086Sdrh   }
1465d8bc7086Sdrh   return v;
1466d8bc7086Sdrh }
1467d8bc7086Sdrh 
146815007a99Sdrh 
1469d8bc7086Sdrh /*
14707b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
1471ec7429aeSdrh ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
14727b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
1473a2dc3b1aSdanielk1977 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1474a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute
1475a2dc3b1aSdanielk1977 ** the limit and offset.  If there is no limit and/or offset, then
1476a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative.
14777b58daeaSdrh **
1478d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if
1479ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset.  iLimit and
14807b58daeaSdrh ** iOffset should have been preset to appropriate default values
14817b58daeaSdrh ** (usually but not always -1) prior to calling this routine.
1482ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
14837b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
14847b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
14857b58daeaSdrh ** SELECT statements.
14867b58daeaSdrh */
1487ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
148802afc861Sdrh   Vdbe *v = 0;
148902afc861Sdrh   int iLimit = 0;
149015007a99Sdrh   int iOffset;
149115007a99Sdrh   int addr1, addr2;
149215007a99Sdrh 
14937b58daeaSdrh   /*
14947b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
14957b58daeaSdrh   ** contraversy about what the correct behavior should be.
14967b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
14977b58daeaSdrh   ** no rows.
14987b58daeaSdrh   */
1499a2dc3b1aSdanielk1977   if( p->pLimit ){
150015007a99Sdrh     p->iLimit = iLimit = pParse->nMem;
1501d59ba6ceSdrh     pParse->nMem += 2;
150215007a99Sdrh     v = sqlite3GetVdbe(pParse);
15037b58daeaSdrh     if( v==0 ) return;
1504a2dc3b1aSdanielk1977     sqlite3ExprCode(pParse, p->pLimit);
1505a2dc3b1aSdanielk1977     sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
150615007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iLimit, 0);
1507ad6d9460Sdrh     VdbeComment((v, "# LIMIT counter"));
150815007a99Sdrh     sqlite3VdbeAddOp(v, OP_IfMemZero, iLimit, iBreak);
15097b58daeaSdrh   }
1510a2dc3b1aSdanielk1977   if( p->pOffset ){
151115007a99Sdrh     p->iOffset = iOffset = pParse->nMem++;
151215007a99Sdrh     v = sqlite3GetVdbe(pParse);
15137b58daeaSdrh     if( v==0 ) return;
1514a2dc3b1aSdanielk1977     sqlite3ExprCode(pParse, p->pOffset);
1515a2dc3b1aSdanielk1977     sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
151615007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iOffset, p->pLimit==0);
1517ad6d9460Sdrh     VdbeComment((v, "# OFFSET counter"));
151815007a99Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iOffset, 0);
151915007a99Sdrh     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
152015007a99Sdrh     sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
152115007a99Sdrh     sqlite3VdbeJumpHere(v, addr1);
1522d59ba6ceSdrh     if( p->pLimit ){
1523d59ba6ceSdrh       sqlite3VdbeAddOp(v, OP_Add, 0, 0);
1524d59ba6ceSdrh     }
15257b58daeaSdrh   }
1526d59ba6ceSdrh   if( p->pLimit ){
152715007a99Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iLimit, 0);
152815007a99Sdrh     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
152915007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemInt, -1, iLimit+1);
153015007a99Sdrh     addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
153115007a99Sdrh     sqlite3VdbeJumpHere(v, addr1);
153215007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iLimit+1, 1);
1533d59ba6ceSdrh     VdbeComment((v, "# LIMIT+OFFSET"));
153415007a99Sdrh     sqlite3VdbeJumpHere(v, addr2);
1535d59ba6ceSdrh   }
15367b58daeaSdrh }
15377b58daeaSdrh 
15387b58daeaSdrh /*
15390342b1f5Sdrh ** Allocate a virtual index to use for sorting.
1540d3d39e93Sdrh */
15414db38a70Sdrh static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
15420342b1f5Sdrh   if( pOrderBy ){
1543dc1bdc4fSdanielk1977     int addr;
15449d2985c7Sdrh     assert( pOrderBy->iECursor==0 );
15459d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
1546b9bb7c18Sdrh     addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenEphemeral,
15479d2985c7Sdrh                             pOrderBy->iECursor, pOrderBy->nExpr+1);
1548b9bb7c18Sdrh     assert( p->addrOpenEphm[2] == -1 );
1549b9bb7c18Sdrh     p->addrOpenEphm[2] = addr;
1550736c22b8Sdrh   }
1551dc1bdc4fSdanielk1977 }
1552dc1bdc4fSdanielk1977 
1553b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1554fbc4ee7bSdrh /*
1555fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
1556fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
1557fbc4ee7bSdrh ** the column has no default collating sequence.
1558fbc4ee7bSdrh **
1559fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
1560fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
1561fbc4ee7bSdrh */
1562dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1563fbc4ee7bSdrh   CollSeq *pRet;
1564dc1bdc4fSdanielk1977   if( p->pPrior ){
1565dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1566fbc4ee7bSdrh   }else{
1567fbc4ee7bSdrh     pRet = 0;
1568dc1bdc4fSdanielk1977   }
1569fbc4ee7bSdrh   if( pRet==0 ){
1570dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1571dc1bdc4fSdanielk1977   }
1572dc1bdc4fSdanielk1977   return pRet;
1573d3d39e93Sdrh }
1574b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1575d3d39e93Sdrh 
1576b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1577d3d39e93Sdrh /*
157882c3d636Sdrh ** This routine is called to process a query that is really the union
157982c3d636Sdrh ** or intersection of two or more separate queries.
1580c926afbcSdrh **
1581e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1582e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1583e78e8284Sdrh ** in which case this routine will be called recursively.
1584e78e8284Sdrh **
1585e78e8284Sdrh ** The results of the total query are to be written into a destination
1586e78e8284Sdrh ** of type eDest with parameter iParm.
1587e78e8284Sdrh **
1588e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1589e78e8284Sdrh **
1590e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1591e78e8284Sdrh **
1592e78e8284Sdrh ** This statement is parsed up as follows:
1593e78e8284Sdrh **
1594e78e8284Sdrh **     SELECT c FROM t3
1595e78e8284Sdrh **      |
1596e78e8284Sdrh **      `----->  SELECT b FROM t2
1597e78e8284Sdrh **                |
15984b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1599e78e8284Sdrh **
1600e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1601e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1602e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1603e78e8284Sdrh **
1604e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1605e78e8284Sdrh ** individual selects always group from left to right.
160682c3d636Sdrh */
160784ac9d02Sdanielk1977 static int multiSelect(
1608fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
1609fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
1610fbc4ee7bSdrh   int eDest,            /* \___  Store query results as specified */
1611fbc4ee7bSdrh   int iParm,            /* /     by these two parameters.         */
161284ac9d02Sdanielk1977   char *aff             /* If eDest is SRT_Union, the affinity string */
161384ac9d02Sdanielk1977 ){
161484ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
161510e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
161610e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
16178cdbf836Sdrh   int nCol;             /* Number of columns in the result set */
16180342b1f5Sdrh   ExprList *pOrderBy;   /* The ORDER BY clause on p */
16190342b1f5Sdrh   int aSetP2[2];        /* Set P2 value of these op to number of columns */
16200342b1f5Sdrh   int nSetP2 = 0;       /* Number of slots in aSetP2[] used */
162182c3d636Sdrh 
16227b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1623fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
162482c3d636Sdrh   */
162584ac9d02Sdanielk1977   if( p==0 || p->pPrior==0 ){
162684ac9d02Sdanielk1977     rc = 1;
162784ac9d02Sdanielk1977     goto multi_select_end;
162884ac9d02Sdanielk1977   }
1629d8bc7086Sdrh   pPrior = p->pPrior;
16300342b1f5Sdrh   assert( pPrior->pRightmost!=pPrior );
16310342b1f5Sdrh   assert( pPrior->pRightmost==p->pRightmost );
1632d8bc7086Sdrh   if( pPrior->pOrderBy ){
16334adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1634da93d238Sdrh       selectOpName(p->op));
163584ac9d02Sdanielk1977     rc = 1;
163684ac9d02Sdanielk1977     goto multi_select_end;
163782c3d636Sdrh   }
1638a2dc3b1aSdanielk1977   if( pPrior->pLimit ){
16394adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
16407b58daeaSdrh       selectOpName(p->op));
164184ac9d02Sdanielk1977     rc = 1;
164284ac9d02Sdanielk1977     goto multi_select_end;
16437b58daeaSdrh   }
164482c3d636Sdrh 
1645d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
1646d8bc7086Sdrh   */
16474adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
164884ac9d02Sdanielk1977   if( v==0 ){
164984ac9d02Sdanielk1977     rc = 1;
165084ac9d02Sdanielk1977     goto multi_select_end;
165184ac9d02Sdanielk1977   }
1652d8bc7086Sdrh 
16531cc3d75fSdrh   /* Create the destination temporary table if necessary
16541cc3d75fSdrh   */
1655b9bb7c18Sdrh   if( eDest==SRT_EphemTab ){
1656b4964b72Sdanielk1977     assert( p->pEList );
16570342b1f5Sdrh     assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1658b9bb7c18Sdrh     aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 0);
16591cc3d75fSdrh     eDest = SRT_Table;
16601cc3d75fSdrh   }
16611cc3d75fSdrh 
1662f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1663d8bc7086Sdrh   */
16640342b1f5Sdrh   pOrderBy = p->pOrderBy;
166582c3d636Sdrh   switch( p->op ){
1666f46f905aSdrh     case TK_ALL: {
16670342b1f5Sdrh       if( pOrderBy==0 ){
1668ec7429aeSdrh         int addr = 0;
1669a2dc3b1aSdanielk1977         assert( !pPrior->pLimit );
1670a2dc3b1aSdanielk1977         pPrior->pLimit = p->pLimit;
1671a2dc3b1aSdanielk1977         pPrior->pOffset = p->pOffset;
1672b3bce662Sdanielk1977         rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
1673ad68cb6bSdanielk1977         p->pLimit = 0;
1674ad68cb6bSdanielk1977         p->pOffset = 0;
167584ac9d02Sdanielk1977         if( rc ){
167684ac9d02Sdanielk1977           goto multi_select_end;
167784ac9d02Sdanielk1977         }
1678f46f905aSdrh         p->pPrior = 0;
16797b58daeaSdrh         p->iLimit = pPrior->iLimit;
16807b58daeaSdrh         p->iOffset = pPrior->iOffset;
1681ec7429aeSdrh         if( p->iLimit>=0 ){
1682ec7429aeSdrh           addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0);
1683ec7429aeSdrh           VdbeComment((v, "# Jump ahead if LIMIT reached"));
1684ec7429aeSdrh         }
1685b3bce662Sdanielk1977         rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
1686f46f905aSdrh         p->pPrior = pPrior;
168784ac9d02Sdanielk1977         if( rc ){
168884ac9d02Sdanielk1977           goto multi_select_end;
168984ac9d02Sdanielk1977         }
1690ec7429aeSdrh         if( addr ){
1691ec7429aeSdrh           sqlite3VdbeJumpHere(v, addr);
1692ec7429aeSdrh         }
1693f46f905aSdrh         break;
1694f46f905aSdrh       }
1695f46f905aSdrh       /* For UNION ALL ... ORDER BY fall through to the next case */
1696f46f905aSdrh     }
169782c3d636Sdrh     case TK_EXCEPT:
169882c3d636Sdrh     case TK_UNION: {
1699d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1700742f947bSdanielk1977       int op = 0;      /* One of the SRT_ operations to apply to self */
1701d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
1702a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
1703dc1bdc4fSdanielk1977       int addr;
170482c3d636Sdrh 
1705d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
17060342b1f5Sdrh       if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
1707d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1708c926afbcSdrh         ** right.
1709d8bc7086Sdrh         */
171082c3d636Sdrh         unionTab = iParm;
171182c3d636Sdrh       }else{
1712d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1713d8bc7086Sdrh         ** intermediate results.
1714d8bc7086Sdrh         */
171582c3d636Sdrh         unionTab = pParse->nTab++;
17160342b1f5Sdrh         if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){
171784ac9d02Sdanielk1977           rc = 1;
171884ac9d02Sdanielk1977           goto multi_select_end;
1719d8bc7086Sdrh         }
1720b9bb7c18Sdrh         addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, unionTab, 0);
17210342b1f5Sdrh         if( priorOp==SRT_Table ){
17220342b1f5Sdrh           assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
17230342b1f5Sdrh           aSetP2[nSetP2++] = addr;
17240342b1f5Sdrh         }else{
1725b9bb7c18Sdrh           assert( p->addrOpenEphm[0] == -1 );
1726b9bb7c18Sdrh           p->addrOpenEphm[0] = addr;
1727b9bb7c18Sdrh           p->pRightmost->usesEphm = 1;
1728dc1bdc4fSdanielk1977         }
17290342b1f5Sdrh         createSortingIndex(pParse, p, pOrderBy);
173084ac9d02Sdanielk1977         assert( p->pEList );
1731d8bc7086Sdrh       }
1732d8bc7086Sdrh 
1733d8bc7086Sdrh       /* Code the SELECT statements to our left
1734d8bc7086Sdrh       */
1735b3bce662Sdanielk1977       assert( !pPrior->pOrderBy );
1736b3bce662Sdanielk1977       rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
173784ac9d02Sdanielk1977       if( rc ){
173884ac9d02Sdanielk1977         goto multi_select_end;
173984ac9d02Sdanielk1977       }
1740d8bc7086Sdrh 
1741d8bc7086Sdrh       /* Code the current SELECT statement
1742d8bc7086Sdrh       */
1743d8bc7086Sdrh       switch( p->op ){
1744d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
1745d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
1746d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
1747d8bc7086Sdrh       }
174882c3d636Sdrh       p->pPrior = 0;
1749c926afbcSdrh       p->pOrderBy = 0;
17504b14b4d7Sdrh       p->disallowOrderBy = pOrderBy!=0;
1751a2dc3b1aSdanielk1977       pLimit = p->pLimit;
1752a2dc3b1aSdanielk1977       p->pLimit = 0;
1753a2dc3b1aSdanielk1977       pOffset = p->pOffset;
1754a2dc3b1aSdanielk1977       p->pOffset = 0;
1755b3bce662Sdanielk1977       rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
175682c3d636Sdrh       p->pPrior = pPrior;
1757c926afbcSdrh       p->pOrderBy = pOrderBy;
1758a2dc3b1aSdanielk1977       sqlite3ExprDelete(p->pLimit);
1759a2dc3b1aSdanielk1977       p->pLimit = pLimit;
1760a2dc3b1aSdanielk1977       p->pOffset = pOffset;
1761be5fd490Sdrh       p->iLimit = -1;
1762be5fd490Sdrh       p->iOffset = -1;
176384ac9d02Sdanielk1977       if( rc ){
176484ac9d02Sdanielk1977         goto multi_select_end;
176584ac9d02Sdanielk1977       }
176684ac9d02Sdanielk1977 
1767d8bc7086Sdrh 
1768d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1769d8bc7086Sdrh       ** it is that we currently need.
1770d8bc7086Sdrh       */
1771c926afbcSdrh       if( eDest!=priorOp || unionTab!=iParm ){
17726b56344dSdrh         int iCont, iBreak, iStart;
177382c3d636Sdrh         assert( p->pEList );
177441202ccaSdrh         if( eDest==SRT_Callback ){
177592378253Sdrh           Select *pFirst = p;
177692378253Sdrh           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
177792378253Sdrh           generateColumnNames(pParse, 0, pFirst->pEList);
177841202ccaSdrh         }
17794adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
17804adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
1781ec7429aeSdrh         computeLimitRegisters(pParse, p, iBreak);
17824adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
17834adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
178438640e15Sdrh         rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
17850342b1f5Sdrh                              pOrderBy, -1, eDest, iParm,
178684ac9d02Sdanielk1977                              iCont, iBreak, 0);
178784ac9d02Sdanielk1977         if( rc ){
178884ac9d02Sdanielk1977           rc = 1;
178984ac9d02Sdanielk1977           goto multi_select_end;
179084ac9d02Sdanielk1977         }
17914adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
17924adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
17934adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
17944adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
179582c3d636Sdrh       }
179682c3d636Sdrh       break;
179782c3d636Sdrh     }
179882c3d636Sdrh     case TK_INTERSECT: {
179982c3d636Sdrh       int tab1, tab2;
18006b56344dSdrh       int iCont, iBreak, iStart;
1801a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset;
1802dc1bdc4fSdanielk1977       int addr;
180382c3d636Sdrh 
1804d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
18056206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
1806d8bc7086Sdrh       ** by allocating the tables we will need.
1807d8bc7086Sdrh       */
180882c3d636Sdrh       tab1 = pParse->nTab++;
180982c3d636Sdrh       tab2 = pParse->nTab++;
18100342b1f5Sdrh       if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){
181184ac9d02Sdanielk1977         rc = 1;
181284ac9d02Sdanielk1977         goto multi_select_end;
1813d8bc7086Sdrh       }
18140342b1f5Sdrh       createSortingIndex(pParse, p, pOrderBy);
1815dc1bdc4fSdanielk1977 
1816b9bb7c18Sdrh       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab1, 0);
1817b9bb7c18Sdrh       assert( p->addrOpenEphm[0] == -1 );
1818b9bb7c18Sdrh       p->addrOpenEphm[0] = addr;
1819b9bb7c18Sdrh       p->pRightmost->usesEphm = 1;
182084ac9d02Sdanielk1977       assert( p->pEList );
1821d8bc7086Sdrh 
1822d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1823d8bc7086Sdrh       */
1824b3bce662Sdanielk1977       rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
182584ac9d02Sdanielk1977       if( rc ){
182684ac9d02Sdanielk1977         goto multi_select_end;
182784ac9d02Sdanielk1977       }
1828d8bc7086Sdrh 
1829d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1830d8bc7086Sdrh       */
1831b9bb7c18Sdrh       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab2, 0);
1832b9bb7c18Sdrh       assert( p->addrOpenEphm[1] == -1 );
1833b9bb7c18Sdrh       p->addrOpenEphm[1] = addr;
183482c3d636Sdrh       p->pPrior = 0;
1835a2dc3b1aSdanielk1977       pLimit = p->pLimit;
1836a2dc3b1aSdanielk1977       p->pLimit = 0;
1837a2dc3b1aSdanielk1977       pOffset = p->pOffset;
1838a2dc3b1aSdanielk1977       p->pOffset = 0;
1839b3bce662Sdanielk1977       rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
184082c3d636Sdrh       p->pPrior = pPrior;
1841a2dc3b1aSdanielk1977       sqlite3ExprDelete(p->pLimit);
1842a2dc3b1aSdanielk1977       p->pLimit = pLimit;
1843a2dc3b1aSdanielk1977       p->pOffset = pOffset;
184484ac9d02Sdanielk1977       if( rc ){
184584ac9d02Sdanielk1977         goto multi_select_end;
184684ac9d02Sdanielk1977       }
1847d8bc7086Sdrh 
1848d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1849d8bc7086Sdrh       ** tables.
1850d8bc7086Sdrh       */
185182c3d636Sdrh       assert( p->pEList );
185241202ccaSdrh       if( eDest==SRT_Callback ){
185392378253Sdrh         Select *pFirst = p;
185492378253Sdrh         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
185592378253Sdrh         generateColumnNames(pParse, 0, pFirst->pEList);
185641202ccaSdrh       }
18574adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
18584adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
1859ec7429aeSdrh       computeLimitRegisters(pParse, p, iBreak);
18604adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
18614a9f241cSdrh       iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0);
18624adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
186338640e15Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
18640342b1f5Sdrh                              pOrderBy, -1, eDest, iParm,
186584ac9d02Sdanielk1977                              iCont, iBreak, 0);
186684ac9d02Sdanielk1977       if( rc ){
186784ac9d02Sdanielk1977         rc = 1;
186884ac9d02Sdanielk1977         goto multi_select_end;
186984ac9d02Sdanielk1977       }
18704adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
18714adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
18724adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
18734adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
18744adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
187582c3d636Sdrh       break;
187682c3d636Sdrh     }
187782c3d636Sdrh   }
18788cdbf836Sdrh 
18798cdbf836Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
18808cdbf836Sdrh   ** in their result sets.
18818cdbf836Sdrh   */
188282c3d636Sdrh   assert( p->pEList && pPrior->pEList );
188382c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
18844adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
1885da93d238Sdrh       " do not have the same number of result columns", selectOpName(p->op));
188684ac9d02Sdanielk1977     rc = 1;
188784ac9d02Sdanielk1977     goto multi_select_end;
18882282792aSdrh   }
188984ac9d02Sdanielk1977 
18908cdbf836Sdrh   /* Set the number of columns in temporary tables
18918cdbf836Sdrh   */
18928cdbf836Sdrh   nCol = p->pEList->nExpr;
18930342b1f5Sdrh   while( nSetP2 ){
18940342b1f5Sdrh     sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
18958cdbf836Sdrh   }
18968cdbf836Sdrh 
1897fbc4ee7bSdrh   /* Compute collating sequences used by either the ORDER BY clause or
1898fbc4ee7bSdrh   ** by any temporary tables needed to implement the compound select.
1899fbc4ee7bSdrh   ** Attach the KeyInfo structure to all temporary tables.  Invoke the
1900fbc4ee7bSdrh   ** ORDER BY processing if there is an ORDER BY clause.
19018cdbf836Sdrh   **
19028cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
19038cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
19048cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
19058cdbf836Sdrh   ** no temp tables are required.
1906fbc4ee7bSdrh   */
1907b9bb7c18Sdrh   if( pOrderBy || p->usesEphm ){
1908fbc4ee7bSdrh     int i;                        /* Loop counter */
1909fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
19100342b1f5Sdrh     Select *pLoop;                /* For looping through SELECT statements */
19111e31e0b2Sdrh     int nKeyCol;                  /* Number of entries in pKeyInfo->aCol[] */
1912f68d7d17Sdrh     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
1913f68d7d17Sdrh     CollSeq **aCopy;              /* A copy of pKeyInfo->aColl[] */
1914fbc4ee7bSdrh 
19150342b1f5Sdrh     assert( p->pRightmost==p );
19161e31e0b2Sdrh     nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0);
19171e31e0b2Sdrh     pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1));
1918dc1bdc4fSdanielk1977     if( !pKeyInfo ){
1919dc1bdc4fSdanielk1977       rc = SQLITE_NOMEM;
1920dc1bdc4fSdanielk1977       goto multi_select_end;
1921dc1bdc4fSdanielk1977     }
1922dc1bdc4fSdanielk1977 
192314db2665Sdanielk1977     pKeyInfo->enc = ENC(pParse->db);
1924dc1bdc4fSdanielk1977     pKeyInfo->nField = nCol;
1925dc1bdc4fSdanielk1977 
19260342b1f5Sdrh     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
19270342b1f5Sdrh       *apColl = multiSelectCollSeq(pParse, p, i);
19280342b1f5Sdrh       if( 0==*apColl ){
19290342b1f5Sdrh         *apColl = pParse->db->pDfltColl;
1930dc1bdc4fSdanielk1977       }
1931dc1bdc4fSdanielk1977     }
1932dc1bdc4fSdanielk1977 
19330342b1f5Sdrh     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
19340342b1f5Sdrh       for(i=0; i<2; i++){
1935b9bb7c18Sdrh         int addr = pLoop->addrOpenEphm[i];
19360342b1f5Sdrh         if( addr<0 ){
19370342b1f5Sdrh           /* If [0] is unused then [1] is also unused.  So we can
19380342b1f5Sdrh           ** always safely abort as soon as the first unused slot is found */
1939b9bb7c18Sdrh           assert( pLoop->addrOpenEphm[1]<0 );
19400342b1f5Sdrh           break;
19410342b1f5Sdrh         }
19420342b1f5Sdrh         sqlite3VdbeChangeP2(v, addr, nCol);
19430342b1f5Sdrh         sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO);
19440ee5a1e7Sdrh         pLoop->addrOpenEphm[i] = -1;
19450342b1f5Sdrh       }
1946dc1bdc4fSdanielk1977     }
1947dc1bdc4fSdanielk1977 
19480342b1f5Sdrh     if( pOrderBy ){
19490342b1f5Sdrh       struct ExprList_item *pOTerm = pOrderBy->a;
19504efc083fSdrh       int nOrderByExpr = pOrderBy->nExpr;
19510342b1f5Sdrh       int addr;
19524db38a70Sdrh       u8 *pSortOrder;
19530342b1f5Sdrh 
1954f68d7d17Sdrh       /* Reuse the same pKeyInfo for the ORDER BY as was used above for
1955f68d7d17Sdrh       ** the compound select statements.  Except we have to change out the
1956f68d7d17Sdrh       ** pKeyInfo->aColl[] values.  Some of the aColl[] values will be
1957f68d7d17Sdrh       ** reused when constructing the pKeyInfo for the ORDER BY, so make
1958f68d7d17Sdrh       ** a copy.  Sufficient space to hold both the nCol entries for
1959f68d7d17Sdrh       ** the compound select and the nOrderbyExpr entries for the ORDER BY
1960f68d7d17Sdrh       ** was allocated above.  But we need to move the compound select
1961f68d7d17Sdrh       ** entries out of the way before constructing the ORDER BY entries.
1962f68d7d17Sdrh       ** Move the compound select entries into aCopy[] where they can be
1963f68d7d17Sdrh       ** accessed and reused when constructing the ORDER BY entries.
1964f68d7d17Sdrh       ** Because nCol might be greater than or less than nOrderByExpr
1965f68d7d17Sdrh       ** we have to use memmove() when doing the copy.
1966f68d7d17Sdrh       */
19671e31e0b2Sdrh       aCopy = &pKeyInfo->aColl[nOrderByExpr];
19684efc083fSdrh       pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
1969f68d7d17Sdrh       memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
1970f68d7d17Sdrh 
19710342b1f5Sdrh       apColl = pKeyInfo->aColl;
19724efc083fSdrh       for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
19730342b1f5Sdrh         Expr *pExpr = pOTerm->pExpr;
19748b4c40d8Sdrh         if( (pExpr->flags & EP_ExpCollate) ){
19758b4c40d8Sdrh           assert( pExpr->pColl!=0 );
19768b4c40d8Sdrh           *apColl = pExpr->pColl;
197784ac9d02Sdanielk1977         }else{
19780342b1f5Sdrh           *apColl = aCopy[pExpr->iColumn];
197984ac9d02Sdanielk1977         }
19804db38a70Sdrh         *pSortOrder = pOTerm->sortOrder;
198184ac9d02Sdanielk1977       }
19820342b1f5Sdrh       assert( p->pRightmost==p );
1983b9bb7c18Sdrh       assert( p->addrOpenEphm[2]>=0 );
1984b9bb7c18Sdrh       addr = p->addrOpenEphm[2];
19854db38a70Sdrh       sqlite3VdbeChangeP2(v, addr, p->pEList->nExpr+2);
19864efc083fSdrh       pKeyInfo->nField = nOrderByExpr;
19874db38a70Sdrh       sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
19884db38a70Sdrh       pKeyInfo = 0;
1989cdd536f0Sdrh       generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1990dc1bdc4fSdanielk1977     }
1991dc1bdc4fSdanielk1977 
1992dc1bdc4fSdanielk1977     sqliteFree(pKeyInfo);
1993dc1bdc4fSdanielk1977   }
1994dc1bdc4fSdanielk1977 
1995dc1bdc4fSdanielk1977 multi_select_end:
199684ac9d02Sdanielk1977   return rc;
19972282792aSdrh }
1998b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
19992282792aSdrh 
2000b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
20012282792aSdrh /*
2002832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
20036a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
200484e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
20056a3ea0e6Sdrh ** unchanged.)
2006832508b7Sdrh **
2007832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
2008832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
2009832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
2010832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
2011832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
2012832508b7Sdrh ** of the subquery rather the result set of the subquery.
2013832508b7Sdrh */
20146a3ea0e6Sdrh static void substExprList(ExprList*,int,ExprList*);  /* Forward Decl */
2015b3bce662Sdanielk1977 static void substSelect(Select *, int, ExprList *);  /* Forward Decl */
20166a3ea0e6Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
2017832508b7Sdrh   if( pExpr==0 ) return;
201850350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
201950350a15Sdrh     if( pExpr->iColumn<0 ){
202050350a15Sdrh       pExpr->op = TK_NULL;
202150350a15Sdrh     }else{
2022832508b7Sdrh       Expr *pNew;
202384e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
2024832508b7Sdrh       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
2025832508b7Sdrh       pNew = pEList->a[pExpr->iColumn].pExpr;
2026832508b7Sdrh       assert( pNew!=0 );
2027832508b7Sdrh       pExpr->op = pNew->op;
2028d94a6698Sdrh       assert( pExpr->pLeft==0 );
20294adee20fSdanielk1977       pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
2030d94a6698Sdrh       assert( pExpr->pRight==0 );
20314adee20fSdanielk1977       pExpr->pRight = sqlite3ExprDup(pNew->pRight);
2032d94a6698Sdrh       assert( pExpr->pList==0 );
20334adee20fSdanielk1977       pExpr->pList = sqlite3ExprListDup(pNew->pList);
2034832508b7Sdrh       pExpr->iTable = pNew->iTable;
2035fbbe005aSdanielk1977       pExpr->pTab = pNew->pTab;
2036832508b7Sdrh       pExpr->iColumn = pNew->iColumn;
2037832508b7Sdrh       pExpr->iAgg = pNew->iAgg;
20384adee20fSdanielk1977       sqlite3TokenCopy(&pExpr->token, &pNew->token);
20394adee20fSdanielk1977       sqlite3TokenCopy(&pExpr->span, &pNew->span);
2040a1cb183dSdanielk1977       pExpr->pSelect = sqlite3SelectDup(pNew->pSelect);
2041a1cb183dSdanielk1977       pExpr->flags = pNew->flags;
204250350a15Sdrh     }
2043832508b7Sdrh   }else{
20446a3ea0e6Sdrh     substExpr(pExpr->pLeft, iTable, pEList);
20456a3ea0e6Sdrh     substExpr(pExpr->pRight, iTable, pEList);
2046b3bce662Sdanielk1977     substSelect(pExpr->pSelect, iTable, pEList);
20476a3ea0e6Sdrh     substExprList(pExpr->pList, iTable, pEList);
2048832508b7Sdrh   }
2049832508b7Sdrh }
2050b3bce662Sdanielk1977 static void substExprList(ExprList *pList, int iTable, ExprList *pEList){
2051832508b7Sdrh   int i;
2052832508b7Sdrh   if( pList==0 ) return;
2053832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
20546a3ea0e6Sdrh     substExpr(pList->a[i].pExpr, iTable, pEList);
2055832508b7Sdrh   }
2056832508b7Sdrh }
2057b3bce662Sdanielk1977 static void substSelect(Select *p, int iTable, ExprList *pEList){
2058b3bce662Sdanielk1977   if( !p ) return;
2059b3bce662Sdanielk1977   substExprList(p->pEList, iTable, pEList);
2060b3bce662Sdanielk1977   substExprList(p->pGroupBy, iTable, pEList);
2061b3bce662Sdanielk1977   substExprList(p->pOrderBy, iTable, pEList);
2062b3bce662Sdanielk1977   substExpr(p->pHaving, iTable, pEList);
2063b3bce662Sdanielk1977   substExpr(p->pWhere, iTable, pEList);
2064b3bce662Sdanielk1977 }
2065b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_VIEW) */
2066832508b7Sdrh 
2067b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
2068832508b7Sdrh /*
20691350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
20701350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
20711350b030Sdrh ** occurs.
20721350b030Sdrh **
20731350b030Sdrh ** To understand the concept of flattening, consider the following
20741350b030Sdrh ** query:
20751350b030Sdrh **
20761350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
20771350b030Sdrh **
20781350b030Sdrh ** The default way of implementing this query is to execute the
20791350b030Sdrh ** subquery first and store the results in a temporary table, then
20801350b030Sdrh ** run the outer query on that temporary table.  This requires two
20811350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
20821350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
2083832508b7Sdrh ** optimized.
20841350b030Sdrh **
2085832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
20861350b030Sdrh ** a single flat select, like this:
20871350b030Sdrh **
20881350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
20891350b030Sdrh **
20901350b030Sdrh ** The code generated for this simpification gives the same result
2091832508b7Sdrh ** but only has to scan the data once.  And because indices might
2092832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
2093832508b7Sdrh ** avoided.
20941350b030Sdrh **
2095832508b7Sdrh ** Flattening is only attempted if all of the following are true:
20961350b030Sdrh **
2097832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
20981350b030Sdrh **
2099832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
2100832508b7Sdrh **
21018af4d3acSdrh **   (3)  The subquery is not the right operand of a left outer join, or
21028af4d3acSdrh **        the subquery is not itself a join.  (Ticket #306)
2103832508b7Sdrh **
2104832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
2105832508b7Sdrh **
2106832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
2107832508b7Sdrh **        aggregates.
2108832508b7Sdrh **
2109832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
2110832508b7Sdrh **        DISTINCT.
2111832508b7Sdrh **
211208192d5fSdrh **   (7)  The subquery has a FROM clause.
211308192d5fSdrh **
2114df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
2115df199a25Sdrh **
2116df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
2117df199a25Sdrh **        aggregates.
2118df199a25Sdrh **
2119df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
2120df199a25Sdrh **        use LIMIT.
2121df199a25Sdrh **
2122174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
2123174b6195Sdrh **
21243fc673e6Sdrh **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
21253fc673e6Sdrh **        subquery has no WHERE clause.  (added by ticket #350)
21263fc673e6Sdrh **
2127ac83963aSdrh **  (13)  The subquery and outer query do not both use LIMIT
2128ac83963aSdrh **
2129ac83963aSdrh **  (14)  The subquery does not use OFFSET
2130ac83963aSdrh **
2131832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
2132832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
2133832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
2134832508b7Sdrh **
2135665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
2136832508b7Sdrh ** If flattening is attempted this routine returns 1.
2137832508b7Sdrh **
2138832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
2139832508b7Sdrh ** the subquery before this routine runs.
21401350b030Sdrh */
21418c74a8caSdrh static int flattenSubquery(
21428c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
21438c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
21448c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
21458c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
21468c74a8caSdrh ){
21470bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
2148ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
2149ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
21500bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
21516a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
215291bb0eedSdrh   int i;              /* Loop counter */
215391bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
215491bb0eedSdrh   struct SrcList_item *pSubitem;   /* The subquery */
21551350b030Sdrh 
2156832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
2157832508b7Sdrh   */
2158832508b7Sdrh   if( p==0 ) return 0;
2159832508b7Sdrh   pSrc = p->pSrc;
2160ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
216191bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
216291bb0eedSdrh   pSub = pSubitem->pSelect;
2163832508b7Sdrh   assert( pSub!=0 );
2164ac83963aSdrh   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
2165ac83963aSdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
2166832508b7Sdrh   pSubSrc = pSub->pSrc;
2167832508b7Sdrh   assert( pSubSrc );
2168ac83963aSdrh   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
2169ac83963aSdrh   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
2170ac83963aSdrh   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
2171ac83963aSdrh   ** became arbitrary expressions, we were forced to add restrictions (13)
2172ac83963aSdrh   ** and (14). */
2173ac83963aSdrh   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
2174ac83963aSdrh   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
2175ac83963aSdrh   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
2176ac83963aSdrh   if( (pSub->isDistinct || pSub->pLimit)
2177ac83963aSdrh          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
2178df199a25Sdrh      return 0;
2179df199a25Sdrh   }
2180ac83963aSdrh   if( p->isDistinct && subqueryIsAgg ) return 0;         /* Restriction (6)  */
2181ac83963aSdrh   if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){
2182ac83963aSdrh      return 0;                                           /* Restriction (11) */
2183ac83963aSdrh   }
2184832508b7Sdrh 
21858af4d3acSdrh   /* Restriction 3:  If the subquery is a join, make sure the subquery is
21868af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
21878af4d3acSdrh   ** is not allowed:
21888af4d3acSdrh   **
21898af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
21908af4d3acSdrh   **
21918af4d3acSdrh   ** If we flatten the above, we would get
21928af4d3acSdrh   **
21938af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
21948af4d3acSdrh   **
21958af4d3acSdrh   ** which is not at all the same thing.
21968af4d3acSdrh   */
219761dfc31dSdrh   if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){
21988af4d3acSdrh     return 0;
21998af4d3acSdrh   }
22008af4d3acSdrh 
22013fc673e6Sdrh   /* Restriction 12:  If the subquery is the right operand of a left outer
22023fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
22033fc673e6Sdrh   ** An examples of why this is not allowed:
22043fc673e6Sdrh   **
22053fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
22063fc673e6Sdrh   **
22073fc673e6Sdrh   ** If we flatten the above, we would get
22083fc673e6Sdrh   **
22093fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
22103fc673e6Sdrh   **
22113fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
22123fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
22133fc673e6Sdrh   */
221461dfc31dSdrh   if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){
22153fc673e6Sdrh     return 0;
22163fc673e6Sdrh   }
22173fc673e6Sdrh 
22180bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
221963eb5f29Sdrh   ** iFrom-th entry of the FROM clause in the outer query.
2220832508b7Sdrh   */
2221c31c2eb8Sdrh 
2222c31c2eb8Sdrh   /* Move all of the FROM elements of the subquery into the
2223c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
2224c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
2225c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
2226c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
2227c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
2228c31c2eb8Sdrh   ** elements we are now copying in.
2229c31c2eb8Sdrh   */
223091bb0eedSdrh   iParent = pSubitem->iCursor;
2231c31c2eb8Sdrh   {
2232c31c2eb8Sdrh     int nSubSrc = pSubSrc->nSrc;
223391bb0eedSdrh     int jointype = pSubitem->jointype;
2234c31c2eb8Sdrh 
2235a04a34ffSdanielk1977     sqlite3DeleteTable(pSubitem->pTab);
223691bb0eedSdrh     sqliteFree(pSubitem->zDatabase);
223791bb0eedSdrh     sqliteFree(pSubitem->zName);
223891bb0eedSdrh     sqliteFree(pSubitem->zAlias);
2239c31c2eb8Sdrh     if( nSubSrc>1 ){
2240c31c2eb8Sdrh       int extra = nSubSrc - 1;
2241c31c2eb8Sdrh       for(i=1; i<nSubSrc; i++){
22424adee20fSdanielk1977         pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
2243c31c2eb8Sdrh       }
2244c31c2eb8Sdrh       p->pSrc = pSrc;
2245c31c2eb8Sdrh       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2246c31c2eb8Sdrh         pSrc->a[i] = pSrc->a[i-extra];
2247c31c2eb8Sdrh       }
2248c31c2eb8Sdrh     }
2249c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
2250c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
2251c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2252c31c2eb8Sdrh     }
225361dfc31dSdrh     pSrc->a[iFrom].jointype = jointype;
2254c31c2eb8Sdrh   }
2255c31c2eb8Sdrh 
2256c31c2eb8Sdrh   /* Now begin substituting subquery result set expressions for
2257c31c2eb8Sdrh   ** references to the iParent in the outer query.
2258c31c2eb8Sdrh   **
2259c31c2eb8Sdrh   ** Example:
2260c31c2eb8Sdrh   **
2261c31c2eb8Sdrh   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2262c31c2eb8Sdrh   **   \                     \_____________ subquery __________/          /
2263c31c2eb8Sdrh   **    \_____________________ outer query ______________________________/
2264c31c2eb8Sdrh   **
2265c31c2eb8Sdrh   ** We look at every expression in the outer query and every place we see
2266c31c2eb8Sdrh   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2267c31c2eb8Sdrh   */
2268832508b7Sdrh   pList = p->pEList;
2269832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
22706977fea8Sdrh     Expr *pExpr;
22716977fea8Sdrh     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
22722646da7eSdrh       pList->a[i].zName = sqliteStrNDup((char*)pExpr->span.z, pExpr->span.n);
2273832508b7Sdrh     }
2274832508b7Sdrh   }
2275643054c1Sdrh   substExprList(p->pEList, iParent, pSub->pEList);
22761b2e0329Sdrh   if( isAgg ){
22776a3ea0e6Sdrh     substExprList(p->pGroupBy, iParent, pSub->pEList);
22786a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
22791b2e0329Sdrh   }
2280174b6195Sdrh   if( pSub->pOrderBy ){
2281174b6195Sdrh     assert( p->pOrderBy==0 );
2282174b6195Sdrh     p->pOrderBy = pSub->pOrderBy;
2283174b6195Sdrh     pSub->pOrderBy = 0;
2284174b6195Sdrh   }else if( p->pOrderBy ){
22856a3ea0e6Sdrh     substExprList(p->pOrderBy, iParent, pSub->pEList);
2286174b6195Sdrh   }
2287832508b7Sdrh   if( pSub->pWhere ){
22884adee20fSdanielk1977     pWhere = sqlite3ExprDup(pSub->pWhere);
2289832508b7Sdrh   }else{
2290832508b7Sdrh     pWhere = 0;
2291832508b7Sdrh   }
2292832508b7Sdrh   if( subqueryIsAgg ){
2293832508b7Sdrh     assert( p->pHaving==0 );
22941b2e0329Sdrh     p->pHaving = p->pWhere;
22951b2e0329Sdrh     p->pWhere = pWhere;
22966a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
229791bb0eedSdrh     p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
22981b2e0329Sdrh     assert( p->pGroupBy==0 );
22994adee20fSdanielk1977     p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
2300832508b7Sdrh   }else{
23016a3ea0e6Sdrh     substExpr(p->pWhere, iParent, pSub->pEList);
230291bb0eedSdrh     p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
2303832508b7Sdrh   }
2304c31c2eb8Sdrh 
2305c31c2eb8Sdrh   /* The flattened query is distinct if either the inner or the
2306c31c2eb8Sdrh   ** outer query is distinct.
2307c31c2eb8Sdrh   */
2308832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
23098c74a8caSdrh 
2310a58fdfb1Sdanielk1977   /*
2311a58fdfb1Sdanielk1977   ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2312ac83963aSdrh   **
2313ac83963aSdrh   ** One is tempted to try to add a and b to combine the limits.  But this
2314ac83963aSdrh   ** does not work if either limit is negative.
2315a58fdfb1Sdanielk1977   */
2316a2dc3b1aSdanielk1977   if( pSub->pLimit ){
2317a2dc3b1aSdanielk1977     p->pLimit = pSub->pLimit;
2318a2dc3b1aSdanielk1977     pSub->pLimit = 0;
2319df199a25Sdrh   }
23208c74a8caSdrh 
2321c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
2322c31c2eb8Sdrh   ** success.
2323c31c2eb8Sdrh   */
23244adee20fSdanielk1977   sqlite3SelectDelete(pSub);
2325832508b7Sdrh   return 1;
23261350b030Sdrh }
2327b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */
23281350b030Sdrh 
23291350b030Sdrh /*
23309562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it
23319562b551Sdrh ** is a simple min() or max() query.  If it is and this query can be
23329562b551Sdrh ** satisfied using a single seek to the beginning or end of an index,
2333e78e8284Sdrh ** then generate the code for this SELECT and return 1.  If this is not a
23349562b551Sdrh ** simple min() or max() query, then return 0;
23359562b551Sdrh **
23369562b551Sdrh ** A simply min() or max() query looks like this:
23379562b551Sdrh **
23389562b551Sdrh **    SELECT min(a) FROM table;
23399562b551Sdrh **    SELECT max(a) FROM table;
23409562b551Sdrh **
23419562b551Sdrh ** The query may have only a single table in its FROM argument.  There
23429562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
23439562b551Sdrh ** be the min() or max() of a single column of the table.  The column
23449562b551Sdrh ** in the min() or max() function must be indexed.
23459562b551Sdrh **
23464adee20fSdanielk1977 ** The parameters to this routine are the same as for sqlite3Select().
23479562b551Sdrh ** See the header comment on that routine for additional information.
23489562b551Sdrh */
23499562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
23509562b551Sdrh   Expr *pExpr;
23519562b551Sdrh   int iCol;
23529562b551Sdrh   Table *pTab;
23539562b551Sdrh   Index *pIdx;
23549562b551Sdrh   int base;
23559562b551Sdrh   Vdbe *v;
23569562b551Sdrh   int seekOp;
23576e17529eSdrh   ExprList *pEList, *pList, eList;
23589562b551Sdrh   struct ExprList_item eListItem;
23596e17529eSdrh   SrcList *pSrc;
2360ec7429aeSdrh   int brk;
2361da184236Sdanielk1977   int iDb;
23626e17529eSdrh 
23639562b551Sdrh   /* Check to see if this query is a simple min() or max() query.  Return
23649562b551Sdrh   ** zero if it is  not.
23659562b551Sdrh   */
23669562b551Sdrh   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
23676e17529eSdrh   pSrc = p->pSrc;
23686e17529eSdrh   if( pSrc->nSrc!=1 ) return 0;
23696e17529eSdrh   pEList = p->pEList;
23706e17529eSdrh   if( pEList->nExpr!=1 ) return 0;
23716e17529eSdrh   pExpr = pEList->a[0].pExpr;
23729562b551Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
23736e17529eSdrh   pList = pExpr->pList;
23746e17529eSdrh   if( pList==0 || pList->nExpr!=1 ) return 0;
23756977fea8Sdrh   if( pExpr->token.n!=3 ) return 0;
23762646da7eSdrh   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
23770bce8354Sdrh     seekOp = OP_Rewind;
23782646da7eSdrh   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
23790bce8354Sdrh     seekOp = OP_Last;
23800bce8354Sdrh   }else{
23810bce8354Sdrh     return 0;
23820bce8354Sdrh   }
23836e17529eSdrh   pExpr = pList->a[0].pExpr;
23849562b551Sdrh   if( pExpr->op!=TK_COLUMN ) return 0;
23859562b551Sdrh   iCol = pExpr->iColumn;
23866e17529eSdrh   pTab = pSrc->a[0].pTab;
23879562b551Sdrh 
2388a41c7497Sdanielk1977   /* This optimization cannot be used with virtual tables. */
2389a41c7497Sdanielk1977   if( IsVirtual(pTab) ) return 0;
2390c00da105Sdanielk1977 
23919562b551Sdrh   /* If we get to here, it means the query is of the correct form.
239217f71934Sdrh   ** Check to make sure we have an index and make pIdx point to the
239317f71934Sdrh   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
239417f71934Sdrh   ** key column, no index is necessary so set pIdx to NULL.  If no
239517f71934Sdrh   ** usable index is found, return 0.
23969562b551Sdrh   */
23979562b551Sdrh   if( iCol<0 ){
23989562b551Sdrh     pIdx = 0;
23999562b551Sdrh   }else{
2400dc1bdc4fSdanielk1977     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
2401206f3d96Sdrh     if( pColl==0 ) return 0;
24029562b551Sdrh     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
24039562b551Sdrh       assert( pIdx->nColumn>=1 );
2404b3bf556eSdanielk1977       if( pIdx->aiColumn[0]==iCol &&
2405b3bf556eSdanielk1977           0==sqlite3StrICmp(pIdx->azColl[0], pColl->zName) ){
2406b3bf556eSdanielk1977         break;
2407b3bf556eSdanielk1977       }
24089562b551Sdrh     }
24099562b551Sdrh     if( pIdx==0 ) return 0;
24109562b551Sdrh   }
24119562b551Sdrh 
2412e5f50722Sdrh   /* Identify column types if we will be using the callback.  This
24139562b551Sdrh   ** step is skipped if the output is going to a table or a memory cell.
2414e5f50722Sdrh   ** The column names have already been generated in the calling function.
24159562b551Sdrh   */
24164adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
24179562b551Sdrh   if( v==0 ) return 0;
24189562b551Sdrh 
24190c37e630Sdrh   /* If the output is destined for a temporary table, open that table.
24200c37e630Sdrh   */
2421b9bb7c18Sdrh   if( eDest==SRT_EphemTab ){
2422b9bb7c18Sdrh     sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 1);
24230c37e630Sdrh   }
24240c37e630Sdrh 
242517f71934Sdrh   /* Generating code to find the min or the max.  Basically all we have
242617f71934Sdrh   ** to do is find the first or the last entry in the chosen index.  If
242717f71934Sdrh   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
242817f71934Sdrh   ** or last entry in the main table.
24299562b551Sdrh   */
2430da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2431b9bb7c18Sdrh   assert( iDb>=0 || pTab->isEphem );
2432da184236Sdanielk1977   sqlite3CodeVerifySchema(pParse, iDb);
2433c00da105Sdanielk1977   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
24346e17529eSdrh   base = pSrc->a[0].iCursor;
2435ec7429aeSdrh   brk = sqlite3VdbeMakeLabel(v);
2436ec7429aeSdrh   computeLimitRegisters(pParse, p, brk);
24376e17529eSdrh   if( pSrc->a[0].pSelect==0 ){
2438c00da105Sdanielk1977     sqlite3OpenTable(pParse, base, iDb, pTab, OP_OpenRead);
24396e17529eSdrh   }
24409562b551Sdrh   if( pIdx==0 ){
24414adee20fSdanielk1977     sqlite3VdbeAddOp(v, seekOp, base, 0);
24429562b551Sdrh   }else{
24433719d7f9Sdanielk1977     /* Even though the cursor used to open the index here is closed
24443719d7f9Sdanielk1977     ** as soon as a single value has been read from it, allocate it
24453719d7f9Sdanielk1977     ** using (pParse->nTab++) to prevent the cursor id from being
24463719d7f9Sdanielk1977     ** reused. This is important for statements of the form
24473719d7f9Sdanielk1977     ** "INSERT INTO x SELECT max() FROM x".
24483719d7f9Sdanielk1977     */
24493719d7f9Sdanielk1977     int iIdx;
2450b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
24513719d7f9Sdanielk1977     iIdx = pParse->nTab++;
2452da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
2453da184236Sdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
24543719d7f9Sdanielk1977     sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
2455b3bf556eSdanielk1977         (char*)pKey, P3_KEYINFO_HANDOFF);
24569eb516c0Sdrh     if( seekOp==OP_Rewind ){
2457f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
24581af3fdb4Sdrh       sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
24591af3fdb4Sdrh       seekOp = OP_MoveGt;
24609eb516c0Sdrh     }
24613719d7f9Sdanielk1977     sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
2462f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
24633719d7f9Sdanielk1977     sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
24647cf6e4deSdrh     sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
24659562b551Sdrh   }
24665cf8e8c7Sdrh   eList.nExpr = 1;
24675cf8e8c7Sdrh   memset(&eListItem, 0, sizeof(eListItem));
24685cf8e8c7Sdrh   eList.a = &eListItem;
24695cf8e8c7Sdrh   eList.a[0].pExpr = pExpr;
2470ec7429aeSdrh   selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0);
2471ec7429aeSdrh   sqlite3VdbeResolveLabel(v, brk);
24724adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Close, base, 0);
24736e17529eSdrh 
24749562b551Sdrh   return 1;
24759562b551Sdrh }
24769562b551Sdrh 
24779562b551Sdrh /*
2478290c1948Sdrh ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement.  Return
2479290c1948Sdrh ** the number of errors seen.
2480290c1948Sdrh **
2481290c1948Sdrh ** An ORDER BY or GROUP BY is a list of expressions.  If any expression
2482290c1948Sdrh ** is an integer constant, then that expression is replaced by the
2483290c1948Sdrh ** corresponding entry in the result set.
2484290c1948Sdrh */
2485290c1948Sdrh static int processOrderGroupBy(
2486b3bce662Sdanielk1977   NameContext *pNC,     /* Name context of the SELECT statement. */
2487290c1948Sdrh   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
2488290c1948Sdrh   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
2489290c1948Sdrh ){
2490290c1948Sdrh   int i;
2491b3bce662Sdanielk1977   ExprList *pEList = pNC->pEList;     /* The result set of the SELECT */
2492b3bce662Sdanielk1977   Parse *pParse = pNC->pParse;     /* The result set of the SELECT */
2493b3bce662Sdanielk1977   assert( pEList );
2494b3bce662Sdanielk1977 
2495290c1948Sdrh   if( pOrderBy==0 ) return 0;
2496290c1948Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
2497290c1948Sdrh     int iCol;
2498290c1948Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
2499b3bce662Sdanielk1977     if( sqlite3ExprIsInteger(pE, &iCol) ){
2500b3bce662Sdanielk1977       if( iCol>0 && iCol<=pEList->nExpr ){
25018b4c40d8Sdrh         CollSeq *pColl = pE->pColl;
25028b4c40d8Sdrh         int flags = pE->flags & EP_ExpCollate;
2503290c1948Sdrh         sqlite3ExprDelete(pE);
2504290c1948Sdrh         pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
25058b4c40d8Sdrh         if( pColl && flags ){
25068b4c40d8Sdrh           pE->pColl = pColl;
25078b4c40d8Sdrh           pE->flags |= flags;
25088b4c40d8Sdrh         }
2509b3bce662Sdanielk1977       }else{
2510290c1948Sdrh         sqlite3ErrorMsg(pParse,
2511290c1948Sdrh            "%s BY column number %d out of range - should be "
2512290c1948Sdrh            "between 1 and %d", zType, iCol, pEList->nExpr);
2513290c1948Sdrh         return 1;
2514290c1948Sdrh       }
2515290c1948Sdrh     }
2516b3bce662Sdanielk1977     if( sqlite3ExprResolveNames(pNC, pE) ){
2517b3bce662Sdanielk1977       return 1;
2518b3bce662Sdanielk1977     }
2519290c1948Sdrh   }
2520290c1948Sdrh   return 0;
2521290c1948Sdrh }
2522290c1948Sdrh 
2523290c1948Sdrh /*
2524b3bce662Sdanielk1977 ** This routine resolves any names used in the result set of the
2525b3bce662Sdanielk1977 ** supplied SELECT statement. If the SELECT statement being resolved
2526b3bce662Sdanielk1977 ** is a sub-select, then pOuterNC is a pointer to the NameContext
2527b3bce662Sdanielk1977 ** of the parent SELECT.
2528b3bce662Sdanielk1977 */
2529b3bce662Sdanielk1977 int sqlite3SelectResolve(
2530b3bce662Sdanielk1977   Parse *pParse,         /* The parser context */
2531b3bce662Sdanielk1977   Select *p,             /* The SELECT statement being coded. */
2532b3bce662Sdanielk1977   NameContext *pOuterNC  /* The outer name context. May be NULL. */
2533b3bce662Sdanielk1977 ){
2534b3bce662Sdanielk1977   ExprList *pEList;          /* Result set. */
2535b3bce662Sdanielk1977   int i;                     /* For-loop variable used in multiple places */
2536b3bce662Sdanielk1977   NameContext sNC;           /* Local name-context */
253713449892Sdrh   ExprList *pGroupBy;        /* The group by clause */
2538b3bce662Sdanielk1977 
2539b3bce662Sdanielk1977   /* If this routine has run before, return immediately. */
2540b3bce662Sdanielk1977   if( p->isResolved ){
2541b3bce662Sdanielk1977     assert( !pOuterNC );
2542b3bce662Sdanielk1977     return SQLITE_OK;
2543b3bce662Sdanielk1977   }
2544b3bce662Sdanielk1977   p->isResolved = 1;
2545b3bce662Sdanielk1977 
2546b3bce662Sdanielk1977   /* If there have already been errors, do nothing. */
2547b3bce662Sdanielk1977   if( pParse->nErr>0 ){
2548b3bce662Sdanielk1977     return SQLITE_ERROR;
2549b3bce662Sdanielk1977   }
2550b3bce662Sdanielk1977 
2551b3bce662Sdanielk1977   /* Prepare the select statement. This call will allocate all cursors
2552b3bce662Sdanielk1977   ** required to handle the tables and subqueries in the FROM clause.
2553b3bce662Sdanielk1977   */
2554b3bce662Sdanielk1977   if( prepSelectStmt(pParse, p) ){
2555b3bce662Sdanielk1977     return SQLITE_ERROR;
2556b3bce662Sdanielk1977   }
2557b3bce662Sdanielk1977 
2558a2dc3b1aSdanielk1977   /* Resolve the expressions in the LIMIT and OFFSET clauses. These
2559a2dc3b1aSdanielk1977   ** are not allowed to refer to any names, so pass an empty NameContext.
2560a2dc3b1aSdanielk1977   */
2561ffe07b2dSdrh   memset(&sNC, 0, sizeof(sNC));
2562b3bce662Sdanielk1977   sNC.pParse = pParse;
2563a2dc3b1aSdanielk1977   if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2564a2dc3b1aSdanielk1977       sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2565a2dc3b1aSdanielk1977     return SQLITE_ERROR;
2566a2dc3b1aSdanielk1977   }
2567a2dc3b1aSdanielk1977 
2568a2dc3b1aSdanielk1977   /* Set up the local name-context to pass to ExprResolveNames() to
2569a2dc3b1aSdanielk1977   ** resolve the expression-list.
2570a2dc3b1aSdanielk1977   */
2571a2dc3b1aSdanielk1977   sNC.allowAgg = 1;
2572a2dc3b1aSdanielk1977   sNC.pSrcList = p->pSrc;
2573a2dc3b1aSdanielk1977   sNC.pNext = pOuterNC;
2574b3bce662Sdanielk1977 
2575b3bce662Sdanielk1977   /* Resolve names in the result set. */
2576b3bce662Sdanielk1977   pEList = p->pEList;
2577b3bce662Sdanielk1977   if( !pEList ) return SQLITE_ERROR;
2578b3bce662Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
2579b3bce662Sdanielk1977     Expr *pX = pEList->a[i].pExpr;
2580b3bce662Sdanielk1977     if( sqlite3ExprResolveNames(&sNC, pX) ){
2581b3bce662Sdanielk1977       return SQLITE_ERROR;
2582b3bce662Sdanielk1977     }
2583b3bce662Sdanielk1977   }
2584b3bce662Sdanielk1977 
2585b3bce662Sdanielk1977   /* If there are no aggregate functions in the result-set, and no GROUP BY
2586b3bce662Sdanielk1977   ** expression, do not allow aggregates in any of the other expressions.
2587b3bce662Sdanielk1977   */
2588b3bce662Sdanielk1977   assert( !p->isAgg );
258913449892Sdrh   pGroupBy = p->pGroupBy;
259013449892Sdrh   if( pGroupBy || sNC.hasAgg ){
2591b3bce662Sdanielk1977     p->isAgg = 1;
2592b3bce662Sdanielk1977   }else{
2593b3bce662Sdanielk1977     sNC.allowAgg = 0;
2594b3bce662Sdanielk1977   }
2595b3bce662Sdanielk1977 
2596b3bce662Sdanielk1977   /* If a HAVING clause is present, then there must be a GROUP BY clause.
2597b3bce662Sdanielk1977   */
259813449892Sdrh   if( p->pHaving && !pGroupBy ){
2599b3bce662Sdanielk1977     sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2600b3bce662Sdanielk1977     return SQLITE_ERROR;
2601b3bce662Sdanielk1977   }
2602b3bce662Sdanielk1977 
2603b3bce662Sdanielk1977   /* Add the expression list to the name-context before parsing the
2604b3bce662Sdanielk1977   ** other expressions in the SELECT statement. This is so that
2605b3bce662Sdanielk1977   ** expressions in the WHERE clause (etc.) can refer to expressions by
2606b3bce662Sdanielk1977   ** aliases in the result set.
2607b3bce662Sdanielk1977   **
2608b3bce662Sdanielk1977   ** Minor point: If this is the case, then the expression will be
2609b3bce662Sdanielk1977   ** re-evaluated for each reference to it.
2610b3bce662Sdanielk1977   */
2611b3bce662Sdanielk1977   sNC.pEList = p->pEList;
2612b3bce662Sdanielk1977   if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2613994c80afSdrh      sqlite3ExprResolveNames(&sNC, p->pHaving) ){
2614b3bce662Sdanielk1977     return SQLITE_ERROR;
2615b3bce662Sdanielk1977   }
2616994c80afSdrh   if( p->pPrior==0 ){
2617994c80afSdrh     if( processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
2618994c80afSdrh         processOrderGroupBy(&sNC, pGroupBy, "GROUP") ){
2619994c80afSdrh       return SQLITE_ERROR;
2620994c80afSdrh     }
2621994c80afSdrh   }
2622b3bce662Sdanielk1977 
262313449892Sdrh   /* Make sure the GROUP BY clause does not contain aggregate functions.
262413449892Sdrh   */
262513449892Sdrh   if( pGroupBy ){
262613449892Sdrh     struct ExprList_item *pItem;
262713449892Sdrh 
262813449892Sdrh     for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
262913449892Sdrh       if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
263013449892Sdrh         sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
263113449892Sdrh             "the GROUP BY clause");
263213449892Sdrh         return SQLITE_ERROR;
263313449892Sdrh       }
263413449892Sdrh     }
263513449892Sdrh   }
263613449892Sdrh 
2637f6bbe022Sdrh   /* If this is one SELECT of a compound, be sure to resolve names
2638f6bbe022Sdrh   ** in the other SELECTs.
2639f6bbe022Sdrh   */
2640f6bbe022Sdrh   if( p->pPrior ){
2641f6bbe022Sdrh     return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC);
2642f6bbe022Sdrh   }else{
2643b3bce662Sdanielk1977     return SQLITE_OK;
2644b3bce662Sdanielk1977   }
2645f6bbe022Sdrh }
2646b3bce662Sdanielk1977 
2647b3bce662Sdanielk1977 /*
264813449892Sdrh ** Reset the aggregate accumulator.
264913449892Sdrh **
265013449892Sdrh ** The aggregate accumulator is a set of memory cells that hold
265113449892Sdrh ** intermediate results while calculating an aggregate.  This
265213449892Sdrh ** routine simply stores NULLs in all of those memory cells.
2653b3bce662Sdanielk1977 */
265413449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
265513449892Sdrh   Vdbe *v = pParse->pVdbe;
265613449892Sdrh   int i;
2657c99130fdSdrh   struct AggInfo_func *pFunc;
265813449892Sdrh   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
265913449892Sdrh     return;
266013449892Sdrh   }
266113449892Sdrh   for(i=0; i<pAggInfo->nColumn; i++){
2662d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0);
266313449892Sdrh   }
2664c99130fdSdrh   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
2665d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0);
2666c99130fdSdrh     if( pFunc->iDistinct>=0 ){
2667c99130fdSdrh       Expr *pE = pFunc->pExpr;
2668c99130fdSdrh       if( pE->pList==0 || pE->pList->nExpr!=1 ){
2669c99130fdSdrh         sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
2670c99130fdSdrh            "by an expression");
2671c99130fdSdrh         pFunc->iDistinct = -1;
2672c99130fdSdrh       }else{
2673c99130fdSdrh         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
2674b9bb7c18Sdrh         sqlite3VdbeOp3(v, OP_OpenEphemeral, pFunc->iDistinct, 0,
2675c99130fdSdrh                           (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
2676c99130fdSdrh       }
2677c99130fdSdrh     }
267813449892Sdrh   }
2679b3bce662Sdanielk1977 }
2680b3bce662Sdanielk1977 
2681b3bce662Sdanielk1977 /*
268213449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function
268313449892Sdrh ** in the AggInfo structure.
2684b3bce662Sdanielk1977 */
268513449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
268613449892Sdrh   Vdbe *v = pParse->pVdbe;
268713449892Sdrh   int i;
268813449892Sdrh   struct AggInfo_func *pF;
268913449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
2690a10a34b8Sdrh     ExprList *pList = pF->pExpr->pList;
2691a10a34b8Sdrh     sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0,
2692a10a34b8Sdrh                       (void*)pF->pFunc, P3_FUNCDEF);
2693b3bce662Sdanielk1977   }
269413449892Sdrh }
269513449892Sdrh 
269613449892Sdrh /*
269713449892Sdrh ** Update the accumulator memory cells for an aggregate based on
269813449892Sdrh ** the current cursor position.
269913449892Sdrh */
270013449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
270113449892Sdrh   Vdbe *v = pParse->pVdbe;
270213449892Sdrh   int i;
270313449892Sdrh   struct AggInfo_func *pF;
270413449892Sdrh   struct AggInfo_col *pC;
270513449892Sdrh 
270613449892Sdrh   pAggInfo->directMode = 1;
270713449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
270813449892Sdrh     int nArg;
2709c99130fdSdrh     int addrNext = 0;
271013449892Sdrh     ExprList *pList = pF->pExpr->pList;
271113449892Sdrh     if( pList ){
271213449892Sdrh       nArg = pList->nExpr;
271313449892Sdrh       sqlite3ExprCodeExprList(pParse, pList);
271413449892Sdrh     }else{
271513449892Sdrh       nArg = 0;
271613449892Sdrh     }
2717c99130fdSdrh     if( pF->iDistinct>=0 ){
2718c99130fdSdrh       addrNext = sqlite3VdbeMakeLabel(v);
2719c99130fdSdrh       assert( nArg==1 );
2720f8875400Sdrh       codeDistinct(v, pF->iDistinct, addrNext, 1);
2721c99130fdSdrh     }
272213449892Sdrh     if( pF->pFunc->needCollSeq ){
272313449892Sdrh       CollSeq *pColl = 0;
272413449892Sdrh       struct ExprList_item *pItem;
272513449892Sdrh       int j;
272643617e9aSdrh       assert( pList!=0 );  /* pList!=0 if pF->pFunc->needCollSeq is true */
272743617e9aSdrh       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
272813449892Sdrh         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
272913449892Sdrh       }
273013449892Sdrh       if( !pColl ){
273113449892Sdrh         pColl = pParse->db->pDfltColl;
273213449892Sdrh       }
273313449892Sdrh       sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
273413449892Sdrh     }
273513449892Sdrh     sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF);
2736c99130fdSdrh     if( addrNext ){
2737c99130fdSdrh       sqlite3VdbeResolveLabel(v, addrNext);
2738c99130fdSdrh     }
273913449892Sdrh   }
274013449892Sdrh   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
27415774b806Sdrh     sqlite3ExprCode(pParse, pC->pExpr);
274213449892Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1);
274313449892Sdrh   }
274413449892Sdrh   pAggInfo->directMode = 0;
274513449892Sdrh }
274613449892Sdrh 
2747b3bce662Sdanielk1977 
2748b3bce662Sdanielk1977 /*
27499bb61fe7Sdrh ** Generate code for the given SELECT statement.
27509bb61fe7Sdrh **
2751fef5208cSdrh ** The results are distributed in various ways depending on the
2752fef5208cSdrh ** value of eDest and iParm.
2753fef5208cSdrh **
2754fef5208cSdrh **     eDest Value       Result
2755fef5208cSdrh **     ------------    -------------------------------------------
2756fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
2757fef5208cSdrh **
2758fef5208cSdrh **     SRT_Mem         Store first result in memory cell iParm
2759fef5208cSdrh **
2760e014a838Sdanielk1977 **     SRT_Set         Store results as keys of table iParm.
2761fef5208cSdrh **
276282c3d636Sdrh **     SRT_Union       Store results as a key in a temporary table iParm
276382c3d636Sdrh **
27644b11c6d3Sjplyon **     SRT_Except      Remove results from the temporary table iParm.
2765c4a3c779Sdrh **
2766c4a3c779Sdrh **     SRT_Table       Store results in temporary table iParm
27679bb61fe7Sdrh **
2768e78e8284Sdrh ** The table above is incomplete.  Additional eDist value have be added
2769e78e8284Sdrh ** since this comment was written.  See the selectInnerLoop() function for
2770e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings.
2771e78e8284Sdrh **
27729bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
27739bb61fe7Sdrh ** encountered, then an appropriate error message is left in
27749bb61fe7Sdrh ** pParse->zErrMsg.
27759bb61fe7Sdrh **
27769bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
27779bb61fe7Sdrh ** calling function needs to do that.
27781b2e0329Sdrh **
27791b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
27801b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
27811b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
27821b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
27831b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
27841b2e0329Sdrh ** can be changed.
2785e78e8284Sdrh **
2786e78e8284Sdrh ** Example 1:   The meaning of the pParent parameter.
2787e78e8284Sdrh **
2788e78e8284Sdrh **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2789e78e8284Sdrh **    \                      \_______ subquery _______/        /
2790e78e8284Sdrh **     \                                                      /
2791e78e8284Sdrh **      \____________________ outer query ___________________/
2792e78e8284Sdrh **
2793e78e8284Sdrh ** This routine is called for the outer query first.   For that call,
2794e78e8284Sdrh ** pParent will be NULL.  During the processing of the outer query, this
2795e78e8284Sdrh ** routine is called recursively to handle the subquery.  For the recursive
2796e78e8284Sdrh ** call, pParent will point to the outer query.  Because the subquery is
2797e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will
2798e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.)
27999bb61fe7Sdrh */
28004adee20fSdanielk1977 int sqlite3Select(
2801cce7d176Sdrh   Parse *pParse,         /* The parser context */
28029bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
2803e78e8284Sdrh   int eDest,             /* How to dispose of the results */
2804e78e8284Sdrh   int iParm,             /* A parameter used by the eDest disposal method */
2805832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
2806832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
280784ac9d02Sdanielk1977   int *pParentAgg,       /* True if pParent uses aggregate functions */
2808b3bce662Sdanielk1977   char *aff              /* If eDest is SRT_Union, the affinity string */
2809cce7d176Sdrh ){
281013449892Sdrh   int i, j;              /* Loop counters */
281113449892Sdrh   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
281213449892Sdrh   Vdbe *v;               /* The virtual machine under construction */
2813b3bce662Sdanielk1977   int isAgg;             /* True for select lists like "count(*)" */
2814a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
2815ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
28169bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
28179bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
28182282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
28192282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
282019a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
282119a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
28221d83f052Sdrh   int rc = 1;            /* Value to return from this function */
2823b9bb7c18Sdrh   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
282413449892Sdrh   AggInfo sAggInfo;      /* Information used by aggregate queries */
2825ec7429aeSdrh   int iEnd;              /* Address of the end of the query */
28269bb61fe7Sdrh 
28279e12800dSdanielk1977   if( p==0 || sqlite3MallocFailed() || pParse->nErr ){
28286f7adc8aSdrh     return 1;
28296f7adc8aSdrh   }
28304adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
283113449892Sdrh   memset(&sAggInfo, 0, sizeof(sAggInfo));
2832daffd0e5Sdrh 
2833b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
283482c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
283582c3d636Sdrh   */
283682c3d636Sdrh   if( p->pPrior ){
28370342b1f5Sdrh     if( p->pRightmost==0 ){
28380342b1f5Sdrh       Select *pLoop;
28390342b1f5Sdrh       for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
28400342b1f5Sdrh         pLoop->pRightmost = p;
28410342b1f5Sdrh       }
28420342b1f5Sdrh     }
284384ac9d02Sdanielk1977     return multiSelect(pParse, p, eDest, iParm, aff);
284482c3d636Sdrh   }
2845b7f9164eSdrh #endif
284682c3d636Sdrh 
2847b3bce662Sdanielk1977   pOrderBy = p->pOrderBy;
284813449892Sdrh   if( IgnorableOrderby(eDest) ){
2849b3bce662Sdanielk1977     p->pOrderBy = 0;
2850b3bce662Sdanielk1977   }
2851b3bce662Sdanielk1977   if( sqlite3SelectResolve(pParse, p, 0) ){
2852b3bce662Sdanielk1977     goto select_end;
2853b3bce662Sdanielk1977   }
2854b3bce662Sdanielk1977   p->pOrderBy = pOrderBy;
2855b3bce662Sdanielk1977 
285682c3d636Sdrh   /* Make local copies of the parameters for this query.
285782c3d636Sdrh   */
28589bb61fe7Sdrh   pTabList = p->pSrc;
28599bb61fe7Sdrh   pWhere = p->pWhere;
28602282792aSdrh   pGroupBy = p->pGroupBy;
28612282792aSdrh   pHaving = p->pHaving;
2862b3bce662Sdanielk1977   isAgg = p->isAgg;
286319a775c2Sdrh   isDistinct = p->isDistinct;
2864b3bce662Sdanielk1977   pEList = p->pEList;
2865b3bce662Sdanielk1977   if( pEList==0 ) goto select_end;
28669bb61fe7Sdrh 
28679bb61fe7Sdrh   /*
28689bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
28699bb61fe7Sdrh   ** errors before this routine starts.
28709bb61fe7Sdrh   */
28711d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
2872cce7d176Sdrh 
28732282792aSdrh   /* If writing to memory or generating a set
28742282792aSdrh   ** only a single column may be output.
287519a775c2Sdrh   */
287693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
2877fef5208cSdrh   if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
28784adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "only a single result allowed for "
2879da93d238Sdrh        "a SELECT that is part of an expression");
28801d83f052Sdrh     goto select_end;
288119a775c2Sdrh   }
288293758c8dSdanielk1977 #endif
288319a775c2Sdrh 
2884c926afbcSdrh   /* ORDER BY is ignored for some destinations.
28852282792aSdrh   */
288613449892Sdrh   if( IgnorableOrderby(eDest) ){
2887acd4c695Sdrh     pOrderBy = 0;
28882282792aSdrh   }
28892282792aSdrh 
2890d820cb1bSdrh   /* Begin generating code.
2891d820cb1bSdrh   */
28924adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
2893d820cb1bSdrh   if( v==0 ) goto select_end;
2894d820cb1bSdrh 
2895d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
2896d820cb1bSdrh   */
289751522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
2898ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
2899742f947bSdanielk1977     const char *zSavedAuthContext = 0;
2900c31c2eb8Sdrh     int needRestoreContext;
290113449892Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
2902c31c2eb8Sdrh 
29031787ccabSdanielk1977     if( pItem->pSelect==0 || pItem->isPopulated ) continue;
290413449892Sdrh     if( pItem->zName!=0 ){
29055cf590c1Sdrh       zSavedAuthContext = pParse->zAuthContext;
290613449892Sdrh       pParse->zAuthContext = pItem->zName;
2907c31c2eb8Sdrh       needRestoreContext = 1;
2908c31c2eb8Sdrh     }else{
2909c31c2eb8Sdrh       needRestoreContext = 0;
29105cf590c1Sdrh     }
2911b9bb7c18Sdrh     sqlite3Select(pParse, pItem->pSelect, SRT_EphemTab,
291213449892Sdrh                  pItem->iCursor, p, i, &isAgg, 0);
2913c31c2eb8Sdrh     if( needRestoreContext ){
29145cf590c1Sdrh       pParse->zAuthContext = zSavedAuthContext;
29155cf590c1Sdrh     }
2916832508b7Sdrh     pTabList = p->pSrc;
2917832508b7Sdrh     pWhere = p->pWhere;
291813449892Sdrh     if( !IgnorableOrderby(eDest) ){
2919832508b7Sdrh       pOrderBy = p->pOrderBy;
2920acd4c695Sdrh     }
2921832508b7Sdrh     pGroupBy = p->pGroupBy;
2922832508b7Sdrh     pHaving = p->pHaving;
2923832508b7Sdrh     isDistinct = p->isDistinct;
29241b2e0329Sdrh   }
292551522cd3Sdrh #endif
29261b2e0329Sdrh 
29276e17529eSdrh   /* Check for the special case of a min() or max() function by itself
29286e17529eSdrh   ** in the result set.
29296e17529eSdrh   */
29306e17529eSdrh   if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
29316e17529eSdrh     rc = 0;
29326e17529eSdrh     goto select_end;
29336e17529eSdrh   }
29346e17529eSdrh 
29351b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
29361b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
29371b2e0329Sdrh   */
2938b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
29391b2e0329Sdrh   if( pParent && pParentAgg &&
294074161705Sdrh       flattenSubquery(pParent, parentTab, *pParentAgg, isAgg) ){
29411b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
2942b3bce662Sdanielk1977     goto select_end;
29431b2e0329Sdrh   }
2944b7f9164eSdrh #endif
2945832508b7Sdrh 
29468b4c40d8Sdrh   /* If there is an ORDER BY clause, then this sorting
29478b4c40d8Sdrh   ** index might end up being unused if the data can be
29489d2985c7Sdrh   ** extracted in pre-sorted order.  If that is the case, then the
2949b9bb7c18Sdrh   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
29509d2985c7Sdrh   ** we figure out that the sorting index is not needed.  The addrSortIndex
29519d2985c7Sdrh   ** variable is used to facilitate that change.
29527cedc8d4Sdanielk1977   */
29537cedc8d4Sdanielk1977   if( pOrderBy ){
29540342b1f5Sdrh     KeyInfo *pKeyInfo;
29557cedc8d4Sdanielk1977     if( pParse->nErr ){
29567cedc8d4Sdanielk1977       goto select_end;
29577cedc8d4Sdanielk1977     }
29580342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
29599d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
2960b9bb7c18Sdrh     p->addrOpenEphm[2] = addrSortIndex =
29611e31e0b2Sdrh       sqlite3VdbeOp3(v, OP_OpenEphemeral, pOrderBy->iECursor, pOrderBy->nExpr+2,                     (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
29629d2985c7Sdrh   }else{
29639d2985c7Sdrh     addrSortIndex = -1;
29647cedc8d4Sdanielk1977   }
29657cedc8d4Sdanielk1977 
29662d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
29672d0794e3Sdrh   */
2968b9bb7c18Sdrh   if( eDest==SRT_EphemTab ){
2969b9bb7c18Sdrh     sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, pEList->nExpr);
29702d0794e3Sdrh   }
29712d0794e3Sdrh 
2972f42bacc2Sdrh   /* Set the limiter.
2973f42bacc2Sdrh   */
2974f42bacc2Sdrh   iEnd = sqlite3VdbeMakeLabel(v);
2975f42bacc2Sdrh   computeLimitRegisters(pParse, p, iEnd);
2976f42bacc2Sdrh 
2977dece1a84Sdrh   /* Open a virtual index to use for the distinct set.
2978cce7d176Sdrh   */
297919a775c2Sdrh   if( isDistinct ){
29800342b1f5Sdrh     KeyInfo *pKeyInfo;
2981832508b7Sdrh     distinct = pParse->nTab++;
29820342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
2983b9bb7c18Sdrh     sqlite3VdbeOp3(v, OP_OpenEphemeral, distinct, 0,
29840342b1f5Sdrh                         (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
2985832508b7Sdrh   }else{
2986832508b7Sdrh     distinct = -1;
2987efb7251dSdrh   }
2988832508b7Sdrh 
298913449892Sdrh   /* Aggregate and non-aggregate queries are handled differently */
299013449892Sdrh   if( !isAgg && pGroupBy==0 ){
299113449892Sdrh     /* This case is for non-aggregate queries
299213449892Sdrh     ** Begin the database scan
2993832508b7Sdrh     */
299413449892Sdrh     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy);
29951d83f052Sdrh     if( pWInfo==0 ) goto select_end;
2996cce7d176Sdrh 
2997b9bb7c18Sdrh     /* If sorting index that was created by a prior OP_OpenEphemeral
2998b9bb7c18Sdrh     ** instruction ended up not being needed, then change the OP_OpenEphemeral
29999d2985c7Sdrh     ** into an OP_Noop.
30009d2985c7Sdrh     */
30019d2985c7Sdrh     if( addrSortIndex>=0 && pOrderBy==0 ){
3002f8875400Sdrh       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
3003b9bb7c18Sdrh       p->addrOpenEphm[2] = -1;
30049d2985c7Sdrh     }
30059d2985c7Sdrh 
300613449892Sdrh     /* Use the standard inner loop
3007cce7d176Sdrh     */
3008df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
300984ac9d02Sdanielk1977                     iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
30101d83f052Sdrh        goto select_end;
3011cce7d176Sdrh     }
30122282792aSdrh 
3013cce7d176Sdrh     /* End the database scan loop.
3014cce7d176Sdrh     */
30154adee20fSdanielk1977     sqlite3WhereEnd(pWInfo);
301613449892Sdrh   }else{
301713449892Sdrh     /* This is the processing for aggregate queries */
301813449892Sdrh     NameContext sNC;    /* Name context for processing aggregate information */
301913449892Sdrh     int iAMem;          /* First Mem address for storing current GROUP BY */
302013449892Sdrh     int iBMem;          /* First Mem address for previous GROUP BY */
302113449892Sdrh     int iUseFlag;       /* Mem address holding flag indicating that at least
302213449892Sdrh                         ** one row of the input to the aggregator has been
302313449892Sdrh                         ** processed */
302413449892Sdrh     int iAbortFlag;     /* Mem address which causes query abort if positive */
302513449892Sdrh     int groupBySort;    /* Rows come from source in GROUP BY order */
3026cce7d176Sdrh 
302713449892Sdrh 
302813449892Sdrh     /* The following variables hold addresses or labels for parts of the
302913449892Sdrh     ** virtual machine program we are putting together */
303013449892Sdrh     int addrOutputRow;      /* Start of subroutine that outputs a result row */
303113449892Sdrh     int addrSetAbort;       /* Set the abort flag and return */
303213449892Sdrh     int addrInitializeLoop; /* Start of code that initializes the input loop */
303313449892Sdrh     int addrTopOfLoop;      /* Top of the input loop */
303413449892Sdrh     int addrGroupByChange;  /* Code that runs when any GROUP BY term changes */
303513449892Sdrh     int addrProcessRow;     /* Code to process a single input row */
303613449892Sdrh     int addrEnd;            /* End of all processing */
3037b9bb7c18Sdrh     int addrSortingIdx;     /* The OP_OpenEphemeral for the sorting index */
3038e313382eSdrh     int addrReset;          /* Subroutine for resetting the accumulator */
303913449892Sdrh 
304013449892Sdrh     addrEnd = sqlite3VdbeMakeLabel(v);
304113449892Sdrh 
304213449892Sdrh     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
304313449892Sdrh     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
304413449892Sdrh     ** SELECT statement.
30452282792aSdrh     */
304613449892Sdrh     memset(&sNC, 0, sizeof(sNC));
304713449892Sdrh     sNC.pParse = pParse;
304813449892Sdrh     sNC.pSrcList = pTabList;
304913449892Sdrh     sNC.pAggInfo = &sAggInfo;
305013449892Sdrh     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
30519d2985c7Sdrh     sAggInfo.pGroupBy = pGroupBy;
305213449892Sdrh     if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){
30531d83f052Sdrh       goto select_end;
30542282792aSdrh     }
305513449892Sdrh     if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){
305613449892Sdrh       goto select_end;
30572282792aSdrh     }
305813449892Sdrh     if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
305913449892Sdrh       goto select_end;
306013449892Sdrh     }
306113449892Sdrh     sAggInfo.nAccumulator = sAggInfo.nColumn;
306213449892Sdrh     for(i=0; i<sAggInfo.nFunc; i++){
306313449892Sdrh       if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
306413449892Sdrh         goto select_end;
306513449892Sdrh       }
306613449892Sdrh     }
30679e12800dSdanielk1977     if( sqlite3MallocFailed() ) goto select_end;
306813449892Sdrh 
306913449892Sdrh     /* Processing for aggregates with GROUP BY is very different and
307013449892Sdrh     ** much more complex tha aggregates without a GROUP BY.
307113449892Sdrh     */
307213449892Sdrh     if( pGroupBy ){
307313449892Sdrh       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
307413449892Sdrh 
307513449892Sdrh       /* Create labels that we will be needing
307613449892Sdrh       */
307713449892Sdrh 
307813449892Sdrh       addrInitializeLoop = sqlite3VdbeMakeLabel(v);
307913449892Sdrh       addrGroupByChange = sqlite3VdbeMakeLabel(v);
308013449892Sdrh       addrProcessRow = sqlite3VdbeMakeLabel(v);
308113449892Sdrh 
308213449892Sdrh       /* If there is a GROUP BY clause we might need a sorting index to
308313449892Sdrh       ** implement it.  Allocate that sorting index now.  If it turns out
3084b9bb7c18Sdrh       ** that we do not need it after all, the OpenEphemeral instruction
308513449892Sdrh       ** will be converted into a Noop.
308613449892Sdrh       */
308713449892Sdrh       sAggInfo.sortingIdx = pParse->nTab++;
308813449892Sdrh       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
308913449892Sdrh       addrSortingIdx =
3090b9bb7c18Sdrh           sqlite3VdbeOp3(v, OP_OpenEphemeral, sAggInfo.sortingIdx,
309113449892Sdrh                          sAggInfo.nSortingColumn,
309213449892Sdrh                          (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
309313449892Sdrh 
309413449892Sdrh       /* Initialize memory locations used by GROUP BY aggregate processing
309513449892Sdrh       */
309613449892Sdrh       iUseFlag = pParse->nMem++;
309713449892Sdrh       iAbortFlag = pParse->nMem++;
309813449892Sdrh       iAMem = pParse->nMem;
309913449892Sdrh       pParse->nMem += pGroupBy->nExpr;
310013449892Sdrh       iBMem = pParse->nMem;
310113449892Sdrh       pParse->nMem += pGroupBy->nExpr;
3102d654be80Sdrh       sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag);
3103de29e3e9Sdrh       VdbeComment((v, "# clear abort flag"));
3104d654be80Sdrh       sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag);
3105de29e3e9Sdrh       VdbeComment((v, "# indicate accumulator empty"));
310613449892Sdrh       sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop);
310713449892Sdrh 
310813449892Sdrh       /* Generate a subroutine that outputs a single row of the result
310913449892Sdrh       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
311013449892Sdrh       ** is less than or equal to zero, the subroutine is a no-op.  If
311113449892Sdrh       ** the processing calls for the query to abort, this subroutine
311213449892Sdrh       ** increments the iAbortFlag memory location before returning in
311313449892Sdrh       ** order to signal the caller to abort.
311413449892Sdrh       */
311513449892Sdrh       addrSetAbort = sqlite3VdbeCurrentAddr(v);
3116de29e3e9Sdrh       sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag);
3117de29e3e9Sdrh       VdbeComment((v, "# set abort flag"));
311813449892Sdrh       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
311913449892Sdrh       addrOutputRow = sqlite3VdbeCurrentAddr(v);
312013449892Sdrh       sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2);
3121de29e3e9Sdrh       VdbeComment((v, "# Groupby result generator entry point"));
312213449892Sdrh       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
312313449892Sdrh       finalizeAggFunctions(pParse, &sAggInfo);
312413449892Sdrh       if( pHaving ){
312513449892Sdrh         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1);
312613449892Sdrh       }
312713449892Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
312813449892Sdrh                            distinct, eDest, iParm,
312913449892Sdrh                            addrOutputRow+1, addrSetAbort, aff);
313013449892Sdrh       if( rc ){
313113449892Sdrh         goto select_end;
313213449892Sdrh       }
313313449892Sdrh       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
3134de29e3e9Sdrh       VdbeComment((v, "# end groupby result generator"));
313513449892Sdrh 
3136e313382eSdrh       /* Generate a subroutine that will reset the group-by accumulator
3137e313382eSdrh       */
3138e313382eSdrh       addrReset = sqlite3VdbeCurrentAddr(v);
3139e313382eSdrh       resetAccumulator(pParse, &sAggInfo);
3140e313382eSdrh       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
3141e313382eSdrh 
314213449892Sdrh       /* Begin a loop that will extract all source rows in GROUP BY order.
314313449892Sdrh       ** This might involve two separate loops with an OP_Sort in between, or
314413449892Sdrh       ** it might be a single loop that uses an index to extract information
314513449892Sdrh       ** in the right order to begin with.
314613449892Sdrh       */
314713449892Sdrh       sqlite3VdbeResolveLabel(v, addrInitializeLoop);
3148e313382eSdrh       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
314913449892Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy);
31505360ad34Sdrh       if( pWInfo==0 ) goto select_end;
315113449892Sdrh       if( pGroupBy==0 ){
315213449892Sdrh         /* The optimizer is able to deliver rows in group by order so
3153b9bb7c18Sdrh         ** we do not have to sort.  The OP_OpenEphemeral table will be
315413449892Sdrh         ** cancelled later because we still need to use the pKeyInfo
315513449892Sdrh         */
315613449892Sdrh         pGroupBy = p->pGroupBy;
315713449892Sdrh         groupBySort = 0;
315813449892Sdrh       }else{
315913449892Sdrh         /* Rows are coming out in undetermined order.  We have to push
316013449892Sdrh         ** each row into a sorting index, terminate the first loop,
316113449892Sdrh         ** then loop over the sorting index in order to get the output
316213449892Sdrh         ** in sorted order
316313449892Sdrh         */
316413449892Sdrh         groupBySort = 1;
316513449892Sdrh         sqlite3ExprCodeExprList(pParse, pGroupBy);
316613449892Sdrh         sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0);
316713449892Sdrh         j = pGroupBy->nExpr+1;
316813449892Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
316913449892Sdrh           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
317013449892Sdrh           if( pCol->iSorterColumn<j ) continue;
3171945498f3Sdrh           sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn, pCol->iTable);
317213449892Sdrh           j++;
317313449892Sdrh         }
317413449892Sdrh         sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0);
317513449892Sdrh         sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0);
317613449892Sdrh         sqlite3WhereEnd(pWInfo);
317797571957Sdrh         sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
3178de29e3e9Sdrh         VdbeComment((v, "# GROUP BY sort"));
317913449892Sdrh         sAggInfo.useSortingIdx = 1;
318013449892Sdrh       }
318113449892Sdrh 
318213449892Sdrh       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
318313449892Sdrh       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
318413449892Sdrh       ** Then compare the current GROUP BY terms against the GROUP BY terms
318513449892Sdrh       ** from the previous row currently stored in a0, a1, a2...
318613449892Sdrh       */
318713449892Sdrh       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
318813449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
318913449892Sdrh         if( groupBySort ){
319013449892Sdrh           sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j);
319113449892Sdrh         }else{
319213449892Sdrh           sAggInfo.directMode = 1;
319313449892Sdrh           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr);
319413449892Sdrh         }
319513449892Sdrh         sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1);
319613449892Sdrh       }
319713449892Sdrh       for(j=pGroupBy->nExpr-1; j>=0; j--){
319813449892Sdrh         if( j<pGroupBy->nExpr-1 ){
319913449892Sdrh           sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0);
320013449892Sdrh         }
320113449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0);
320213449892Sdrh         if( j==0 ){
3203e313382eSdrh           sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow);
320413449892Sdrh         }else{
32054f686238Sdrh           sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange);
320613449892Sdrh         }
320713449892Sdrh         sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ);
320813449892Sdrh       }
320913449892Sdrh 
321013449892Sdrh       /* Generate code that runs whenever the GROUP BY changes.
321113449892Sdrh       ** Change in the GROUP BY are detected by the previous code
321213449892Sdrh       ** block.  If there were no changes, this block is skipped.
321313449892Sdrh       **
321413449892Sdrh       ** This code copies current group by terms in b0,b1,b2,...
321513449892Sdrh       ** over to a0,a1,a2.  It then calls the output subroutine
321613449892Sdrh       ** and resets the aggregate accumulator registers in preparation
321713449892Sdrh       ** for the next GROUP BY batch.
321813449892Sdrh       */
321913449892Sdrh       sqlite3VdbeResolveLabel(v, addrGroupByChange);
322013449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
3221d654be80Sdrh         sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j);
322213449892Sdrh       }
322313449892Sdrh       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
3224de29e3e9Sdrh       VdbeComment((v, "# output one row"));
322513449892Sdrh       sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd);
3226de29e3e9Sdrh       VdbeComment((v, "# check abort flag"));
3227e313382eSdrh       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
3228de29e3e9Sdrh       VdbeComment((v, "# reset accumulator"));
322913449892Sdrh 
323013449892Sdrh       /* Update the aggregate accumulators based on the content of
323113449892Sdrh       ** the current row
323213449892Sdrh       */
323313449892Sdrh       sqlite3VdbeResolveLabel(v, addrProcessRow);
323413449892Sdrh       updateAccumulator(pParse, &sAggInfo);
3235de29e3e9Sdrh       sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag);
3236de29e3e9Sdrh       VdbeComment((v, "# indicate data in accumulator"));
323713449892Sdrh 
323813449892Sdrh       /* End of the loop
323913449892Sdrh       */
324013449892Sdrh       if( groupBySort ){
324113449892Sdrh         sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
324213449892Sdrh       }else{
324313449892Sdrh         sqlite3WhereEnd(pWInfo);
3244f8875400Sdrh         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
324513449892Sdrh       }
324613449892Sdrh 
324713449892Sdrh       /* Output the final row of result
324813449892Sdrh       */
324913449892Sdrh       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
3250de29e3e9Sdrh       VdbeComment((v, "# output final row"));
325113449892Sdrh 
325213449892Sdrh     } /* endif pGroupBy */
325313449892Sdrh     else {
325413449892Sdrh       /* This case runs if the aggregate has no GROUP BY clause.  The
325513449892Sdrh       ** processing is much simpler since there is only a single row
325613449892Sdrh       ** of output.
325713449892Sdrh       */
325813449892Sdrh       resetAccumulator(pParse, &sAggInfo);
325913449892Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
32605360ad34Sdrh       if( pWInfo==0 ) goto select_end;
326113449892Sdrh       updateAccumulator(pParse, &sAggInfo);
326213449892Sdrh       sqlite3WhereEnd(pWInfo);
326313449892Sdrh       finalizeAggFunctions(pParse, &sAggInfo);
326413449892Sdrh       pOrderBy = 0;
32655774b806Sdrh       if( pHaving ){
32665774b806Sdrh         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1);
32675774b806Sdrh       }
326813449892Sdrh       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
326913449892Sdrh                       eDest, iParm, addrEnd, addrEnd, aff);
327013449892Sdrh     }
327113449892Sdrh     sqlite3VdbeResolveLabel(v, addrEnd);
327213449892Sdrh 
327313449892Sdrh   } /* endif aggregate query */
32742282792aSdrh 
3275cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
3276cce7d176Sdrh   ** and send them to the callback one by one.
3277cce7d176Sdrh   */
3278cce7d176Sdrh   if( pOrderBy ){
3279cdd536f0Sdrh     generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
3280cce7d176Sdrh   }
32816a535340Sdrh 
328293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
3283f620b4e2Sdrh   /* If this was a subquery, we have now converted the subquery into a
32841787ccabSdanielk1977   ** temporary table.  So set the SrcList_item.isPopulated flag to prevent
32851787ccabSdanielk1977   ** this subquery from being evaluated again and to force the use of
32861787ccabSdanielk1977   ** the temporary table.
3287f620b4e2Sdrh   */
3288f620b4e2Sdrh   if( pParent ){
3289f620b4e2Sdrh     assert( pParent->pSrc->nSrc>parentTab );
3290f620b4e2Sdrh     assert( pParent->pSrc->a[parentTab].pSelect==p );
32911787ccabSdanielk1977     pParent->pSrc->a[parentTab].isPopulated = 1;
3292f620b4e2Sdrh   }
329393758c8dSdanielk1977 #endif
3294f620b4e2Sdrh 
3295ec7429aeSdrh   /* Jump here to skip this query
3296ec7429aeSdrh   */
3297ec7429aeSdrh   sqlite3VdbeResolveLabel(v, iEnd);
3298ec7429aeSdrh 
32991d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
33001d83f052Sdrh   ** to indicate no errors.
33011d83f052Sdrh   */
33021d83f052Sdrh   rc = 0;
33031d83f052Sdrh 
33041d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
33051d83f052Sdrh   ** successful coding of the SELECT.
33061d83f052Sdrh   */
33071d83f052Sdrh select_end:
3308955de52cSdanielk1977 
3309955de52cSdanielk1977   /* Identify column names if we will be using them in a callback.  This
3310955de52cSdanielk1977   ** step is skipped if the output is going to some other destination.
3311955de52cSdanielk1977   */
3312955de52cSdanielk1977   if( rc==SQLITE_OK && eDest==SRT_Callback ){
3313955de52cSdanielk1977     generateColumnNames(pParse, pTabList, pEList);
3314955de52cSdanielk1977   }
3315955de52cSdanielk1977 
331613449892Sdrh   sqliteFree(sAggInfo.aCol);
331713449892Sdrh   sqliteFree(sAggInfo.aFunc);
33181d83f052Sdrh   return rc;
3319cce7d176Sdrh }
3320485f0039Sdrh 
332177a2a5e7Sdrh #if defined(SQLITE_DEBUG)
3322485f0039Sdrh /*
3323485f0039Sdrh *******************************************************************************
3324485f0039Sdrh ** The following code is used for testing and debugging only.  The code
3325485f0039Sdrh ** that follows does not appear in normal builds.
3326485f0039Sdrh **
3327485f0039Sdrh ** These routines are used to print out the content of all or part of a
3328485f0039Sdrh ** parse structures such as Select or Expr.  Such printouts are useful
3329485f0039Sdrh ** for helping to understand what is happening inside the code generator
3330485f0039Sdrh ** during the execution of complex SELECT statements.
3331485f0039Sdrh **
3332485f0039Sdrh ** These routine are not called anywhere from within the normal
3333485f0039Sdrh ** code base.  Then are intended to be called from within the debugger
3334485f0039Sdrh ** or from temporary "printf" statements inserted for debugging.
3335485f0039Sdrh */
3336485f0039Sdrh void sqlite3PrintExpr(Expr *p){
3337485f0039Sdrh   if( p->token.z && p->token.n>0 ){
3338485f0039Sdrh     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
3339485f0039Sdrh   }else{
3340485f0039Sdrh     sqlite3DebugPrintf("(%d", p->op);
3341485f0039Sdrh   }
3342485f0039Sdrh   if( p->pLeft ){
3343485f0039Sdrh     sqlite3DebugPrintf(" ");
3344485f0039Sdrh     sqlite3PrintExpr(p->pLeft);
3345485f0039Sdrh   }
3346485f0039Sdrh   if( p->pRight ){
3347485f0039Sdrh     sqlite3DebugPrintf(" ");
3348485f0039Sdrh     sqlite3PrintExpr(p->pRight);
3349485f0039Sdrh   }
3350485f0039Sdrh   sqlite3DebugPrintf(")");
3351485f0039Sdrh }
3352485f0039Sdrh void sqlite3PrintExprList(ExprList *pList){
3353485f0039Sdrh   int i;
3354485f0039Sdrh   for(i=0; i<pList->nExpr; i++){
3355485f0039Sdrh     sqlite3PrintExpr(pList->a[i].pExpr);
3356485f0039Sdrh     if( i<pList->nExpr-1 ){
3357485f0039Sdrh       sqlite3DebugPrintf(", ");
3358485f0039Sdrh     }
3359485f0039Sdrh   }
3360485f0039Sdrh }
3361485f0039Sdrh void sqlite3PrintSelect(Select *p, int indent){
3362485f0039Sdrh   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
3363485f0039Sdrh   sqlite3PrintExprList(p->pEList);
3364485f0039Sdrh   sqlite3DebugPrintf("\n");
3365485f0039Sdrh   if( p->pSrc ){
3366485f0039Sdrh     char *zPrefix;
3367485f0039Sdrh     int i;
3368485f0039Sdrh     zPrefix = "FROM";
3369485f0039Sdrh     for(i=0; i<p->pSrc->nSrc; i++){
3370485f0039Sdrh       struct SrcList_item *pItem = &p->pSrc->a[i];
3371485f0039Sdrh       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
3372485f0039Sdrh       zPrefix = "";
3373485f0039Sdrh       if( pItem->pSelect ){
3374485f0039Sdrh         sqlite3DebugPrintf("(\n");
3375485f0039Sdrh         sqlite3PrintSelect(pItem->pSelect, indent+10);
3376485f0039Sdrh         sqlite3DebugPrintf("%*s)", indent+8, "");
3377485f0039Sdrh       }else if( pItem->zName ){
3378485f0039Sdrh         sqlite3DebugPrintf("%s", pItem->zName);
3379485f0039Sdrh       }
3380485f0039Sdrh       if( pItem->pTab ){
3381485f0039Sdrh         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
3382485f0039Sdrh       }
3383485f0039Sdrh       if( pItem->zAlias ){
3384485f0039Sdrh         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
3385485f0039Sdrh       }
3386485f0039Sdrh       if( i<p->pSrc->nSrc-1 ){
3387485f0039Sdrh         sqlite3DebugPrintf(",");
3388485f0039Sdrh       }
3389485f0039Sdrh       sqlite3DebugPrintf("\n");
3390485f0039Sdrh     }
3391485f0039Sdrh   }
3392485f0039Sdrh   if( p->pWhere ){
3393485f0039Sdrh     sqlite3DebugPrintf("%*s WHERE ", indent, "");
3394485f0039Sdrh     sqlite3PrintExpr(p->pWhere);
3395485f0039Sdrh     sqlite3DebugPrintf("\n");
3396485f0039Sdrh   }
3397485f0039Sdrh   if( p->pGroupBy ){
3398485f0039Sdrh     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
3399485f0039Sdrh     sqlite3PrintExprList(p->pGroupBy);
3400485f0039Sdrh     sqlite3DebugPrintf("\n");
3401485f0039Sdrh   }
3402485f0039Sdrh   if( p->pHaving ){
3403485f0039Sdrh     sqlite3DebugPrintf("%*s HAVING ", indent, "");
3404485f0039Sdrh     sqlite3PrintExpr(p->pHaving);
3405485f0039Sdrh     sqlite3DebugPrintf("\n");
3406485f0039Sdrh   }
3407485f0039Sdrh   if( p->pOrderBy ){
3408485f0039Sdrh     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
3409485f0039Sdrh     sqlite3PrintExprList(p->pOrderBy);
3410485f0039Sdrh     sqlite3DebugPrintf("\n");
3411485f0039Sdrh   }
3412485f0039Sdrh }
3413485f0039Sdrh /* End of the structure debug printing code
3414485f0039Sdrh *****************************************************************************/
3415485f0039Sdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
3416