xref: /sqlite-3.40.0/src/select.c (revision fa2bb6da)
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*fa2bb6daSdanielk1977 ** $Id: select.c,v 1.347 2007/05/14 15:49:44 danielk1977 Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19315555caSdrh 
20cce7d176Sdrh /*
21eda639e1Sdrh ** Delete all the content of a Select structure but do not deallocate
22eda639e1Sdrh ** the select structure itself.
23eda639e1Sdrh */
24f0113000Sdanielk1977 static void clearSelect(Select *p){
25eda639e1Sdrh   sqlite3ExprListDelete(p->pEList);
26eda639e1Sdrh   sqlite3SrcListDelete(p->pSrc);
27eda639e1Sdrh   sqlite3ExprDelete(p->pWhere);
28eda639e1Sdrh   sqlite3ExprListDelete(p->pGroupBy);
29eda639e1Sdrh   sqlite3ExprDelete(p->pHaving);
30eda639e1Sdrh   sqlite3ExprListDelete(p->pOrderBy);
31eda639e1Sdrh   sqlite3SelectDelete(p->pPrior);
32eda639e1Sdrh   sqlite3ExprDelete(p->pLimit);
33eda639e1Sdrh   sqlite3ExprDelete(p->pOffset);
34eda639e1Sdrh }
35eda639e1Sdrh 
36eda639e1Sdrh 
37eda639e1Sdrh /*
389bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that
399bb61fe7Sdrh ** structure.
40cce7d176Sdrh */
414adee20fSdanielk1977 Select *sqlite3SelectNew(
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 
437e305f43fSdrh /*
438e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression
439e305f43fSdrh ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
440e305f43fSdrh ** column.  We do this in a subroutine because the error occurs in multiple
441e305f43fSdrh ** places.
442e305f43fSdrh */
443e305f43fSdrh static int checkForMultiColumnSelectError(Parse *pParse, int eDest, int nExpr){
444e305f43fSdrh   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
445e305f43fSdrh     sqlite3ErrorMsg(pParse, "only a single result allowed for "
446e305f43fSdrh        "a SELECT that is part of an expression");
447e305f43fSdrh     return 1;
448e305f43fSdrh   }else{
449e305f43fSdrh     return 0;
450e305f43fSdrh   }
451e305f43fSdrh }
452c99130fdSdrh 
453c99130fdSdrh /*
4542282792aSdrh ** This routine generates the code for the inside of the inner loop
4552282792aSdrh ** of a SELECT.
45682c3d636Sdrh **
45738640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
45838640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
45938640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
46038640e15Sdrh ** datatypes for each column.
4612282792aSdrh */
4622282792aSdrh static int selectInnerLoop(
4632282792aSdrh   Parse *pParse,          /* The parser context */
464df199a25Sdrh   Select *p,              /* The complete select statement being coded */
4652282792aSdrh   ExprList *pEList,       /* List of values being extracted */
46682c3d636Sdrh   int srcTab,             /* Pull data from this table */
467967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
4682282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
4692282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
4702282792aSdrh   int eDest,              /* How to dispose of the results */
4712282792aSdrh   int iParm,              /* An argument to the disposal method */
4722282792aSdrh   int iContinue,          /* Jump here to continue with next row */
47384ac9d02Sdanielk1977   int iBreak,             /* Jump here to break out of the inner loop */
47484ac9d02Sdanielk1977   char *aff               /* affinity string if eDest is SRT_Union */
4752282792aSdrh ){
4762282792aSdrh   Vdbe *v = pParse->pVdbe;
4772282792aSdrh   int i;
478ea48eb2eSdrh   int hasDistinct;        /* True if the DISTINCT keyword is present */
47938640e15Sdrh 
480daffd0e5Sdrh   if( v==0 ) return 0;
48138640e15Sdrh   assert( pEList!=0 );
4822282792aSdrh 
483df199a25Sdrh   /* If there was a LIMIT clause on the SELECT statement, then do the check
484df199a25Sdrh   ** to see if this row should be output.
485df199a25Sdrh   */
486eda639e1Sdrh   hasDistinct = distinct>=0 && pEList->nExpr>0;
487ea48eb2eSdrh   if( pOrderBy==0 && !hasDistinct ){
488ec7429aeSdrh     codeOffset(v, p, iContinue, 0);
489df199a25Sdrh   }
490df199a25Sdrh 
491967e8b73Sdrh   /* Pull the requested columns.
4922282792aSdrh   */
49338640e15Sdrh   if( nColumn>0 ){
494967e8b73Sdrh     for(i=0; i<nColumn; i++){
4954adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
49682c3d636Sdrh     }
49738640e15Sdrh   }else{
49838640e15Sdrh     nColumn = pEList->nExpr;
499c182d163Sdrh     sqlite3ExprCodeExprList(pParse, pEList);
50082c3d636Sdrh   }
5012282792aSdrh 
502daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
503daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
504daffd0e5Sdrh   ** part of the result.
5052282792aSdrh   */
506ea48eb2eSdrh   if( hasDistinct ){
507f8875400Sdrh     assert( pEList!=0 );
508f8875400Sdrh     assert( pEList->nExpr==nColumn );
509f8875400Sdrh     codeDistinct(v, distinct, iContinue, nColumn);
510ea48eb2eSdrh     if( pOrderBy==0 ){
511ec7429aeSdrh       codeOffset(v, p, iContinue, nColumn);
512ea48eb2eSdrh     }
5132282792aSdrh   }
51482c3d636Sdrh 
515e305f43fSdrh   if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){
516e305f43fSdrh     return 0;
517e305f43fSdrh   }
518e305f43fSdrh 
519c926afbcSdrh   switch( eDest ){
52082c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
52182c3d636Sdrh     ** table iParm.
5222282792aSdrh     */
52313449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
524c926afbcSdrh     case SRT_Union: {
525f8875400Sdrh       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
52613449892Sdrh       if( aff ){
52784ac9d02Sdanielk1977         sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
52813449892Sdrh       }
529f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0);
530c926afbcSdrh       break;
531c926afbcSdrh     }
53282c3d636Sdrh 
53382c3d636Sdrh     /* Construct a record from the query result, but instead of
53482c3d636Sdrh     ** saving that record, use it as a key to delete elements from
53582c3d636Sdrh     ** the temporary table iParm.
53682c3d636Sdrh     */
537c926afbcSdrh     case SRT_Except: {
5380bd1f4eaSdrh       int addr;
539f8875400Sdrh       addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
54084ac9d02Sdanielk1977       sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
5414adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
5424adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
543c926afbcSdrh       break;
544c926afbcSdrh     }
5455338a5f7Sdanielk1977 #endif
5465338a5f7Sdanielk1977 
5475338a5f7Sdanielk1977     /* Store the result as data using a unique key.
5485338a5f7Sdanielk1977     */
5495338a5f7Sdanielk1977     case SRT_Table:
550b9bb7c18Sdrh     case SRT_EphemTab: {
5515338a5f7Sdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
5525338a5f7Sdanielk1977       if( pOrderBy ){
553d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
5545338a5f7Sdanielk1977       }else{
555f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
5565338a5f7Sdanielk1977         sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
557e4d90813Sdrh         sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
5585338a5f7Sdanielk1977       }
5595338a5f7Sdanielk1977       break;
5605338a5f7Sdanielk1977     }
5612282792aSdrh 
56293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
5632282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
5642282792aSdrh     ** then there should be a single item on the stack.  Write this
5652282792aSdrh     ** item into the set table with bogus data.
5662282792aSdrh     */
567c926afbcSdrh     case SRT_Set: {
5684adee20fSdanielk1977       int addr1 = sqlite3VdbeCurrentAddr(v);
56952b36cabSdrh       int addr2;
570e014a838Sdanielk1977 
571967e8b73Sdrh       assert( nColumn==1 );
5724adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
5734adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
5744adee20fSdanielk1977       addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
5756c1426fdSdrh       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr,(iParm>>16)&0xff);
576c926afbcSdrh       if( pOrderBy ){
577de941c60Sdrh         /* At first glance you would think we could optimize out the
578de941c60Sdrh         ** ORDER BY in this case since the order of entries in the set
579de941c60Sdrh         ** does not matter.  But there might be a LIMIT clause, in which
580de941c60Sdrh         ** case the order does matter */
581d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
582c926afbcSdrh       }else{
5836c1426fdSdrh         sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
584f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
585c926afbcSdrh       }
586d654be80Sdrh       sqlite3VdbeJumpHere(v, addr2);
587c926afbcSdrh       break;
588c926afbcSdrh     }
58982c3d636Sdrh 
590504b6989Sdrh     /* If any row exist in the result set, record that fact and abort.
591ec7429aeSdrh     */
592ec7429aeSdrh     case SRT_Exists: {
593ec7429aeSdrh       sqlite3VdbeAddOp(v, OP_MemInt, 1, iParm);
594ec7429aeSdrh       sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
595ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
596ec7429aeSdrh       break;
597ec7429aeSdrh     }
598ec7429aeSdrh 
5992282792aSdrh     /* If this is a scalar select that is part of an expression, then
6002282792aSdrh     ** store the results in the appropriate memory cell and break out
6012282792aSdrh     ** of the scan loop.
6022282792aSdrh     */
603c926afbcSdrh     case SRT_Mem: {
604967e8b73Sdrh       assert( nColumn==1 );
605c926afbcSdrh       if( pOrderBy ){
606d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
607c926afbcSdrh       }else{
6084adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
609ec7429aeSdrh         /* The LIMIT clause will jump out of the loop for us */
610c926afbcSdrh       }
611c926afbcSdrh       break;
612c926afbcSdrh     }
61393758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
6142282792aSdrh 
615c182d163Sdrh     /* Send the data to the callback function or to a subroutine.  In the
616c182d163Sdrh     ** case of a subroutine, the subroutine itself is responsible for
617c182d163Sdrh     ** popping the data from the stack.
618f46f905aSdrh     */
619c182d163Sdrh     case SRT_Subroutine:
6209d2985c7Sdrh     case SRT_Callback: {
621f46f905aSdrh       if( pOrderBy ){
622ce665cf6Sdrh         sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
623d59ba6ceSdrh         pushOntoSorter(pParse, pOrderBy, p);
624c182d163Sdrh       }else if( eDest==SRT_Subroutine ){
6254adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
626c182d163Sdrh       }else{
627c182d163Sdrh         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
628ac82fcf5Sdrh       }
629142e30dfSdrh       break;
630142e30dfSdrh     }
631142e30dfSdrh 
6326a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER)
633d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
634d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
635d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
636d7489c39Sdrh     ** about the actual results of the select.
637d7489c39Sdrh     */
638c926afbcSdrh     default: {
639f46f905aSdrh       assert( eDest==SRT_Discard );
6404adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
641c926afbcSdrh       break;
642c926afbcSdrh     }
64393758c8dSdanielk1977 #endif
644c926afbcSdrh   }
645ec7429aeSdrh 
646ec7429aeSdrh   /* Jump to the end of the loop if the LIMIT is reached.
647ec7429aeSdrh   */
648ec7429aeSdrh   if( p->iLimit>=0 && pOrderBy==0 ){
64915007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
650ec7429aeSdrh     sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, iBreak);
651ec7429aeSdrh   }
65282c3d636Sdrh   return 0;
65382c3d636Sdrh }
65482c3d636Sdrh 
65582c3d636Sdrh /*
656dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records
657dece1a84Sdrh ** the collating sequence for each expression in that expression list.
658dece1a84Sdrh **
6590342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
6600342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to
6610342b1f5Sdrh ** implement that clause.  If the ExprList is the result set of a SELECT
6620342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual
6630342b1f5Sdrh ** index to implement a DISTINCT test.
6640342b1f5Sdrh **
665dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
666dece1a84Sdrh ** function is responsible for seeing that this structure is eventually
667dece1a84Sdrh ** freed.  Add the KeyInfo structure to the P3 field of an opcode using
668dece1a84Sdrh ** P3_KEYINFO_HANDOFF is the usual way of dealing with this.
669dece1a84Sdrh */
670dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
671dece1a84Sdrh   sqlite3 *db = pParse->db;
672dece1a84Sdrh   int nExpr;
673dece1a84Sdrh   KeyInfo *pInfo;
674dece1a84Sdrh   struct ExprList_item *pItem;
675dece1a84Sdrh   int i;
676dece1a84Sdrh 
677dece1a84Sdrh   nExpr = pList->nExpr;
678dece1a84Sdrh   pInfo = sqliteMalloc( sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
679dece1a84Sdrh   if( pInfo ){
6802646da7eSdrh     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
681dece1a84Sdrh     pInfo->nField = nExpr;
68214db2665Sdanielk1977     pInfo->enc = ENC(db);
683dece1a84Sdrh     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
684dece1a84Sdrh       CollSeq *pColl;
685dece1a84Sdrh       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
686dece1a84Sdrh       if( !pColl ){
687dece1a84Sdrh         pColl = db->pDfltColl;
688dece1a84Sdrh       }
689dece1a84Sdrh       pInfo->aColl[i] = pColl;
690dece1a84Sdrh       pInfo->aSortOrder[i] = pItem->sortOrder;
691dece1a84Sdrh     }
692dece1a84Sdrh   }
693dece1a84Sdrh   return pInfo;
694dece1a84Sdrh }
695dece1a84Sdrh 
696dece1a84Sdrh 
697dece1a84Sdrh /*
698d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
699d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
700d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
701d8bc7086Sdrh ** routine generates the code needed to do that.
702d8bc7086Sdrh */
703c926afbcSdrh static void generateSortTail(
704cdd536f0Sdrh   Parse *pParse,   /* Parsing context */
705c926afbcSdrh   Select *p,       /* The SELECT statement */
706c926afbcSdrh   Vdbe *v,         /* Generate code into this VDBE */
707c926afbcSdrh   int nColumn,     /* Number of columns of data */
708c926afbcSdrh   int eDest,       /* Write the sorted results here */
709c926afbcSdrh   int iParm        /* Optional parameter associated with eDest */
710c926afbcSdrh ){
7110342b1f5Sdrh   int brk = sqlite3VdbeMakeLabel(v);
7120342b1f5Sdrh   int cont = sqlite3VdbeMakeLabel(v);
713d8bc7086Sdrh   int addr;
7140342b1f5Sdrh   int iTab;
71561fc595fSdrh   int pseudoTab = 0;
7160342b1f5Sdrh   ExprList *pOrderBy = p->pOrderBy;
717ffbc3088Sdrh 
7189d2985c7Sdrh   iTab = pOrderBy->iECursor;
719cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
720cdd536f0Sdrh     pseudoTab = pParse->nTab++;
721cdd536f0Sdrh     sqlite3VdbeAddOp(v, OP_OpenPseudo, pseudoTab, 0);
722cdd536f0Sdrh     sqlite3VdbeAddOp(v, OP_SetNumColumns, pseudoTab, nColumn);
723cdd536f0Sdrh   }
7240342b1f5Sdrh   addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk);
725ec7429aeSdrh   codeOffset(v, p, cont, 0);
726cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
727cdd536f0Sdrh     sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
728cdd536f0Sdrh   }
7294db38a70Sdrh   sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1);
730c926afbcSdrh   switch( eDest ){
731c926afbcSdrh     case SRT_Table:
732b9bb7c18Sdrh     case SRT_EphemTab: {
733f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
7344adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
735e4d90813Sdrh       sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
736c926afbcSdrh       break;
737c926afbcSdrh     }
73893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
739c926afbcSdrh     case SRT_Set: {
740c926afbcSdrh       assert( nColumn==1 );
7414adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
7424adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
7434adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
7446c1426fdSdrh       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
745f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
746c926afbcSdrh       break;
747c926afbcSdrh     }
748c926afbcSdrh     case SRT_Mem: {
749c926afbcSdrh       assert( nColumn==1 );
7504adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
751ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
752c926afbcSdrh       break;
753c926afbcSdrh     }
75493758c8dSdanielk1977 #endif
755ce665cf6Sdrh     case SRT_Callback:
756ac82fcf5Sdrh     case SRT_Subroutine: {
757ac82fcf5Sdrh       int i;
758cdd536f0Sdrh       sqlite3VdbeAddOp(v, OP_Insert, pseudoTab, 0);
759ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
760cdd536f0Sdrh         sqlite3VdbeAddOp(v, OP_Column, pseudoTab, i);
761ac82fcf5Sdrh       }
762ce665cf6Sdrh       if( eDest==SRT_Callback ){
763ce665cf6Sdrh         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
764ce665cf6Sdrh       }else{
7654adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
766ce665cf6Sdrh       }
767ac82fcf5Sdrh       break;
768ac82fcf5Sdrh     }
769c926afbcSdrh     default: {
770f46f905aSdrh       /* Do nothing */
771c926afbcSdrh       break;
772c926afbcSdrh     }
773c926afbcSdrh   }
774ec7429aeSdrh 
775ec7429aeSdrh   /* Jump to the end of the loop when the LIMIT is reached
776ec7429aeSdrh   */
777ec7429aeSdrh   if( p->iLimit>=0 ){
77815007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
779ec7429aeSdrh     sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, brk);
780ec7429aeSdrh   }
781ec7429aeSdrh 
782ec7429aeSdrh   /* The bottom of the loop
783ec7429aeSdrh   */
7840342b1f5Sdrh   sqlite3VdbeResolveLabel(v, cont);
7850342b1f5Sdrh   sqlite3VdbeAddOp(v, OP_Next, iTab, addr);
7860342b1f5Sdrh   sqlite3VdbeResolveLabel(v, brk);
787cdd536f0Sdrh   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
788cdd536f0Sdrh     sqlite3VdbeAddOp(v, OP_Close, pseudoTab, 0);
789cdd536f0Sdrh   }
790cdd536f0Sdrh 
791d8bc7086Sdrh }
792d8bc7086Sdrh 
793d8bc7086Sdrh /*
794517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
795517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
796e78e8284Sdrh **
797955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the
798955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The
799955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
800955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The
801955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is
802955de52cSdanielk1977 ** considered a column by this function.
803e78e8284Sdrh **
804955de52cSdanielk1977 **   SELECT col FROM tbl;
805955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl;
806955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl);
807955de52cSdanielk1977 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
808955de52cSdanielk1977 **
809955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL.
810fcb78a49Sdrh */
811955de52cSdanielk1977 static const char *columnType(
812955de52cSdanielk1977   NameContext *pNC,
813955de52cSdanielk1977   Expr *pExpr,
814955de52cSdanielk1977   const char **pzOriginDb,
815955de52cSdanielk1977   const char **pzOriginTab,
816955de52cSdanielk1977   const char **pzOriginCol
817955de52cSdanielk1977 ){
818955de52cSdanielk1977   char const *zType = 0;
819955de52cSdanielk1977   char const *zOriginDb = 0;
820955de52cSdanielk1977   char const *zOriginTab = 0;
821955de52cSdanielk1977   char const *zOriginCol = 0;
822517eb646Sdanielk1977   int j;
823b3bce662Sdanielk1977   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
8245338a5f7Sdanielk1977 
82500e279d9Sdanielk1977   switch( pExpr->op ){
82630bcf5dbSdrh     case TK_AGG_COLUMN:
82700e279d9Sdanielk1977     case TK_COLUMN: {
828955de52cSdanielk1977       /* The expression is a column. Locate the table the column is being
829955de52cSdanielk1977       ** extracted from in NameContext.pSrcList. This table may be real
830955de52cSdanielk1977       ** database table or a subquery.
831955de52cSdanielk1977       */
832955de52cSdanielk1977       Table *pTab = 0;            /* Table structure column is extracted from */
833955de52cSdanielk1977       Select *pS = 0;             /* Select the column is extracted from */
834955de52cSdanielk1977       int iCol = pExpr->iColumn;  /* Index of column in pTab */
835b3bce662Sdanielk1977       while( pNC && !pTab ){
836b3bce662Sdanielk1977         SrcList *pTabList = pNC->pSrcList;
837b3bce662Sdanielk1977         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
838b3bce662Sdanielk1977         if( j<pTabList->nSrc ){
8396a3ea0e6Sdrh           pTab = pTabList->a[j].pTab;
840955de52cSdanielk1977           pS = pTabList->a[j].pSelect;
841b3bce662Sdanielk1977         }else{
842b3bce662Sdanielk1977           pNC = pNC->pNext;
843b3bce662Sdanielk1977         }
844b3bce662Sdanielk1977       }
845955de52cSdanielk1977 
8467e62779aSdrh       if( pTab==0 ){
8477e62779aSdrh         /* FIX ME:
8487e62779aSdrh         ** This can occurs if you have something like "SELECT new.x;" inside
8497e62779aSdrh         ** a trigger.  In other words, if you reference the special "new"
8507e62779aSdrh         ** table in the result set of a select.  We do not have a good way
8517e62779aSdrh         ** to find the actual table type, so call it "TEXT".  This is really
8527e62779aSdrh         ** something of a bug, but I do not know how to fix it.
8537e62779aSdrh         **
8547e62779aSdrh         ** This code does not produce the correct answer - it just prevents
8557e62779aSdrh         ** a segfault.  See ticket #1229.
8567e62779aSdrh         */
8577e62779aSdrh         zType = "TEXT";
8587e62779aSdrh         break;
8597e62779aSdrh       }
860955de52cSdanielk1977 
861b3bce662Sdanielk1977       assert( pTab );
862955de52cSdanielk1977       if( pS ){
863955de52cSdanielk1977         /* The "table" is actually a sub-select or a view in the FROM clause
864955de52cSdanielk1977         ** of the SELECT statement. Return the declaration type and origin
865955de52cSdanielk1977         ** data for the result-set column of the sub-select.
866955de52cSdanielk1977         */
867955de52cSdanielk1977         if( iCol>=0 && iCol<pS->pEList->nExpr ){
868955de52cSdanielk1977           /* If iCol is less than zero, then the expression requests the
869955de52cSdanielk1977           ** rowid of the sub-select or view. This expression is legal (see
870955de52cSdanielk1977           ** test case misc2.2.2) - it always evaluates to NULL.
871955de52cSdanielk1977           */
872955de52cSdanielk1977           NameContext sNC;
873955de52cSdanielk1977           Expr *p = pS->pEList->a[iCol].pExpr;
874955de52cSdanielk1977           sNC.pSrcList = pS->pSrc;
875955de52cSdanielk1977           sNC.pNext = 0;
876955de52cSdanielk1977           sNC.pParse = pNC->pParse;
877955de52cSdanielk1977           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
878955de52cSdanielk1977         }
8794b2688abSdanielk1977       }else if( pTab->pSchema ){
880955de52cSdanielk1977         /* A real table */
881955de52cSdanielk1977         assert( !pS );
882fcb78a49Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
883fcb78a49Sdrh         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
884fcb78a49Sdrh         if( iCol<0 ){
885fcb78a49Sdrh           zType = "INTEGER";
886955de52cSdanielk1977           zOriginCol = "rowid";
887fcb78a49Sdrh         }else{
888fcb78a49Sdrh           zType = pTab->aCol[iCol].zType;
889955de52cSdanielk1977           zOriginCol = pTab->aCol[iCol].zName;
890955de52cSdanielk1977         }
891955de52cSdanielk1977         zOriginTab = pTab->zName;
892955de52cSdanielk1977         if( pNC->pParse ){
893955de52cSdanielk1977           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
894955de52cSdanielk1977           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
895955de52cSdanielk1977         }
896fcb78a49Sdrh       }
89700e279d9Sdanielk1977       break;
898736c22b8Sdrh     }
89993758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
90000e279d9Sdanielk1977     case TK_SELECT: {
901955de52cSdanielk1977       /* The expression is a sub-select. Return the declaration type and
902955de52cSdanielk1977       ** origin info for the single column in the result set of the SELECT
903955de52cSdanielk1977       ** statement.
904955de52cSdanielk1977       */
905b3bce662Sdanielk1977       NameContext sNC;
90600e279d9Sdanielk1977       Select *pS = pExpr->pSelect;
907955de52cSdanielk1977       Expr *p = pS->pEList->a[0].pExpr;
908955de52cSdanielk1977       sNC.pSrcList = pS->pSrc;
909b3bce662Sdanielk1977       sNC.pNext = pNC;
910955de52cSdanielk1977       sNC.pParse = pNC->pParse;
911955de52cSdanielk1977       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
91200e279d9Sdanielk1977       break;
913fcb78a49Sdrh     }
91493758c8dSdanielk1977 #endif
91500e279d9Sdanielk1977   }
91600e279d9Sdanielk1977 
917955de52cSdanielk1977   if( pzOriginDb ){
918955de52cSdanielk1977     assert( pzOriginTab && pzOriginCol );
919955de52cSdanielk1977     *pzOriginDb = zOriginDb;
920955de52cSdanielk1977     *pzOriginTab = zOriginTab;
921955de52cSdanielk1977     *pzOriginCol = zOriginCol;
922955de52cSdanielk1977   }
923517eb646Sdanielk1977   return zType;
924517eb646Sdanielk1977 }
925517eb646Sdanielk1977 
926517eb646Sdanielk1977 /*
927517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
928517eb646Sdanielk1977 ** in the result set.
929517eb646Sdanielk1977 */
930517eb646Sdanielk1977 static void generateColumnTypes(
931517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
932517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
933517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
934517eb646Sdanielk1977 ){
935517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
936517eb646Sdanielk1977   int i;
937b3bce662Sdanielk1977   NameContext sNC;
938b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
939955de52cSdanielk1977   sNC.pParse = pParse;
940517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
941517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
942955de52cSdanielk1977     const char *zOrigDb = 0;
943955de52cSdanielk1977     const char *zOrigTab = 0;
944955de52cSdanielk1977     const char *zOrigCol = 0;
945955de52cSdanielk1977     const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
946955de52cSdanielk1977 
9474b1ae99dSdanielk1977     /* The vdbe must make it's own copy of the column-type and other
9484b1ae99dSdanielk1977     ** column specific strings, in case the schema is reset before this
9494b1ae99dSdanielk1977     ** virtual machine is deleted.
950fbcd585fSdanielk1977     */
9514b1ae99dSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P3_TRANSIENT);
9524b1ae99dSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P3_TRANSIENT);
9534b1ae99dSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P3_TRANSIENT);
9544b1ae99dSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P3_TRANSIENT);
955fcb78a49Sdrh   }
956fcb78a49Sdrh }
957fcb78a49Sdrh 
958fcb78a49Sdrh /*
959fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
960fcb78a49Sdrh ** in the result set.  This information is used to provide the
961fcabd464Sdrh ** azCol[] values in the callback.
96282c3d636Sdrh */
963832508b7Sdrh static void generateColumnNames(
964832508b7Sdrh   Parse *pParse,      /* Parser context */
965ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
966832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
967832508b7Sdrh ){
968d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
9696a3ea0e6Sdrh   int i, j;
9709bb575fdSdrh   sqlite3 *db = pParse->db;
971fcabd464Sdrh   int fullNames, shortNames;
972fcabd464Sdrh 
973fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN
9743cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
9753cf86063Sdanielk1977   if( pParse->explain ){
97661de0d1bSdanielk1977     return;
9773cf86063Sdanielk1977   }
9785338a5f7Sdanielk1977 #endif
9793cf86063Sdanielk1977 
980d6502758Sdrh   assert( v!=0 );
9819e12800dSdanielk1977   if( pParse->colNamesSet || v==0 || sqlite3MallocFailed() ) return;
982d8bc7086Sdrh   pParse->colNamesSet = 1;
983fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
984fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
98522322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
98682c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
98782c3d636Sdrh     Expr *p;
9885a38705eSdrh     p = pEList->a[i].pExpr;
9895a38705eSdrh     if( p==0 ) continue;
99082c3d636Sdrh     if( pEList->a[i].zName ){
99182c3d636Sdrh       char *zName = pEList->a[i].zName;
992955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
99382c3d636Sdrh       continue;
99482c3d636Sdrh     }
995fa173a76Sdrh     if( p->op==TK_COLUMN && pTabList ){
9966a3ea0e6Sdrh       Table *pTab;
99797665873Sdrh       char *zCol;
9988aff1015Sdrh       int iCol = p->iColumn;
9996a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
10006a3ea0e6Sdrh       assert( j<pTabList->nSrc );
10016a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
10028aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
100397665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1004b1363206Sdrh       if( iCol<0 ){
100547a6db2bSdrh         zCol = "rowid";
1006b1363206Sdrh       }else{
1007b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
1008b1363206Sdrh       }
1009fcabd464Sdrh       if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
1010955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
1011fcabd464Sdrh       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
101282c3d636Sdrh         char *zName = 0;
101382c3d636Sdrh         char *zTab;
101482c3d636Sdrh 
10156a3ea0e6Sdrh         zTab = pTabList->a[j].zAlias;
1016fcabd464Sdrh         if( fullNames || zTab==0 ) zTab = pTab->zName;
1017f93339deSdrh         sqlite3SetString(&zName, zTab, ".", zCol, (char*)0);
1018955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P3_DYNAMIC);
101982c3d636Sdrh       }else{
1020955de52cSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
102182c3d636Sdrh       }
10226977fea8Sdrh     }else if( p->span.z && p->span.z[0] ){
1023955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
10243cf86063Sdanielk1977       /* sqlite3VdbeCompressSpace(v, addr); */
10251bee3d7bSdrh     }else{
10261bee3d7bSdrh       char zName[30];
10271bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
10285bb3eb9bSdrh       sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1);
1029955de52cSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0);
103082c3d636Sdrh     }
103182c3d636Sdrh   }
103276d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
10335080aaa7Sdrh }
103482c3d636Sdrh 
103593758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
103682c3d636Sdrh /*
1037d8bc7086Sdrh ** Name of the connection operator, used for error messages.
1038d8bc7086Sdrh */
1039d8bc7086Sdrh static const char *selectOpName(int id){
1040d8bc7086Sdrh   char *z;
1041d8bc7086Sdrh   switch( id ){
1042d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
1043d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
1044d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
1045d8bc7086Sdrh     default:           z = "UNION";       break;
1046d8bc7086Sdrh   }
1047d8bc7086Sdrh   return z;
1048d8bc7086Sdrh }
104993758c8dSdanielk1977 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1050d8bc7086Sdrh 
1051d8bc7086Sdrh /*
1052315555caSdrh ** Forward declaration
1053315555caSdrh */
10549b3187e1Sdrh static int prepSelectStmt(Parse*, Select*);
1055315555caSdrh 
1056315555caSdrh /*
105722f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
105822f70c32Sdrh ** the result set of that SELECT.
105922f70c32Sdrh */
10604adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
106122f70c32Sdrh   Table *pTab;
1062b733d037Sdrh   int i, j;
106322f70c32Sdrh   ExprList *pEList;
1064290c1948Sdrh   Column *aCol, *pCol;
106522f70c32Sdrh 
106692378253Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
10679b3187e1Sdrh   if( prepSelectStmt(pParse, pSelect) ){
106822f70c32Sdrh     return 0;
106922f70c32Sdrh   }
1070142bdf40Sdanielk1977   if( sqlite3SelectResolve(pParse, pSelect, 0) ){
1071142bdf40Sdanielk1977     return 0;
1072142bdf40Sdanielk1977   }
107322f70c32Sdrh   pTab = sqliteMalloc( sizeof(Table) );
107422f70c32Sdrh   if( pTab==0 ){
107522f70c32Sdrh     return 0;
107622f70c32Sdrh   }
1077ed8a3bb1Sdrh   pTab->nRef = 1;
107822f70c32Sdrh   pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
107922f70c32Sdrh   pEList = pSelect->pEList;
108022f70c32Sdrh   pTab->nCol = pEList->nExpr;
1081417be79cSdrh   assert( pTab->nCol>0 );
1082b733d037Sdrh   pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
1083290c1948Sdrh   for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
108479d5f63fSdrh     Expr *p, *pR;
1085517eb646Sdanielk1977     char *zType;
108691bb0eedSdrh     char *zName;
10872564ef97Sdrh     int nName;
1088b3bf556eSdanielk1977     CollSeq *pColl;
108979d5f63fSdrh     int cnt;
1090b3bce662Sdanielk1977     NameContext sNC;
109179d5f63fSdrh 
109279d5f63fSdrh     /* Get an appropriate name for the column
109379d5f63fSdrh     */
109479d5f63fSdrh     p = pEList->a[i].pExpr;
1095290c1948Sdrh     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
109691bb0eedSdrh     if( (zName = pEList->a[i].zName)!=0 ){
109779d5f63fSdrh       /* If the column contains an "AS <name>" phrase, use <name> as the name */
109891bb0eedSdrh       zName = sqliteStrDup(zName);
1099517eb646Sdanielk1977     }else if( p->op==TK_DOT
1100b733d037Sdrh               && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
110179d5f63fSdrh       /* For columns of the from A.B use B as the name */
110291bb0eedSdrh       zName = sqlite3MPrintf("%T", &pR->token);
1103b733d037Sdrh     }else if( p->span.z && p->span.z[0] ){
110479d5f63fSdrh       /* Use the original text of the column expression as its name */
110591bb0eedSdrh       zName = sqlite3MPrintf("%T", &p->span);
110622f70c32Sdrh     }else{
110779d5f63fSdrh       /* If all else fails, make up a name */
110891bb0eedSdrh       zName = sqlite3MPrintf("column%d", i+1);
110922f70c32Sdrh     }
111091bb0eedSdrh     sqlite3Dequote(zName);
11119e12800dSdanielk1977     if( sqlite3MallocFailed() ){
1112dd5b2fa5Sdrh       sqliteFree(zName);
1113a04a34ffSdanielk1977       sqlite3DeleteTable(pTab);
1114dd5b2fa5Sdrh       return 0;
1115dd5b2fa5Sdrh     }
111679d5f63fSdrh 
111779d5f63fSdrh     /* Make sure the column name is unique.  If the name is not unique,
111879d5f63fSdrh     ** append a integer to the name so that it becomes unique.
111979d5f63fSdrh     */
11202564ef97Sdrh     nName = strlen(zName);
112179d5f63fSdrh     for(j=cnt=0; j<i; j++){
112279d5f63fSdrh       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
11232564ef97Sdrh         zName[nName] = 0;
11242564ef97Sdrh         zName = sqlite3MPrintf("%z:%d", zName, ++cnt);
112579d5f63fSdrh         j = -1;
1126dd5b2fa5Sdrh         if( zName==0 ) break;
112779d5f63fSdrh       }
112879d5f63fSdrh     }
112991bb0eedSdrh     pCol->zName = zName;
1130e014a838Sdanielk1977 
113179d5f63fSdrh     /* Get the typename, type affinity, and collating sequence for the
113279d5f63fSdrh     ** column.
113379d5f63fSdrh     */
1134c43e8be8Sdrh     memset(&sNC, 0, sizeof(sNC));
1135b3bce662Sdanielk1977     sNC.pSrcList = pSelect->pSrc;
1136955de52cSdanielk1977     zType = sqliteStrDup(columnType(&sNC, p, 0, 0, 0));
1137290c1948Sdrh     pCol->zType = zType;
1138c60e9b82Sdanielk1977     pCol->affinity = sqlite3ExprAffinity(p);
1139b3bf556eSdanielk1977     pColl = sqlite3ExprCollSeq(pParse, p);
1140b3bf556eSdanielk1977     if( pColl ){
1141e7259296Sdanielk1977       pCol->zColl = sqliteStrDup(pColl->zName);
11420202b29eSdanielk1977     }
114322f70c32Sdrh   }
114422f70c32Sdrh   pTab->iPKey = -1;
114522f70c32Sdrh   return pTab;
114622f70c32Sdrh }
114722f70c32Sdrh 
114822f70c32Sdrh /*
11499b3187e1Sdrh ** Prepare a SELECT statement for processing by doing the following
11509b3187e1Sdrh ** things:
1151d8bc7086Sdrh **
11529b3187e1Sdrh **    (1)  Make sure VDBE cursor numbers have been assigned to every
11539b3187e1Sdrh **         element of the FROM clause.
11549b3187e1Sdrh **
11559b3187e1Sdrh **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
11569b3187e1Sdrh **         defines FROM clause.  When views appear in the FROM clause,
115763eb5f29Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
115863eb5f29Sdrh **         that implements the view.  A copy is made of the view's SELECT
115963eb5f29Sdrh **         statement so that we can freely modify or delete that statement
116063eb5f29Sdrh **         without worrying about messing up the presistent representation
116163eb5f29Sdrh **         of the view.
1162d8bc7086Sdrh **
11639b3187e1Sdrh **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
1164ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
1165ad2d8307Sdrh **
11669b3187e1Sdrh **    (4)  Scan the list of columns in the result set (pEList) looking
116754473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
116854473229Sdrh **         If found, expand each "*" to be every column in every table
116954473229Sdrh **         and TABLE.* to be every column in TABLE.
1170d8bc7086Sdrh **
1171d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
1172d8bc7086Sdrh ** in pParse and return non-zero.
1173d8bc7086Sdrh */
11749b3187e1Sdrh static int prepSelectStmt(Parse *pParse, Select *p){
117554473229Sdrh   int i, j, k, rc;
1176ad3cab52Sdrh   SrcList *pTabList;
1177daffd0e5Sdrh   ExprList *pEList;
1178290c1948Sdrh   struct SrcList_item *pFrom;
1179daffd0e5Sdrh 
11809e12800dSdanielk1977   if( p==0 || p->pSrc==0 || sqlite3MallocFailed() ){
11816f7adc8aSdrh     return 1;
11826f7adc8aSdrh   }
1183daffd0e5Sdrh   pTabList = p->pSrc;
1184daffd0e5Sdrh   pEList = p->pEList;
1185d8bc7086Sdrh 
11869b3187e1Sdrh   /* Make sure cursor numbers have been assigned to all entries in
11879b3187e1Sdrh   ** the FROM clause of the SELECT statement.
11889b3187e1Sdrh   */
11899b3187e1Sdrh   sqlite3SrcListAssignCursors(pParse, p->pSrc);
11909b3187e1Sdrh 
11919b3187e1Sdrh   /* Look up every table named in the FROM clause of the select.  If
11929b3187e1Sdrh   ** an entry of the FROM clause is a subquery instead of a table or view,
11939b3187e1Sdrh   ** then create a transient table structure to describe the subquery.
1194d8bc7086Sdrh   */
1195290c1948Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1196f0113000Sdanielk1977     Table *pTab;
11979b3187e1Sdrh     if( pFrom->pTab!=0 ){
11989b3187e1Sdrh       /* This statement has already been prepared.  There is no need
11999b3187e1Sdrh       ** to go further. */
12009b3187e1Sdrh       assert( i==0 );
1201d8bc7086Sdrh       return 0;
1202d8bc7086Sdrh     }
1203290c1948Sdrh     if( pFrom->zName==0 ){
120493758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
120522f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
1206290c1948Sdrh       assert( pFrom->pSelect!=0 );
1207290c1948Sdrh       if( pFrom->zAlias==0 ){
120891bb0eedSdrh         pFrom->zAlias =
120991bb0eedSdrh           sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
1210ad2d8307Sdrh       }
1211ed8a3bb1Sdrh       assert( pFrom->pTab==0 );
1212290c1948Sdrh       pFrom->pTab = pTab =
1213290c1948Sdrh         sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
121422f70c32Sdrh       if( pTab==0 ){
1215daffd0e5Sdrh         return 1;
1216daffd0e5Sdrh       }
1217b9bb7c18Sdrh       /* The isEphem flag indicates that the Table structure has been
12185cf590c1Sdrh       ** dynamically allocated and may be freed at any time.  In other words,
12195cf590c1Sdrh       ** pTab is not pointing to a persistent table structure that defines
12205cf590c1Sdrh       ** part of the schema. */
1221b9bb7c18Sdrh       pTab->isEphem = 1;
122293758c8dSdanielk1977 #endif
122322f70c32Sdrh     }else{
1224a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
1225ed8a3bb1Sdrh       assert( pFrom->pTab==0 );
1226290c1948Sdrh       pFrom->pTab = pTab =
1227290c1948Sdrh         sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
1228a76b5dfcSdrh       if( pTab==0 ){
1229d8bc7086Sdrh         return 1;
1230d8bc7086Sdrh       }
1231ed8a3bb1Sdrh       pTab->nRef++;
123293626f48Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
123393626f48Sdanielk1977       if( pTab->pSelect || IsVirtual(pTab) ){
123463eb5f29Sdrh         /* We reach here if the named table is a really a view */
12354adee20fSdanielk1977         if( sqlite3ViewGetColumnNames(pParse, pTab) ){
1236417be79cSdrh           return 1;
1237417be79cSdrh         }
1238290c1948Sdrh         /* If pFrom->pSelect!=0 it means we are dealing with a
123963eb5f29Sdrh         ** view within a view.  The SELECT structure has already been
124063eb5f29Sdrh         ** copied by the outer view so we can skip the copy step here
124163eb5f29Sdrh         ** in the inner view.
124263eb5f29Sdrh         */
1243290c1948Sdrh         if( pFrom->pSelect==0 ){
1244290c1948Sdrh           pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
1245a76b5dfcSdrh         }
1246d8bc7086Sdrh       }
124793758c8dSdanielk1977 #endif
124822f70c32Sdrh     }
124963eb5f29Sdrh   }
1250d8bc7086Sdrh 
1251ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
1252ad2d8307Sdrh   */
1253ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
1254ad2d8307Sdrh 
12557c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
125654473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
125754473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
12587c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
12597c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
12607c917d19Sdrh   ** each one to the list of all columns in all tables.
126154473229Sdrh   **
126254473229Sdrh   ** The first loop just checks to see if there are any "*" operators
126354473229Sdrh   ** that need expanding.
1264d8bc7086Sdrh   */
12657c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
126654473229Sdrh     Expr *pE = pEList->a[k].pExpr;
126754473229Sdrh     if( pE->op==TK_ALL ) break;
126854473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
126954473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
12707c917d19Sdrh   }
127154473229Sdrh   rc = 0;
12727c917d19Sdrh   if( k<pEList->nExpr ){
127354473229Sdrh     /*
127454473229Sdrh     ** If we get here it means the result set contains one or more "*"
127554473229Sdrh     ** operators that need to be expanded.  Loop through each expression
127654473229Sdrh     ** in the result set and expand them one by one.
127754473229Sdrh     */
12787c917d19Sdrh     struct ExprList_item *a = pEList->a;
12797c917d19Sdrh     ExprList *pNew = 0;
1280d70dc52dSdrh     int flags = pParse->db->flags;
1281d70dc52dSdrh     int longNames = (flags & SQLITE_FullColNames)!=0 &&
1282d70dc52dSdrh                       (flags & SQLITE_ShortColNames)==0;
1283d70dc52dSdrh 
12847c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
128554473229Sdrh       Expr *pE = a[k].pExpr;
128654473229Sdrh       if( pE->op!=TK_ALL &&
128754473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
128854473229Sdrh         /* This particular expression does not need to be expanded.
128954473229Sdrh         */
12904adee20fSdanielk1977         pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
1291261919ccSdanielk1977         if( pNew ){
12927c917d19Sdrh           pNew->a[pNew->nExpr-1].zName = a[k].zName;
1293261919ccSdanielk1977         }else{
1294261919ccSdanielk1977           rc = 1;
1295261919ccSdanielk1977         }
12967c917d19Sdrh         a[k].pExpr = 0;
12977c917d19Sdrh         a[k].zName = 0;
12987c917d19Sdrh       }else{
129954473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
130054473229Sdrh         ** expanded. */
130154473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
1302cf55b7aeSdrh         char *zTName;            /* text of name of TABLE */
130354473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
1304cf55b7aeSdrh           zTName = sqlite3NameFromToken(&pE->pLeft->token);
130554473229Sdrh         }else{
1306cf55b7aeSdrh           zTName = 0;
130754473229Sdrh         }
1308290c1948Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1309290c1948Sdrh           Table *pTab = pFrom->pTab;
1310290c1948Sdrh           char *zTabName = pFrom->zAlias;
131154473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
131254473229Sdrh             zTabName = pTab->zName;
131354473229Sdrh           }
1314cf55b7aeSdrh           if( zTName && (zTabName==0 || zTabName[0]==0 ||
1315cf55b7aeSdrh                  sqlite3StrICmp(zTName, zTabName)!=0) ){
131654473229Sdrh             continue;
131754473229Sdrh           }
131854473229Sdrh           tableSeen = 1;
1319d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
1320f0113000Sdanielk1977             Expr *pExpr, *pRight;
1321ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
1322ad2d8307Sdrh 
132391bb0eedSdrh             if( i>0 ){
132491bb0eedSdrh               struct SrcList_item *pLeft = &pTabList->a[i-1];
132561dfc31dSdrh               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
132691bb0eedSdrh                         columnIndex(pLeft->pTab, zName)>=0 ){
1327ad2d8307Sdrh                 /* In a NATURAL join, omit the join columns from the
1328ad2d8307Sdrh                 ** table on the right */
1329ad2d8307Sdrh                 continue;
1330ad2d8307Sdrh               }
133161dfc31dSdrh               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
1332ad2d8307Sdrh                 /* In a join with a USING clause, omit columns in the
1333ad2d8307Sdrh                 ** using clause from the table on the right. */
1334ad2d8307Sdrh                 continue;
1335ad2d8307Sdrh               }
133691bb0eedSdrh             }
13374adee20fSdanielk1977             pRight = sqlite3Expr(TK_ID, 0, 0, 0);
133822f70c32Sdrh             if( pRight==0 ) break;
133991bb0eedSdrh             setToken(&pRight->token, zName);
1340d70dc52dSdrh             if( zTabName && (longNames || pTabList->nSrc>1) ){
1341f0113000Sdanielk1977               Expr *pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
13424adee20fSdanielk1977               pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
134322f70c32Sdrh               if( pExpr==0 ) break;
134491bb0eedSdrh               setToken(&pLeft->token, zTabName);
134591bb0eedSdrh               setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
13466977fea8Sdrh               pExpr->span.dyn = 1;
13476977fea8Sdrh               pExpr->token.z = 0;
13486977fea8Sdrh               pExpr->token.n = 0;
13496977fea8Sdrh               pExpr->token.dyn = 0;
135022f70c32Sdrh             }else{
135122f70c32Sdrh               pExpr = pRight;
13526977fea8Sdrh               pExpr->span = pExpr->token;
135322f70c32Sdrh             }
1354d70dc52dSdrh             if( longNames ){
1355d70dc52dSdrh               pNew = sqlite3ExprListAppend(pNew, pExpr, &pExpr->span);
1356d70dc52dSdrh             }else{
135779d5f63fSdrh               pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token);
1358d8bc7086Sdrh             }
1359d8bc7086Sdrh           }
1360d70dc52dSdrh         }
136154473229Sdrh         if( !tableSeen ){
1362cf55b7aeSdrh           if( zTName ){
1363cf55b7aeSdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
1364f5db2d3eSdrh           }else{
13654adee20fSdanielk1977             sqlite3ErrorMsg(pParse, "no tables specified");
1366f5db2d3eSdrh           }
136754473229Sdrh           rc = 1;
136854473229Sdrh         }
1369cf55b7aeSdrh         sqliteFree(zTName);
13707c917d19Sdrh       }
13717c917d19Sdrh     }
13724adee20fSdanielk1977     sqlite3ExprListDelete(pEList);
13737c917d19Sdrh     p->pEList = pNew;
1374d8bc7086Sdrh   }
1375e5c941b8Sdrh   if( p->pEList && p->pEList->nExpr>SQLITE_MAX_COLUMN ){
1376e5c941b8Sdrh     sqlite3ErrorMsg(pParse, "too many columns in result set");
1377e5c941b8Sdrh     rc = SQLITE_ERROR;
1378e5c941b8Sdrh   }
137954473229Sdrh   return rc;
1380d8bc7086Sdrh }
1381d8bc7086Sdrh 
138293758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1383ff78bd2fSdrh /*
1384d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with
1385d8bc7086Sdrh ** columns in a result.  For each ORDER BY expression, the opcode of
1386967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of
1387d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable
1388d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter.
1389d8bc7086Sdrh **
1390d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first.  A match
1391d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT.
1392d8bc7086Sdrh **
1393d8bc7086Sdrh ** Any entry that does not match is flagged as an error.  The number
1394d8bc7086Sdrh ** of errors is returned.
1395d8bc7086Sdrh */
1396d8bc7086Sdrh static int matchOrderbyToColumn(
1397d8bc7086Sdrh   Parse *pParse,          /* A place to leave error messages */
1398d8bc7086Sdrh   Select *pSelect,        /* Match to result columns of this SELECT */
1399d8bc7086Sdrh   ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
1400e4de1febSdrh   int iTable,             /* Insert this value in iTable */
1401d8bc7086Sdrh   int mustComplete        /* If TRUE all ORDER BYs must match */
1402d8bc7086Sdrh ){
1403d8bc7086Sdrh   int nErr = 0;
1404d8bc7086Sdrh   int i, j;
1405d8bc7086Sdrh   ExprList *pEList;
1406d8bc7086Sdrh 
1407daffd0e5Sdrh   if( pSelect==0 || pOrderBy==0 ) return 1;
1408d8bc7086Sdrh   if( mustComplete ){
1409d8bc7086Sdrh     for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1410d8bc7086Sdrh   }
14119b3187e1Sdrh   if( prepSelectStmt(pParse, pSelect) ){
1412d8bc7086Sdrh     return 1;
1413d8bc7086Sdrh   }
1414d8bc7086Sdrh   if( pSelect->pPrior ){
141592cd52f5Sdrh     if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
141692cd52f5Sdrh       return 1;
141792cd52f5Sdrh     }
1418d8bc7086Sdrh   }
1419d8bc7086Sdrh   pEList = pSelect->pEList;
1420d8bc7086Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
142194ccde58Sdrh     struct ExprList_item *pItem;
1422d8bc7086Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
1423e4de1febSdrh     int iCol = -1;
142494ccde58Sdrh     char *zLabel;
142594ccde58Sdrh 
1426d8bc7086Sdrh     if( pOrderBy->a[i].done ) continue;
14274adee20fSdanielk1977     if( sqlite3ExprIsInteger(pE, &iCol) ){
1428e4de1febSdrh       if( iCol<=0 || iCol>pEList->nExpr ){
14294adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
1430da93d238Sdrh           "ORDER BY position %d should be between 1 and %d",
1431e4de1febSdrh           iCol, pEList->nExpr);
1432e4de1febSdrh         nErr++;
1433e4de1febSdrh         break;
1434e4de1febSdrh       }
1435fcb78a49Sdrh       if( !mustComplete ) continue;
1436e4de1febSdrh       iCol--;
1437e4de1febSdrh     }
143894ccde58Sdrh     if( iCol<0 && (zLabel = sqlite3NameFromToken(&pE->token))!=0 ){
143994ccde58Sdrh       for(j=0, pItem=pEList->a; j<pEList->nExpr; j++, pItem++){
144094ccde58Sdrh         char *zName;
14415ea2df91Sdrh         int isMatch;
144294ccde58Sdrh         if( pItem->zName ){
144394ccde58Sdrh           zName = sqlite3StrDup(pItem->zName);
144494ccde58Sdrh         }else{
144594ccde58Sdrh           zName = sqlite3NameFromToken(&pItem->pExpr->token);
144694ccde58Sdrh         }
14475ea2df91Sdrh         isMatch = zName && sqlite3StrICmp(zName, zLabel)==0;
14485ea2df91Sdrh         sqliteFree(zName);
14495ea2df91Sdrh         if( isMatch ){
1450e4de1febSdrh           iCol = j;
145194ccde58Sdrh           break;
145294ccde58Sdrh         }
1453d8bc7086Sdrh       }
14546e142f54Sdrh       sqliteFree(zLabel);
1455d8bc7086Sdrh     }
1456e4de1febSdrh     if( iCol>=0 ){
1457967e8b73Sdrh       pE->op = TK_COLUMN;
1458e4de1febSdrh       pE->iColumn = iCol;
1459d8bc7086Sdrh       pE->iTable = iTable;
1460a58fdfb1Sdanielk1977       pE->iAgg = -1;
1461d8bc7086Sdrh       pOrderBy->a[i].done = 1;
146294ccde58Sdrh     }else if( mustComplete ){
14634adee20fSdanielk1977       sqlite3ErrorMsg(pParse,
1464da93d238Sdrh         "ORDER BY term number %d does not match any result column", i+1);
1465d8bc7086Sdrh       nErr++;
1466d8bc7086Sdrh       break;
1467d8bc7086Sdrh     }
1468d8bc7086Sdrh   }
1469d8bc7086Sdrh   return nErr;
1470d8bc7086Sdrh }
147193758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */
1472d8bc7086Sdrh 
1473d8bc7086Sdrh /*
1474d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1475d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1476d8bc7086Sdrh */
14774adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1478d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1479d8bc7086Sdrh   if( v==0 ){
14804adee20fSdanielk1977     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1481d8bc7086Sdrh   }
1482d8bc7086Sdrh   return v;
1483d8bc7086Sdrh }
1484d8bc7086Sdrh 
148515007a99Sdrh 
1486d8bc7086Sdrh /*
14877b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
1488ec7429aeSdrh ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
14897b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
1490a2dc3b1aSdanielk1977 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1491a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute
1492a2dc3b1aSdanielk1977 ** the limit and offset.  If there is no limit and/or offset, then
1493a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative.
14947b58daeaSdrh **
1495d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if
1496ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset.  iLimit and
14977b58daeaSdrh ** iOffset should have been preset to appropriate default values
14987b58daeaSdrh ** (usually but not always -1) prior to calling this routine.
1499ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
15007b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
15017b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
15027b58daeaSdrh ** SELECT statements.
15037b58daeaSdrh */
1504ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
150502afc861Sdrh   Vdbe *v = 0;
150602afc861Sdrh   int iLimit = 0;
150715007a99Sdrh   int iOffset;
150815007a99Sdrh   int addr1, addr2;
150915007a99Sdrh 
15107b58daeaSdrh   /*
15117b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
15127b58daeaSdrh   ** contraversy about what the correct behavior should be.
15137b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
15147b58daeaSdrh   ** no rows.
15157b58daeaSdrh   */
1516a2dc3b1aSdanielk1977   if( p->pLimit ){
151715007a99Sdrh     p->iLimit = iLimit = pParse->nMem;
1518d59ba6ceSdrh     pParse->nMem += 2;
151915007a99Sdrh     v = sqlite3GetVdbe(pParse);
15207b58daeaSdrh     if( v==0 ) return;
1521a2dc3b1aSdanielk1977     sqlite3ExprCode(pParse, p->pLimit);
1522a2dc3b1aSdanielk1977     sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
15231e4eaeb5Sdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iLimit, 1);
1524ad6d9460Sdrh     VdbeComment((v, "# LIMIT counter"));
152515007a99Sdrh     sqlite3VdbeAddOp(v, OP_IfMemZero, iLimit, iBreak);
15261e4eaeb5Sdanielk1977     sqlite3VdbeAddOp(v, OP_MemLoad, iLimit, 0);
15277b58daeaSdrh   }
1528a2dc3b1aSdanielk1977   if( p->pOffset ){
152915007a99Sdrh     p->iOffset = iOffset = pParse->nMem++;
153015007a99Sdrh     v = sqlite3GetVdbe(pParse);
15317b58daeaSdrh     if( v==0 ) return;
1532a2dc3b1aSdanielk1977     sqlite3ExprCode(pParse, p->pOffset);
1533a2dc3b1aSdanielk1977     sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
153415007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iOffset, p->pLimit==0);
1535ad6d9460Sdrh     VdbeComment((v, "# OFFSET counter"));
153615007a99Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iOffset, 0);
153715007a99Sdrh     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
153815007a99Sdrh     sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
153915007a99Sdrh     sqlite3VdbeJumpHere(v, addr1);
1540d59ba6ceSdrh     if( p->pLimit ){
1541d59ba6ceSdrh       sqlite3VdbeAddOp(v, OP_Add, 0, 0);
1542d59ba6ceSdrh     }
15437b58daeaSdrh   }
1544d59ba6ceSdrh   if( p->pLimit ){
154515007a99Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iLimit, 0);
154615007a99Sdrh     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
154715007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemInt, -1, iLimit+1);
154815007a99Sdrh     addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
154915007a99Sdrh     sqlite3VdbeJumpHere(v, addr1);
155015007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iLimit+1, 1);
1551d59ba6ceSdrh     VdbeComment((v, "# LIMIT+OFFSET"));
155215007a99Sdrh     sqlite3VdbeJumpHere(v, addr2);
1553d59ba6ceSdrh   }
15547b58daeaSdrh }
15557b58daeaSdrh 
15567b58daeaSdrh /*
15570342b1f5Sdrh ** Allocate a virtual index to use for sorting.
1558d3d39e93Sdrh */
15594db38a70Sdrh static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
15600342b1f5Sdrh   if( pOrderBy ){
1561dc1bdc4fSdanielk1977     int addr;
15629d2985c7Sdrh     assert( pOrderBy->iECursor==0 );
15639d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
1564b9bb7c18Sdrh     addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenEphemeral,
15659d2985c7Sdrh                             pOrderBy->iECursor, pOrderBy->nExpr+1);
1566b9bb7c18Sdrh     assert( p->addrOpenEphm[2] == -1 );
1567b9bb7c18Sdrh     p->addrOpenEphm[2] = addr;
1568736c22b8Sdrh   }
1569dc1bdc4fSdanielk1977 }
1570dc1bdc4fSdanielk1977 
1571b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1572fbc4ee7bSdrh /*
1573fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
1574fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
1575fbc4ee7bSdrh ** the column has no default collating sequence.
1576fbc4ee7bSdrh **
1577fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
1578fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
1579fbc4ee7bSdrh */
1580dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1581fbc4ee7bSdrh   CollSeq *pRet;
1582dc1bdc4fSdanielk1977   if( p->pPrior ){
1583dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1584fbc4ee7bSdrh   }else{
1585fbc4ee7bSdrh     pRet = 0;
1586dc1bdc4fSdanielk1977   }
1587fbc4ee7bSdrh   if( pRet==0 ){
1588dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1589dc1bdc4fSdanielk1977   }
1590dc1bdc4fSdanielk1977   return pRet;
1591d3d39e93Sdrh }
1592b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1593d3d39e93Sdrh 
1594b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1595d3d39e93Sdrh /*
159682c3d636Sdrh ** This routine is called to process a query that is really the union
159782c3d636Sdrh ** or intersection of two or more separate queries.
1598c926afbcSdrh **
1599e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1600e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1601e78e8284Sdrh ** in which case this routine will be called recursively.
1602e78e8284Sdrh **
1603e78e8284Sdrh ** The results of the total query are to be written into a destination
1604e78e8284Sdrh ** of type eDest with parameter iParm.
1605e78e8284Sdrh **
1606e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1607e78e8284Sdrh **
1608e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1609e78e8284Sdrh **
1610e78e8284Sdrh ** This statement is parsed up as follows:
1611e78e8284Sdrh **
1612e78e8284Sdrh **     SELECT c FROM t3
1613e78e8284Sdrh **      |
1614e78e8284Sdrh **      `----->  SELECT b FROM t2
1615e78e8284Sdrh **                |
16164b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1617e78e8284Sdrh **
1618e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1619e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1620e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1621e78e8284Sdrh **
1622e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1623e78e8284Sdrh ** individual selects always group from left to right.
162482c3d636Sdrh */
162584ac9d02Sdanielk1977 static int multiSelect(
1626fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
1627fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
1628fbc4ee7bSdrh   int eDest,            /* \___  Store query results as specified */
1629fbc4ee7bSdrh   int iParm,            /* /     by these two parameters.         */
163084ac9d02Sdanielk1977   char *aff             /* If eDest is SRT_Union, the affinity string */
163184ac9d02Sdanielk1977 ){
163284ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
163310e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
163410e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
16358cdbf836Sdrh   int nCol;             /* Number of columns in the result set */
16360342b1f5Sdrh   ExprList *pOrderBy;   /* The ORDER BY clause on p */
16370342b1f5Sdrh   int aSetP2[2];        /* Set P2 value of these op to number of columns */
16380342b1f5Sdrh   int nSetP2 = 0;       /* Number of slots in aSetP2[] used */
163982c3d636Sdrh 
16407b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1641fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
164282c3d636Sdrh   */
164384ac9d02Sdanielk1977   if( p==0 || p->pPrior==0 ){
164484ac9d02Sdanielk1977     rc = 1;
164584ac9d02Sdanielk1977     goto multi_select_end;
164684ac9d02Sdanielk1977   }
1647d8bc7086Sdrh   pPrior = p->pPrior;
16480342b1f5Sdrh   assert( pPrior->pRightmost!=pPrior );
16490342b1f5Sdrh   assert( pPrior->pRightmost==p->pRightmost );
1650d8bc7086Sdrh   if( pPrior->pOrderBy ){
16514adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1652da93d238Sdrh       selectOpName(p->op));
165384ac9d02Sdanielk1977     rc = 1;
165484ac9d02Sdanielk1977     goto multi_select_end;
165582c3d636Sdrh   }
1656a2dc3b1aSdanielk1977   if( pPrior->pLimit ){
16574adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
16587b58daeaSdrh       selectOpName(p->op));
165984ac9d02Sdanielk1977     rc = 1;
166084ac9d02Sdanielk1977     goto multi_select_end;
16617b58daeaSdrh   }
166282c3d636Sdrh 
1663d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
1664d8bc7086Sdrh   */
16654adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
166684ac9d02Sdanielk1977   if( v==0 ){
166784ac9d02Sdanielk1977     rc = 1;
166884ac9d02Sdanielk1977     goto multi_select_end;
166984ac9d02Sdanielk1977   }
1670d8bc7086Sdrh 
16711cc3d75fSdrh   /* Create the destination temporary table if necessary
16721cc3d75fSdrh   */
1673b9bb7c18Sdrh   if( eDest==SRT_EphemTab ){
1674b4964b72Sdanielk1977     assert( p->pEList );
16750342b1f5Sdrh     assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1676b9bb7c18Sdrh     aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 0);
16771cc3d75fSdrh     eDest = SRT_Table;
16781cc3d75fSdrh   }
16791cc3d75fSdrh 
1680f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1681d8bc7086Sdrh   */
16820342b1f5Sdrh   pOrderBy = p->pOrderBy;
168382c3d636Sdrh   switch( p->op ){
1684f46f905aSdrh     case TK_ALL: {
16850342b1f5Sdrh       if( pOrderBy==0 ){
1686ec7429aeSdrh         int addr = 0;
1687a2dc3b1aSdanielk1977         assert( !pPrior->pLimit );
1688a2dc3b1aSdanielk1977         pPrior->pLimit = p->pLimit;
1689a2dc3b1aSdanielk1977         pPrior->pOffset = p->pOffset;
1690b3bce662Sdanielk1977         rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
1691ad68cb6bSdanielk1977         p->pLimit = 0;
1692ad68cb6bSdanielk1977         p->pOffset = 0;
169384ac9d02Sdanielk1977         if( rc ){
169484ac9d02Sdanielk1977           goto multi_select_end;
169584ac9d02Sdanielk1977         }
1696f46f905aSdrh         p->pPrior = 0;
16977b58daeaSdrh         p->iLimit = pPrior->iLimit;
16987b58daeaSdrh         p->iOffset = pPrior->iOffset;
1699ec7429aeSdrh         if( p->iLimit>=0 ){
1700ec7429aeSdrh           addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0);
1701ec7429aeSdrh           VdbeComment((v, "# Jump ahead if LIMIT reached"));
1702ec7429aeSdrh         }
1703b3bce662Sdanielk1977         rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
1704f46f905aSdrh         p->pPrior = pPrior;
170584ac9d02Sdanielk1977         if( rc ){
170684ac9d02Sdanielk1977           goto multi_select_end;
170784ac9d02Sdanielk1977         }
1708ec7429aeSdrh         if( addr ){
1709ec7429aeSdrh           sqlite3VdbeJumpHere(v, addr);
1710ec7429aeSdrh         }
1711f46f905aSdrh         break;
1712f46f905aSdrh       }
1713f46f905aSdrh       /* For UNION ALL ... ORDER BY fall through to the next case */
1714f46f905aSdrh     }
171582c3d636Sdrh     case TK_EXCEPT:
171682c3d636Sdrh     case TK_UNION: {
1717d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1718742f947bSdanielk1977       int op = 0;      /* One of the SRT_ operations to apply to self */
1719d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
1720a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
1721dc1bdc4fSdanielk1977       int addr;
172282c3d636Sdrh 
1723d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
17240342b1f5Sdrh       if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
1725d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1726c926afbcSdrh         ** right.
1727d8bc7086Sdrh         */
172882c3d636Sdrh         unionTab = iParm;
172982c3d636Sdrh       }else{
1730d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1731d8bc7086Sdrh         ** intermediate results.
1732d8bc7086Sdrh         */
173382c3d636Sdrh         unionTab = pParse->nTab++;
17340342b1f5Sdrh         if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){
173584ac9d02Sdanielk1977           rc = 1;
173684ac9d02Sdanielk1977           goto multi_select_end;
1737d8bc7086Sdrh         }
1738b9bb7c18Sdrh         addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, unionTab, 0);
17390342b1f5Sdrh         if( priorOp==SRT_Table ){
17400342b1f5Sdrh           assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
17410342b1f5Sdrh           aSetP2[nSetP2++] = addr;
17420342b1f5Sdrh         }else{
1743b9bb7c18Sdrh           assert( p->addrOpenEphm[0] == -1 );
1744b9bb7c18Sdrh           p->addrOpenEphm[0] = addr;
1745b9bb7c18Sdrh           p->pRightmost->usesEphm = 1;
1746dc1bdc4fSdanielk1977         }
17470342b1f5Sdrh         createSortingIndex(pParse, p, pOrderBy);
174884ac9d02Sdanielk1977         assert( p->pEList );
1749d8bc7086Sdrh       }
1750d8bc7086Sdrh 
1751d8bc7086Sdrh       /* Code the SELECT statements to our left
1752d8bc7086Sdrh       */
1753b3bce662Sdanielk1977       assert( !pPrior->pOrderBy );
1754b3bce662Sdanielk1977       rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
175584ac9d02Sdanielk1977       if( rc ){
175684ac9d02Sdanielk1977         goto multi_select_end;
175784ac9d02Sdanielk1977       }
1758d8bc7086Sdrh 
1759d8bc7086Sdrh       /* Code the current SELECT statement
1760d8bc7086Sdrh       */
1761d8bc7086Sdrh       switch( p->op ){
1762d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
1763d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
1764d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
1765d8bc7086Sdrh       }
176682c3d636Sdrh       p->pPrior = 0;
1767c926afbcSdrh       p->pOrderBy = 0;
17684b14b4d7Sdrh       p->disallowOrderBy = pOrderBy!=0;
1769a2dc3b1aSdanielk1977       pLimit = p->pLimit;
1770a2dc3b1aSdanielk1977       p->pLimit = 0;
1771a2dc3b1aSdanielk1977       pOffset = p->pOffset;
1772a2dc3b1aSdanielk1977       p->pOffset = 0;
1773b3bce662Sdanielk1977       rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
177482c3d636Sdrh       p->pPrior = pPrior;
1775c926afbcSdrh       p->pOrderBy = pOrderBy;
1776a2dc3b1aSdanielk1977       sqlite3ExprDelete(p->pLimit);
1777a2dc3b1aSdanielk1977       p->pLimit = pLimit;
1778a2dc3b1aSdanielk1977       p->pOffset = pOffset;
1779be5fd490Sdrh       p->iLimit = -1;
1780be5fd490Sdrh       p->iOffset = -1;
178184ac9d02Sdanielk1977       if( rc ){
178284ac9d02Sdanielk1977         goto multi_select_end;
178384ac9d02Sdanielk1977       }
178484ac9d02Sdanielk1977 
1785d8bc7086Sdrh 
1786d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1787d8bc7086Sdrh       ** it is that we currently need.
1788d8bc7086Sdrh       */
1789c926afbcSdrh       if( eDest!=priorOp || unionTab!=iParm ){
17906b56344dSdrh         int iCont, iBreak, iStart;
179182c3d636Sdrh         assert( p->pEList );
179241202ccaSdrh         if( eDest==SRT_Callback ){
179392378253Sdrh           Select *pFirst = p;
179492378253Sdrh           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
179592378253Sdrh           generateColumnNames(pParse, 0, pFirst->pEList);
179641202ccaSdrh         }
17974adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
17984adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
1799ec7429aeSdrh         computeLimitRegisters(pParse, p, iBreak);
18004adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
18014adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
180238640e15Sdrh         rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
18030342b1f5Sdrh                              pOrderBy, -1, eDest, iParm,
180484ac9d02Sdanielk1977                              iCont, iBreak, 0);
180584ac9d02Sdanielk1977         if( rc ){
180684ac9d02Sdanielk1977           rc = 1;
180784ac9d02Sdanielk1977           goto multi_select_end;
180884ac9d02Sdanielk1977         }
18094adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
18104adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
18114adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
18124adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
181382c3d636Sdrh       }
181482c3d636Sdrh       break;
181582c3d636Sdrh     }
181682c3d636Sdrh     case TK_INTERSECT: {
181782c3d636Sdrh       int tab1, tab2;
18186b56344dSdrh       int iCont, iBreak, iStart;
1819a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset;
1820dc1bdc4fSdanielk1977       int addr;
182182c3d636Sdrh 
1822d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
18236206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
1824d8bc7086Sdrh       ** by allocating the tables we will need.
1825d8bc7086Sdrh       */
182682c3d636Sdrh       tab1 = pParse->nTab++;
182782c3d636Sdrh       tab2 = pParse->nTab++;
18280342b1f5Sdrh       if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){
182984ac9d02Sdanielk1977         rc = 1;
183084ac9d02Sdanielk1977         goto multi_select_end;
1831d8bc7086Sdrh       }
18320342b1f5Sdrh       createSortingIndex(pParse, p, pOrderBy);
1833dc1bdc4fSdanielk1977 
1834b9bb7c18Sdrh       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab1, 0);
1835b9bb7c18Sdrh       assert( p->addrOpenEphm[0] == -1 );
1836b9bb7c18Sdrh       p->addrOpenEphm[0] = addr;
1837b9bb7c18Sdrh       p->pRightmost->usesEphm = 1;
183884ac9d02Sdanielk1977       assert( p->pEList );
1839d8bc7086Sdrh 
1840d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1841d8bc7086Sdrh       */
1842b3bce662Sdanielk1977       rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
184384ac9d02Sdanielk1977       if( rc ){
184484ac9d02Sdanielk1977         goto multi_select_end;
184584ac9d02Sdanielk1977       }
1846d8bc7086Sdrh 
1847d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1848d8bc7086Sdrh       */
1849b9bb7c18Sdrh       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab2, 0);
1850b9bb7c18Sdrh       assert( p->addrOpenEphm[1] == -1 );
1851b9bb7c18Sdrh       p->addrOpenEphm[1] = addr;
185282c3d636Sdrh       p->pPrior = 0;
1853a2dc3b1aSdanielk1977       pLimit = p->pLimit;
1854a2dc3b1aSdanielk1977       p->pLimit = 0;
1855a2dc3b1aSdanielk1977       pOffset = p->pOffset;
1856a2dc3b1aSdanielk1977       p->pOffset = 0;
1857b3bce662Sdanielk1977       rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
185882c3d636Sdrh       p->pPrior = pPrior;
1859a2dc3b1aSdanielk1977       sqlite3ExprDelete(p->pLimit);
1860a2dc3b1aSdanielk1977       p->pLimit = pLimit;
1861a2dc3b1aSdanielk1977       p->pOffset = pOffset;
186284ac9d02Sdanielk1977       if( rc ){
186384ac9d02Sdanielk1977         goto multi_select_end;
186484ac9d02Sdanielk1977       }
1865d8bc7086Sdrh 
1866d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1867d8bc7086Sdrh       ** tables.
1868d8bc7086Sdrh       */
186982c3d636Sdrh       assert( p->pEList );
187041202ccaSdrh       if( eDest==SRT_Callback ){
187192378253Sdrh         Select *pFirst = p;
187292378253Sdrh         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
187392378253Sdrh         generateColumnNames(pParse, 0, pFirst->pEList);
187441202ccaSdrh       }
18754adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
18764adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
1877ec7429aeSdrh       computeLimitRegisters(pParse, p, iBreak);
18784adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
18794a9f241cSdrh       iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0);
18804adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
188138640e15Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
18820342b1f5Sdrh                              pOrderBy, -1, eDest, iParm,
188384ac9d02Sdanielk1977                              iCont, iBreak, 0);
188484ac9d02Sdanielk1977       if( rc ){
188584ac9d02Sdanielk1977         rc = 1;
188684ac9d02Sdanielk1977         goto multi_select_end;
188784ac9d02Sdanielk1977       }
18884adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
18894adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
18904adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
18914adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
18924adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
189382c3d636Sdrh       break;
189482c3d636Sdrh     }
189582c3d636Sdrh   }
18968cdbf836Sdrh 
18978cdbf836Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
18988cdbf836Sdrh   ** in their result sets.
18998cdbf836Sdrh   */
190082c3d636Sdrh   assert( p->pEList && pPrior->pEList );
190182c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
19024adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
1903da93d238Sdrh       " do not have the same number of result columns", selectOpName(p->op));
190484ac9d02Sdanielk1977     rc = 1;
190584ac9d02Sdanielk1977     goto multi_select_end;
19062282792aSdrh   }
190784ac9d02Sdanielk1977 
19088cdbf836Sdrh   /* Set the number of columns in temporary tables
19098cdbf836Sdrh   */
19108cdbf836Sdrh   nCol = p->pEList->nExpr;
19110342b1f5Sdrh   while( nSetP2 ){
19120342b1f5Sdrh     sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
19138cdbf836Sdrh   }
19148cdbf836Sdrh 
1915fbc4ee7bSdrh   /* Compute collating sequences used by either the ORDER BY clause or
1916fbc4ee7bSdrh   ** by any temporary tables needed to implement the compound select.
1917fbc4ee7bSdrh   ** Attach the KeyInfo structure to all temporary tables.  Invoke the
1918fbc4ee7bSdrh   ** ORDER BY processing if there is an ORDER BY clause.
19198cdbf836Sdrh   **
19208cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
19218cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
19228cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
19238cdbf836Sdrh   ** no temp tables are required.
1924fbc4ee7bSdrh   */
1925b9bb7c18Sdrh   if( pOrderBy || p->usesEphm ){
1926fbc4ee7bSdrh     int i;                        /* Loop counter */
1927fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
19280342b1f5Sdrh     Select *pLoop;                /* For looping through SELECT statements */
19291e31e0b2Sdrh     int nKeyCol;                  /* Number of entries in pKeyInfo->aCol[] */
1930f68d7d17Sdrh     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
1931f68d7d17Sdrh     CollSeq **aCopy;              /* A copy of pKeyInfo->aColl[] */
1932fbc4ee7bSdrh 
19330342b1f5Sdrh     assert( p->pRightmost==p );
19341e31e0b2Sdrh     nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0);
19351e31e0b2Sdrh     pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1));
1936dc1bdc4fSdanielk1977     if( !pKeyInfo ){
1937dc1bdc4fSdanielk1977       rc = SQLITE_NOMEM;
1938dc1bdc4fSdanielk1977       goto multi_select_end;
1939dc1bdc4fSdanielk1977     }
1940dc1bdc4fSdanielk1977 
194114db2665Sdanielk1977     pKeyInfo->enc = ENC(pParse->db);
1942dc1bdc4fSdanielk1977     pKeyInfo->nField = nCol;
1943dc1bdc4fSdanielk1977 
19440342b1f5Sdrh     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
19450342b1f5Sdrh       *apColl = multiSelectCollSeq(pParse, p, i);
19460342b1f5Sdrh       if( 0==*apColl ){
19470342b1f5Sdrh         *apColl = pParse->db->pDfltColl;
1948dc1bdc4fSdanielk1977       }
1949dc1bdc4fSdanielk1977     }
1950dc1bdc4fSdanielk1977 
19510342b1f5Sdrh     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
19520342b1f5Sdrh       for(i=0; i<2; i++){
1953b9bb7c18Sdrh         int addr = pLoop->addrOpenEphm[i];
19540342b1f5Sdrh         if( addr<0 ){
19550342b1f5Sdrh           /* If [0] is unused then [1] is also unused.  So we can
19560342b1f5Sdrh           ** always safely abort as soon as the first unused slot is found */
1957b9bb7c18Sdrh           assert( pLoop->addrOpenEphm[1]<0 );
19580342b1f5Sdrh           break;
19590342b1f5Sdrh         }
19600342b1f5Sdrh         sqlite3VdbeChangeP2(v, addr, nCol);
19610342b1f5Sdrh         sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO);
19620ee5a1e7Sdrh         pLoop->addrOpenEphm[i] = -1;
19630342b1f5Sdrh       }
1964dc1bdc4fSdanielk1977     }
1965dc1bdc4fSdanielk1977 
19660342b1f5Sdrh     if( pOrderBy ){
19670342b1f5Sdrh       struct ExprList_item *pOTerm = pOrderBy->a;
19684efc083fSdrh       int nOrderByExpr = pOrderBy->nExpr;
19690342b1f5Sdrh       int addr;
19704db38a70Sdrh       u8 *pSortOrder;
19710342b1f5Sdrh 
1972f68d7d17Sdrh       /* Reuse the same pKeyInfo for the ORDER BY as was used above for
1973f68d7d17Sdrh       ** the compound select statements.  Except we have to change out the
1974f68d7d17Sdrh       ** pKeyInfo->aColl[] values.  Some of the aColl[] values will be
1975f68d7d17Sdrh       ** reused when constructing the pKeyInfo for the ORDER BY, so make
1976f68d7d17Sdrh       ** a copy.  Sufficient space to hold both the nCol entries for
1977f68d7d17Sdrh       ** the compound select and the nOrderbyExpr entries for the ORDER BY
1978f68d7d17Sdrh       ** was allocated above.  But we need to move the compound select
1979f68d7d17Sdrh       ** entries out of the way before constructing the ORDER BY entries.
1980f68d7d17Sdrh       ** Move the compound select entries into aCopy[] where they can be
1981f68d7d17Sdrh       ** accessed and reused when constructing the ORDER BY entries.
1982f68d7d17Sdrh       ** Because nCol might be greater than or less than nOrderByExpr
1983f68d7d17Sdrh       ** we have to use memmove() when doing the copy.
1984f68d7d17Sdrh       */
19851e31e0b2Sdrh       aCopy = &pKeyInfo->aColl[nOrderByExpr];
19864efc083fSdrh       pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
1987f68d7d17Sdrh       memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
1988f68d7d17Sdrh 
19890342b1f5Sdrh       apColl = pKeyInfo->aColl;
19904efc083fSdrh       for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
19910342b1f5Sdrh         Expr *pExpr = pOTerm->pExpr;
19928b4c40d8Sdrh         if( (pExpr->flags & EP_ExpCollate) ){
19938b4c40d8Sdrh           assert( pExpr->pColl!=0 );
19948b4c40d8Sdrh           *apColl = pExpr->pColl;
199584ac9d02Sdanielk1977         }else{
19960342b1f5Sdrh           *apColl = aCopy[pExpr->iColumn];
199784ac9d02Sdanielk1977         }
19984db38a70Sdrh         *pSortOrder = pOTerm->sortOrder;
199984ac9d02Sdanielk1977       }
20000342b1f5Sdrh       assert( p->pRightmost==p );
2001b9bb7c18Sdrh       assert( p->addrOpenEphm[2]>=0 );
2002b9bb7c18Sdrh       addr = p->addrOpenEphm[2];
20034db38a70Sdrh       sqlite3VdbeChangeP2(v, addr, p->pEList->nExpr+2);
20044efc083fSdrh       pKeyInfo->nField = nOrderByExpr;
20054db38a70Sdrh       sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
20064db38a70Sdrh       pKeyInfo = 0;
2007cdd536f0Sdrh       generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
2008dc1bdc4fSdanielk1977     }
2009dc1bdc4fSdanielk1977 
2010dc1bdc4fSdanielk1977     sqliteFree(pKeyInfo);
2011dc1bdc4fSdanielk1977   }
2012dc1bdc4fSdanielk1977 
2013dc1bdc4fSdanielk1977 multi_select_end:
201484ac9d02Sdanielk1977   return rc;
20152282792aSdrh }
2016b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
20172282792aSdrh 
2018b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
20192282792aSdrh /*
2020832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
20216a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
202284e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
20236a3ea0e6Sdrh ** unchanged.)
2024832508b7Sdrh **
2025832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
2026832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
2027832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
2028832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
2029832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
2030832508b7Sdrh ** of the subquery rather the result set of the subquery.
2031832508b7Sdrh */
20326a3ea0e6Sdrh static void substExprList(ExprList*,int,ExprList*);  /* Forward Decl */
2033b3bce662Sdanielk1977 static void substSelect(Select *, int, ExprList *);  /* Forward Decl */
20346a3ea0e6Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
2035832508b7Sdrh   if( pExpr==0 ) return;
203650350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
203750350a15Sdrh     if( pExpr->iColumn<0 ){
203850350a15Sdrh       pExpr->op = TK_NULL;
203950350a15Sdrh     }else{
2040832508b7Sdrh       Expr *pNew;
204184e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
2042832508b7Sdrh       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
2043832508b7Sdrh       pNew = pEList->a[pExpr->iColumn].pExpr;
2044832508b7Sdrh       assert( pNew!=0 );
2045832508b7Sdrh       pExpr->op = pNew->op;
2046d94a6698Sdrh       assert( pExpr->pLeft==0 );
20474adee20fSdanielk1977       pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
2048d94a6698Sdrh       assert( pExpr->pRight==0 );
20494adee20fSdanielk1977       pExpr->pRight = sqlite3ExprDup(pNew->pRight);
2050d94a6698Sdrh       assert( pExpr->pList==0 );
20514adee20fSdanielk1977       pExpr->pList = sqlite3ExprListDup(pNew->pList);
2052832508b7Sdrh       pExpr->iTable = pNew->iTable;
2053fbbe005aSdanielk1977       pExpr->pTab = pNew->pTab;
2054832508b7Sdrh       pExpr->iColumn = pNew->iColumn;
2055832508b7Sdrh       pExpr->iAgg = pNew->iAgg;
20564adee20fSdanielk1977       sqlite3TokenCopy(&pExpr->token, &pNew->token);
20574adee20fSdanielk1977       sqlite3TokenCopy(&pExpr->span, &pNew->span);
2058a1cb183dSdanielk1977       pExpr->pSelect = sqlite3SelectDup(pNew->pSelect);
2059a1cb183dSdanielk1977       pExpr->flags = pNew->flags;
206050350a15Sdrh     }
2061832508b7Sdrh   }else{
20626a3ea0e6Sdrh     substExpr(pExpr->pLeft, iTable, pEList);
20636a3ea0e6Sdrh     substExpr(pExpr->pRight, iTable, pEList);
2064b3bce662Sdanielk1977     substSelect(pExpr->pSelect, iTable, pEList);
20656a3ea0e6Sdrh     substExprList(pExpr->pList, iTable, pEList);
2066832508b7Sdrh   }
2067832508b7Sdrh }
2068b3bce662Sdanielk1977 static void substExprList(ExprList *pList, int iTable, ExprList *pEList){
2069832508b7Sdrh   int i;
2070832508b7Sdrh   if( pList==0 ) return;
2071832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
20726a3ea0e6Sdrh     substExpr(pList->a[i].pExpr, iTable, pEList);
2073832508b7Sdrh   }
2074832508b7Sdrh }
2075b3bce662Sdanielk1977 static void substSelect(Select *p, int iTable, ExprList *pEList){
2076b3bce662Sdanielk1977   if( !p ) return;
2077b3bce662Sdanielk1977   substExprList(p->pEList, iTable, pEList);
2078b3bce662Sdanielk1977   substExprList(p->pGroupBy, iTable, pEList);
2079b3bce662Sdanielk1977   substExprList(p->pOrderBy, iTable, pEList);
2080b3bce662Sdanielk1977   substExpr(p->pHaving, iTable, pEList);
2081b3bce662Sdanielk1977   substExpr(p->pWhere, iTable, pEList);
2082*fa2bb6daSdanielk1977   substSelect(p->pPrior, iTable, pEList);
2083b3bce662Sdanielk1977 }
2084b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_VIEW) */
2085832508b7Sdrh 
2086b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
2087832508b7Sdrh /*
20881350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
20891350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
20901350b030Sdrh ** occurs.
20911350b030Sdrh **
20921350b030Sdrh ** To understand the concept of flattening, consider the following
20931350b030Sdrh ** query:
20941350b030Sdrh **
20951350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
20961350b030Sdrh **
20971350b030Sdrh ** The default way of implementing this query is to execute the
20981350b030Sdrh ** subquery first and store the results in a temporary table, then
20991350b030Sdrh ** run the outer query on that temporary table.  This requires two
21001350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
21011350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
2102832508b7Sdrh ** optimized.
21031350b030Sdrh **
2104832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
21051350b030Sdrh ** a single flat select, like this:
21061350b030Sdrh **
21071350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
21081350b030Sdrh **
21091350b030Sdrh ** The code generated for this simpification gives the same result
2110832508b7Sdrh ** but only has to scan the data once.  And because indices might
2111832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
2112832508b7Sdrh ** avoided.
21131350b030Sdrh **
2114832508b7Sdrh ** Flattening is only attempted if all of the following are true:
21151350b030Sdrh **
2116832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
21171350b030Sdrh **
2118832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
2119832508b7Sdrh **
21208af4d3acSdrh **   (3)  The subquery is not the right operand of a left outer join, or
21218af4d3acSdrh **        the subquery is not itself a join.  (Ticket #306)
2122832508b7Sdrh **
2123832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
2124832508b7Sdrh **
2125832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
2126832508b7Sdrh **        aggregates.
2127832508b7Sdrh **
2128832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
2129832508b7Sdrh **        DISTINCT.
2130832508b7Sdrh **
213108192d5fSdrh **   (7)  The subquery has a FROM clause.
213208192d5fSdrh **
2133df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
2134df199a25Sdrh **
2135df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
2136df199a25Sdrh **        aggregates.
2137df199a25Sdrh **
2138df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
2139df199a25Sdrh **        use LIMIT.
2140df199a25Sdrh **
2141174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
2142174b6195Sdrh **
21433fc673e6Sdrh **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
21443fc673e6Sdrh **        subquery has no WHERE clause.  (added by ticket #350)
21453fc673e6Sdrh **
2146ac83963aSdrh **  (13)  The subquery and outer query do not both use LIMIT
2147ac83963aSdrh **
2148ac83963aSdrh **  (14)  The subquery does not use OFFSET
2149ac83963aSdrh **
2150ad91c6cdSdrh **  (15)  The outer query is not part of a compound select or the
2151ad91c6cdSdrh **        subquery does not have both an ORDER BY and a LIMIT clause.
2152ad91c6cdSdrh **        (See ticket #2339)
2153ad91c6cdSdrh **
2154832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
2155832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
2156832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
2157832508b7Sdrh **
2158665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
2159832508b7Sdrh ** If flattening is attempted this routine returns 1.
2160832508b7Sdrh **
2161832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
2162832508b7Sdrh ** the subquery before this routine runs.
21631350b030Sdrh */
21648c74a8caSdrh static int flattenSubquery(
21658c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
21668c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
21678c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
21688c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
21698c74a8caSdrh ){
21700bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
2171ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
2172ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
21730bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
21746a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
217591bb0eedSdrh   int i;              /* Loop counter */
217691bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
217791bb0eedSdrh   struct SrcList_item *pSubitem;   /* The subquery */
21781350b030Sdrh 
2179832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
2180832508b7Sdrh   */
2181832508b7Sdrh   if( p==0 ) return 0;
2182832508b7Sdrh   pSrc = p->pSrc;
2183ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
218491bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
218591bb0eedSdrh   pSub = pSubitem->pSelect;
2186832508b7Sdrh   assert( pSub!=0 );
2187ac83963aSdrh   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
2188ac83963aSdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
2189832508b7Sdrh   pSubSrc = pSub->pSrc;
2190832508b7Sdrh   assert( pSubSrc );
2191ac83963aSdrh   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
2192ac83963aSdrh   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
2193ac83963aSdrh   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
2194ac83963aSdrh   ** became arbitrary expressions, we were forced to add restrictions (13)
2195ac83963aSdrh   ** and (14). */
2196ac83963aSdrh   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
2197ac83963aSdrh   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
2198ad91c6cdSdrh   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
2199ad91c6cdSdrh     return 0;                                            /* Restriction (15) */
2200ad91c6cdSdrh   }
2201ac83963aSdrh   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
2202ac83963aSdrh   if( (pSub->isDistinct || pSub->pLimit)
2203ac83963aSdrh          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
2204df199a25Sdrh      return 0;
2205df199a25Sdrh   }
2206ac83963aSdrh   if( p->isDistinct && subqueryIsAgg ) return 0;         /* Restriction (6)  */
2207ac83963aSdrh   if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){
2208ac83963aSdrh      return 0;                                           /* Restriction (11) */
2209ac83963aSdrh   }
2210832508b7Sdrh 
22118af4d3acSdrh   /* Restriction 3:  If the subquery is a join, make sure the subquery is
22128af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
22138af4d3acSdrh   ** is not allowed:
22148af4d3acSdrh   **
22158af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
22168af4d3acSdrh   **
22178af4d3acSdrh   ** If we flatten the above, we would get
22188af4d3acSdrh   **
22198af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
22208af4d3acSdrh   **
22218af4d3acSdrh   ** which is not at all the same thing.
22228af4d3acSdrh   */
222361dfc31dSdrh   if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){
22248af4d3acSdrh     return 0;
22258af4d3acSdrh   }
22268af4d3acSdrh 
22273fc673e6Sdrh   /* Restriction 12:  If the subquery is the right operand of a left outer
22283fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
22293fc673e6Sdrh   ** An examples of why this is not allowed:
22303fc673e6Sdrh   **
22313fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
22323fc673e6Sdrh   **
22333fc673e6Sdrh   ** If we flatten the above, we would get
22343fc673e6Sdrh   **
22353fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
22363fc673e6Sdrh   **
22373fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
22383fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
22393fc673e6Sdrh   */
224061dfc31dSdrh   if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){
22413fc673e6Sdrh     return 0;
22423fc673e6Sdrh   }
22433fc673e6Sdrh 
22440bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
224563eb5f29Sdrh   ** iFrom-th entry of the FROM clause in the outer query.
2246832508b7Sdrh   */
2247c31c2eb8Sdrh 
2248c31c2eb8Sdrh   /* Move all of the FROM elements of the subquery into the
2249c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
2250c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
2251c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
2252c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
2253c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
2254c31c2eb8Sdrh   ** elements we are now copying in.
2255c31c2eb8Sdrh   */
225691bb0eedSdrh   iParent = pSubitem->iCursor;
2257c31c2eb8Sdrh   {
2258c31c2eb8Sdrh     int nSubSrc = pSubSrc->nSrc;
225991bb0eedSdrh     int jointype = pSubitem->jointype;
2260c31c2eb8Sdrh 
2261a04a34ffSdanielk1977     sqlite3DeleteTable(pSubitem->pTab);
226291bb0eedSdrh     sqliteFree(pSubitem->zDatabase);
226391bb0eedSdrh     sqliteFree(pSubitem->zName);
226491bb0eedSdrh     sqliteFree(pSubitem->zAlias);
2265c31c2eb8Sdrh     if( nSubSrc>1 ){
2266c31c2eb8Sdrh       int extra = nSubSrc - 1;
2267c31c2eb8Sdrh       for(i=1; i<nSubSrc; i++){
22684adee20fSdanielk1977         pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
2269c31c2eb8Sdrh       }
2270c31c2eb8Sdrh       p->pSrc = pSrc;
2271c31c2eb8Sdrh       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2272c31c2eb8Sdrh         pSrc->a[i] = pSrc->a[i-extra];
2273c31c2eb8Sdrh       }
2274c31c2eb8Sdrh     }
2275c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
2276c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
2277c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2278c31c2eb8Sdrh     }
227961dfc31dSdrh     pSrc->a[iFrom].jointype = jointype;
2280c31c2eb8Sdrh   }
2281c31c2eb8Sdrh 
2282c31c2eb8Sdrh   /* Now begin substituting subquery result set expressions for
2283c31c2eb8Sdrh   ** references to the iParent in the outer query.
2284c31c2eb8Sdrh   **
2285c31c2eb8Sdrh   ** Example:
2286c31c2eb8Sdrh   **
2287c31c2eb8Sdrh   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2288c31c2eb8Sdrh   **   \                     \_____________ subquery __________/          /
2289c31c2eb8Sdrh   **    \_____________________ outer query ______________________________/
2290c31c2eb8Sdrh   **
2291c31c2eb8Sdrh   ** We look at every expression in the outer query and every place we see
2292c31c2eb8Sdrh   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2293c31c2eb8Sdrh   */
2294832508b7Sdrh   pList = p->pEList;
2295832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
22966977fea8Sdrh     Expr *pExpr;
22976977fea8Sdrh     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
22982646da7eSdrh       pList->a[i].zName = sqliteStrNDup((char*)pExpr->span.z, pExpr->span.n);
2299832508b7Sdrh     }
2300832508b7Sdrh   }
2301643054c1Sdrh   substExprList(p->pEList, iParent, pSub->pEList);
23021b2e0329Sdrh   if( isAgg ){
23036a3ea0e6Sdrh     substExprList(p->pGroupBy, iParent, pSub->pEList);
23046a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
23051b2e0329Sdrh   }
2306174b6195Sdrh   if( pSub->pOrderBy ){
2307174b6195Sdrh     assert( p->pOrderBy==0 );
2308174b6195Sdrh     p->pOrderBy = pSub->pOrderBy;
2309174b6195Sdrh     pSub->pOrderBy = 0;
2310174b6195Sdrh   }else if( p->pOrderBy ){
23116a3ea0e6Sdrh     substExprList(p->pOrderBy, iParent, pSub->pEList);
2312174b6195Sdrh   }
2313832508b7Sdrh   if( pSub->pWhere ){
23144adee20fSdanielk1977     pWhere = sqlite3ExprDup(pSub->pWhere);
2315832508b7Sdrh   }else{
2316832508b7Sdrh     pWhere = 0;
2317832508b7Sdrh   }
2318832508b7Sdrh   if( subqueryIsAgg ){
2319832508b7Sdrh     assert( p->pHaving==0 );
23201b2e0329Sdrh     p->pHaving = p->pWhere;
23211b2e0329Sdrh     p->pWhere = pWhere;
23226a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
232391bb0eedSdrh     p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
23241b2e0329Sdrh     assert( p->pGroupBy==0 );
23254adee20fSdanielk1977     p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
2326832508b7Sdrh   }else{
23276a3ea0e6Sdrh     substExpr(p->pWhere, iParent, pSub->pEList);
232891bb0eedSdrh     p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
2329832508b7Sdrh   }
2330c31c2eb8Sdrh 
2331c31c2eb8Sdrh   /* The flattened query is distinct if either the inner or the
2332c31c2eb8Sdrh   ** outer query is distinct.
2333c31c2eb8Sdrh   */
2334832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
23358c74a8caSdrh 
2336a58fdfb1Sdanielk1977   /*
2337a58fdfb1Sdanielk1977   ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2338ac83963aSdrh   **
2339ac83963aSdrh   ** One is tempted to try to add a and b to combine the limits.  But this
2340ac83963aSdrh   ** does not work if either limit is negative.
2341a58fdfb1Sdanielk1977   */
2342a2dc3b1aSdanielk1977   if( pSub->pLimit ){
2343a2dc3b1aSdanielk1977     p->pLimit = pSub->pLimit;
2344a2dc3b1aSdanielk1977     pSub->pLimit = 0;
2345df199a25Sdrh   }
23468c74a8caSdrh 
2347c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
2348c31c2eb8Sdrh   ** success.
2349c31c2eb8Sdrh   */
23504adee20fSdanielk1977   sqlite3SelectDelete(pSub);
2351832508b7Sdrh   return 1;
23521350b030Sdrh }
2353b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */
23541350b030Sdrh 
23551350b030Sdrh /*
23569562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it
23579562b551Sdrh ** is a simple min() or max() query.  If it is and this query can be
23589562b551Sdrh ** satisfied using a single seek to the beginning or end of an index,
2359e78e8284Sdrh ** then generate the code for this SELECT and return 1.  If this is not a
23609562b551Sdrh ** simple min() or max() query, then return 0;
23619562b551Sdrh **
23629562b551Sdrh ** A simply min() or max() query looks like this:
23639562b551Sdrh **
23649562b551Sdrh **    SELECT min(a) FROM table;
23659562b551Sdrh **    SELECT max(a) FROM table;
23669562b551Sdrh **
23679562b551Sdrh ** The query may have only a single table in its FROM argument.  There
23689562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
23699562b551Sdrh ** be the min() or max() of a single column of the table.  The column
23709562b551Sdrh ** in the min() or max() function must be indexed.
23719562b551Sdrh **
23724adee20fSdanielk1977 ** The parameters to this routine are the same as for sqlite3Select().
23739562b551Sdrh ** See the header comment on that routine for additional information.
23749562b551Sdrh */
23759562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
23769562b551Sdrh   Expr *pExpr;
23779562b551Sdrh   int iCol;
23789562b551Sdrh   Table *pTab;
23799562b551Sdrh   Index *pIdx;
23809562b551Sdrh   int base;
23819562b551Sdrh   Vdbe *v;
23829562b551Sdrh   int seekOp;
23836e17529eSdrh   ExprList *pEList, *pList, eList;
23849562b551Sdrh   struct ExprList_item eListItem;
23856e17529eSdrh   SrcList *pSrc;
2386ec7429aeSdrh   int brk;
2387da184236Sdanielk1977   int iDb;
23886e17529eSdrh 
23899562b551Sdrh   /* Check to see if this query is a simple min() or max() query.  Return
23909562b551Sdrh   ** zero if it is  not.
23919562b551Sdrh   */
23929562b551Sdrh   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
23936e17529eSdrh   pSrc = p->pSrc;
23946e17529eSdrh   if( pSrc->nSrc!=1 ) return 0;
23956e17529eSdrh   pEList = p->pEList;
23966e17529eSdrh   if( pEList->nExpr!=1 ) return 0;
23976e17529eSdrh   pExpr = pEList->a[0].pExpr;
23989562b551Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
23996e17529eSdrh   pList = pExpr->pList;
24006e17529eSdrh   if( pList==0 || pList->nExpr!=1 ) return 0;
24016977fea8Sdrh   if( pExpr->token.n!=3 ) return 0;
24022646da7eSdrh   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
24030bce8354Sdrh     seekOp = OP_Rewind;
24042646da7eSdrh   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
24050bce8354Sdrh     seekOp = OP_Last;
24060bce8354Sdrh   }else{
24070bce8354Sdrh     return 0;
24080bce8354Sdrh   }
24096e17529eSdrh   pExpr = pList->a[0].pExpr;
24109562b551Sdrh   if( pExpr->op!=TK_COLUMN ) return 0;
24119562b551Sdrh   iCol = pExpr->iColumn;
24126e17529eSdrh   pTab = pSrc->a[0].pTab;
24139562b551Sdrh 
2414a41c7497Sdanielk1977   /* This optimization cannot be used with virtual tables. */
2415a41c7497Sdanielk1977   if( IsVirtual(pTab) ) return 0;
2416c00da105Sdanielk1977 
24179562b551Sdrh   /* If we get to here, it means the query is of the correct form.
241817f71934Sdrh   ** Check to make sure we have an index and make pIdx point to the
241917f71934Sdrh   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
242017f71934Sdrh   ** key column, no index is necessary so set pIdx to NULL.  If no
242117f71934Sdrh   ** usable index is found, return 0.
24229562b551Sdrh   */
24239562b551Sdrh   if( iCol<0 ){
24249562b551Sdrh     pIdx = 0;
24259562b551Sdrh   }else{
2426dc1bdc4fSdanielk1977     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
2427206f3d96Sdrh     if( pColl==0 ) return 0;
24289562b551Sdrh     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
24299562b551Sdrh       assert( pIdx->nColumn>=1 );
2430b3bf556eSdanielk1977       if( pIdx->aiColumn[0]==iCol &&
2431b3bf556eSdanielk1977           0==sqlite3StrICmp(pIdx->azColl[0], pColl->zName) ){
2432b3bf556eSdanielk1977         break;
2433b3bf556eSdanielk1977       }
24349562b551Sdrh     }
24359562b551Sdrh     if( pIdx==0 ) return 0;
24369562b551Sdrh   }
24379562b551Sdrh 
2438e5f50722Sdrh   /* Identify column types if we will be using the callback.  This
24399562b551Sdrh   ** step is skipped if the output is going to a table or a memory cell.
2440e5f50722Sdrh   ** The column names have already been generated in the calling function.
24419562b551Sdrh   */
24424adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
24439562b551Sdrh   if( v==0 ) return 0;
24449562b551Sdrh 
24450c37e630Sdrh   /* If the output is destined for a temporary table, open that table.
24460c37e630Sdrh   */
2447b9bb7c18Sdrh   if( eDest==SRT_EphemTab ){
2448b9bb7c18Sdrh     sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 1);
24490c37e630Sdrh   }
24500c37e630Sdrh 
245117f71934Sdrh   /* Generating code to find the min or the max.  Basically all we have
245217f71934Sdrh   ** to do is find the first or the last entry in the chosen index.  If
245317f71934Sdrh   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
245417f71934Sdrh   ** or last entry in the main table.
24559562b551Sdrh   */
2456da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2457b9bb7c18Sdrh   assert( iDb>=0 || pTab->isEphem );
2458da184236Sdanielk1977   sqlite3CodeVerifySchema(pParse, iDb);
2459c00da105Sdanielk1977   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
24606e17529eSdrh   base = pSrc->a[0].iCursor;
2461ec7429aeSdrh   brk = sqlite3VdbeMakeLabel(v);
2462ec7429aeSdrh   computeLimitRegisters(pParse, p, brk);
24636e17529eSdrh   if( pSrc->a[0].pSelect==0 ){
2464c00da105Sdanielk1977     sqlite3OpenTable(pParse, base, iDb, pTab, OP_OpenRead);
24656e17529eSdrh   }
24669562b551Sdrh   if( pIdx==0 ){
24674adee20fSdanielk1977     sqlite3VdbeAddOp(v, seekOp, base, 0);
24689562b551Sdrh   }else{
24693719d7f9Sdanielk1977     /* Even though the cursor used to open the index here is closed
24703719d7f9Sdanielk1977     ** as soon as a single value has been read from it, allocate it
24713719d7f9Sdanielk1977     ** using (pParse->nTab++) to prevent the cursor id from being
24723719d7f9Sdanielk1977     ** reused. This is important for statements of the form
24733719d7f9Sdanielk1977     ** "INSERT INTO x SELECT max() FROM x".
24743719d7f9Sdanielk1977     */
24753719d7f9Sdanielk1977     int iIdx;
2476b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
24773719d7f9Sdanielk1977     iIdx = pParse->nTab++;
2478da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
2479da184236Sdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
24803719d7f9Sdanielk1977     sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
2481b3bf556eSdanielk1977         (char*)pKey, P3_KEYINFO_HANDOFF);
24829eb516c0Sdrh     if( seekOp==OP_Rewind ){
2483f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
24841af3fdb4Sdrh       sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
24851af3fdb4Sdrh       seekOp = OP_MoveGt;
24869eb516c0Sdrh     }
24873719d7f9Sdanielk1977     sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
2488f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
24893719d7f9Sdanielk1977     sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
24907cf6e4deSdrh     sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
24919562b551Sdrh   }
24925cf8e8c7Sdrh   eList.nExpr = 1;
24935cf8e8c7Sdrh   memset(&eListItem, 0, sizeof(eListItem));
24945cf8e8c7Sdrh   eList.a = &eListItem;
24955cf8e8c7Sdrh   eList.a[0].pExpr = pExpr;
2496ec7429aeSdrh   selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0);
2497ec7429aeSdrh   sqlite3VdbeResolveLabel(v, brk);
24984adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Close, base, 0);
24996e17529eSdrh 
25009562b551Sdrh   return 1;
25019562b551Sdrh }
25029562b551Sdrh 
25039562b551Sdrh /*
2504290c1948Sdrh ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement.  Return
2505290c1948Sdrh ** the number of errors seen.
2506290c1948Sdrh **
2507290c1948Sdrh ** An ORDER BY or GROUP BY is a list of expressions.  If any expression
2508290c1948Sdrh ** is an integer constant, then that expression is replaced by the
2509290c1948Sdrh ** corresponding entry in the result set.
2510290c1948Sdrh */
2511290c1948Sdrh static int processOrderGroupBy(
2512b3bce662Sdanielk1977   NameContext *pNC,     /* Name context of the SELECT statement. */
2513290c1948Sdrh   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
2514290c1948Sdrh   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
2515290c1948Sdrh ){
2516290c1948Sdrh   int i;
2517b3bce662Sdanielk1977   ExprList *pEList = pNC->pEList;     /* The result set of the SELECT */
2518b3bce662Sdanielk1977   Parse *pParse = pNC->pParse;     /* The result set of the SELECT */
2519b3bce662Sdanielk1977   assert( pEList );
2520b3bce662Sdanielk1977 
2521290c1948Sdrh   if( pOrderBy==0 ) return 0;
2522e5c941b8Sdrh   if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){
2523e5c941b8Sdrh     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
2524e5c941b8Sdrh     return 1;
2525e5c941b8Sdrh   }
2526290c1948Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
2527290c1948Sdrh     int iCol;
2528290c1948Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
2529b3bce662Sdanielk1977     if( sqlite3ExprIsInteger(pE, &iCol) ){
2530b3bce662Sdanielk1977       if( iCol>0 && iCol<=pEList->nExpr ){
25318b4c40d8Sdrh         CollSeq *pColl = pE->pColl;
25328b4c40d8Sdrh         int flags = pE->flags & EP_ExpCollate;
2533290c1948Sdrh         sqlite3ExprDelete(pE);
2534290c1948Sdrh         pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
25358b4c40d8Sdrh         if( pColl && flags ){
25368b4c40d8Sdrh           pE->pColl = pColl;
25378b4c40d8Sdrh           pE->flags |= flags;
25388b4c40d8Sdrh         }
2539b3bce662Sdanielk1977       }else{
2540290c1948Sdrh         sqlite3ErrorMsg(pParse,
2541290c1948Sdrh            "%s BY column number %d out of range - should be "
2542290c1948Sdrh            "between 1 and %d", zType, iCol, pEList->nExpr);
2543290c1948Sdrh         return 1;
2544290c1948Sdrh       }
2545290c1948Sdrh     }
2546b3bce662Sdanielk1977     if( sqlite3ExprResolveNames(pNC, pE) ){
2547b3bce662Sdanielk1977       return 1;
2548b3bce662Sdanielk1977     }
2549290c1948Sdrh   }
2550290c1948Sdrh   return 0;
2551290c1948Sdrh }
2552290c1948Sdrh 
2553290c1948Sdrh /*
2554b3bce662Sdanielk1977 ** This routine resolves any names used in the result set of the
2555b3bce662Sdanielk1977 ** supplied SELECT statement. If the SELECT statement being resolved
2556b3bce662Sdanielk1977 ** is a sub-select, then pOuterNC is a pointer to the NameContext
2557b3bce662Sdanielk1977 ** of the parent SELECT.
2558b3bce662Sdanielk1977 */
2559b3bce662Sdanielk1977 int sqlite3SelectResolve(
2560b3bce662Sdanielk1977   Parse *pParse,         /* The parser context */
2561b3bce662Sdanielk1977   Select *p,             /* The SELECT statement being coded. */
2562b3bce662Sdanielk1977   NameContext *pOuterNC  /* The outer name context. May be NULL. */
2563b3bce662Sdanielk1977 ){
2564b3bce662Sdanielk1977   ExprList *pEList;          /* Result set. */
2565b3bce662Sdanielk1977   int i;                     /* For-loop variable used in multiple places */
2566b3bce662Sdanielk1977   NameContext sNC;           /* Local name-context */
256713449892Sdrh   ExprList *pGroupBy;        /* The group by clause */
2568b3bce662Sdanielk1977 
2569b3bce662Sdanielk1977   /* If this routine has run before, return immediately. */
2570b3bce662Sdanielk1977   if( p->isResolved ){
2571b3bce662Sdanielk1977     assert( !pOuterNC );
2572b3bce662Sdanielk1977     return SQLITE_OK;
2573b3bce662Sdanielk1977   }
2574b3bce662Sdanielk1977   p->isResolved = 1;
2575b3bce662Sdanielk1977 
2576b3bce662Sdanielk1977   /* If there have already been errors, do nothing. */
2577b3bce662Sdanielk1977   if( pParse->nErr>0 ){
2578b3bce662Sdanielk1977     return SQLITE_ERROR;
2579b3bce662Sdanielk1977   }
2580b3bce662Sdanielk1977 
2581b3bce662Sdanielk1977   /* Prepare the select statement. This call will allocate all cursors
2582b3bce662Sdanielk1977   ** required to handle the tables and subqueries in the FROM clause.
2583b3bce662Sdanielk1977   */
2584b3bce662Sdanielk1977   if( prepSelectStmt(pParse, p) ){
2585b3bce662Sdanielk1977     return SQLITE_ERROR;
2586b3bce662Sdanielk1977   }
2587b3bce662Sdanielk1977 
2588a2dc3b1aSdanielk1977   /* Resolve the expressions in the LIMIT and OFFSET clauses. These
2589a2dc3b1aSdanielk1977   ** are not allowed to refer to any names, so pass an empty NameContext.
2590a2dc3b1aSdanielk1977   */
2591ffe07b2dSdrh   memset(&sNC, 0, sizeof(sNC));
2592b3bce662Sdanielk1977   sNC.pParse = pParse;
2593a2dc3b1aSdanielk1977   if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2594a2dc3b1aSdanielk1977       sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2595a2dc3b1aSdanielk1977     return SQLITE_ERROR;
2596a2dc3b1aSdanielk1977   }
2597a2dc3b1aSdanielk1977 
2598a2dc3b1aSdanielk1977   /* Set up the local name-context to pass to ExprResolveNames() to
2599a2dc3b1aSdanielk1977   ** resolve the expression-list.
2600a2dc3b1aSdanielk1977   */
2601a2dc3b1aSdanielk1977   sNC.allowAgg = 1;
2602a2dc3b1aSdanielk1977   sNC.pSrcList = p->pSrc;
2603a2dc3b1aSdanielk1977   sNC.pNext = pOuterNC;
2604b3bce662Sdanielk1977 
2605b3bce662Sdanielk1977   /* Resolve names in the result set. */
2606b3bce662Sdanielk1977   pEList = p->pEList;
2607b3bce662Sdanielk1977   if( !pEList ) return SQLITE_ERROR;
2608b3bce662Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
2609b3bce662Sdanielk1977     Expr *pX = pEList->a[i].pExpr;
2610b3bce662Sdanielk1977     if( sqlite3ExprResolveNames(&sNC, pX) ){
2611b3bce662Sdanielk1977       return SQLITE_ERROR;
2612b3bce662Sdanielk1977     }
2613b3bce662Sdanielk1977   }
2614b3bce662Sdanielk1977 
2615b3bce662Sdanielk1977   /* If there are no aggregate functions in the result-set, and no GROUP BY
2616b3bce662Sdanielk1977   ** expression, do not allow aggregates in any of the other expressions.
2617b3bce662Sdanielk1977   */
2618b3bce662Sdanielk1977   assert( !p->isAgg );
261913449892Sdrh   pGroupBy = p->pGroupBy;
262013449892Sdrh   if( pGroupBy || sNC.hasAgg ){
2621b3bce662Sdanielk1977     p->isAgg = 1;
2622b3bce662Sdanielk1977   }else{
2623b3bce662Sdanielk1977     sNC.allowAgg = 0;
2624b3bce662Sdanielk1977   }
2625b3bce662Sdanielk1977 
2626b3bce662Sdanielk1977   /* If a HAVING clause is present, then there must be a GROUP BY clause.
2627b3bce662Sdanielk1977   */
262813449892Sdrh   if( p->pHaving && !pGroupBy ){
2629b3bce662Sdanielk1977     sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2630b3bce662Sdanielk1977     return SQLITE_ERROR;
2631b3bce662Sdanielk1977   }
2632b3bce662Sdanielk1977 
2633b3bce662Sdanielk1977   /* Add the expression list to the name-context before parsing the
2634b3bce662Sdanielk1977   ** other expressions in the SELECT statement. This is so that
2635b3bce662Sdanielk1977   ** expressions in the WHERE clause (etc.) can refer to expressions by
2636b3bce662Sdanielk1977   ** aliases in the result set.
2637b3bce662Sdanielk1977   **
2638b3bce662Sdanielk1977   ** Minor point: If this is the case, then the expression will be
2639b3bce662Sdanielk1977   ** re-evaluated for each reference to it.
2640b3bce662Sdanielk1977   */
2641b3bce662Sdanielk1977   sNC.pEList = p->pEList;
2642b3bce662Sdanielk1977   if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2643994c80afSdrh      sqlite3ExprResolveNames(&sNC, p->pHaving) ){
2644b3bce662Sdanielk1977     return SQLITE_ERROR;
2645b3bce662Sdanielk1977   }
2646994c80afSdrh   if( p->pPrior==0 ){
2647994c80afSdrh     if( processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
2648994c80afSdrh         processOrderGroupBy(&sNC, pGroupBy, "GROUP") ){
2649994c80afSdrh       return SQLITE_ERROR;
2650994c80afSdrh     }
2651994c80afSdrh   }
2652b3bce662Sdanielk1977 
265313449892Sdrh   /* Make sure the GROUP BY clause does not contain aggregate functions.
265413449892Sdrh   */
265513449892Sdrh   if( pGroupBy ){
265613449892Sdrh     struct ExprList_item *pItem;
265713449892Sdrh 
265813449892Sdrh     for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
265913449892Sdrh       if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
266013449892Sdrh         sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
266113449892Sdrh             "the GROUP BY clause");
266213449892Sdrh         return SQLITE_ERROR;
266313449892Sdrh       }
266413449892Sdrh     }
266513449892Sdrh   }
266613449892Sdrh 
2667f6bbe022Sdrh   /* If this is one SELECT of a compound, be sure to resolve names
2668f6bbe022Sdrh   ** in the other SELECTs.
2669f6bbe022Sdrh   */
2670f6bbe022Sdrh   if( p->pPrior ){
2671f6bbe022Sdrh     return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC);
2672f6bbe022Sdrh   }else{
2673b3bce662Sdanielk1977     return SQLITE_OK;
2674b3bce662Sdanielk1977   }
2675f6bbe022Sdrh }
2676b3bce662Sdanielk1977 
2677b3bce662Sdanielk1977 /*
267813449892Sdrh ** Reset the aggregate accumulator.
267913449892Sdrh **
268013449892Sdrh ** The aggregate accumulator is a set of memory cells that hold
268113449892Sdrh ** intermediate results while calculating an aggregate.  This
268213449892Sdrh ** routine simply stores NULLs in all of those memory cells.
2683b3bce662Sdanielk1977 */
268413449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
268513449892Sdrh   Vdbe *v = pParse->pVdbe;
268613449892Sdrh   int i;
2687c99130fdSdrh   struct AggInfo_func *pFunc;
268813449892Sdrh   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
268913449892Sdrh     return;
269013449892Sdrh   }
269113449892Sdrh   for(i=0; i<pAggInfo->nColumn; i++){
2692d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0);
269313449892Sdrh   }
2694c99130fdSdrh   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
2695d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0);
2696c99130fdSdrh     if( pFunc->iDistinct>=0 ){
2697c99130fdSdrh       Expr *pE = pFunc->pExpr;
2698c99130fdSdrh       if( pE->pList==0 || pE->pList->nExpr!=1 ){
2699c99130fdSdrh         sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
2700c99130fdSdrh            "by an expression");
2701c99130fdSdrh         pFunc->iDistinct = -1;
2702c99130fdSdrh       }else{
2703c99130fdSdrh         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
2704b9bb7c18Sdrh         sqlite3VdbeOp3(v, OP_OpenEphemeral, pFunc->iDistinct, 0,
2705c99130fdSdrh                           (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
2706c99130fdSdrh       }
2707c99130fdSdrh     }
270813449892Sdrh   }
2709b3bce662Sdanielk1977 }
2710b3bce662Sdanielk1977 
2711b3bce662Sdanielk1977 /*
271213449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function
271313449892Sdrh ** in the AggInfo structure.
2714b3bce662Sdanielk1977 */
271513449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
271613449892Sdrh   Vdbe *v = pParse->pVdbe;
271713449892Sdrh   int i;
271813449892Sdrh   struct AggInfo_func *pF;
271913449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
2720a10a34b8Sdrh     ExprList *pList = pF->pExpr->pList;
2721a10a34b8Sdrh     sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0,
2722a10a34b8Sdrh                       (void*)pF->pFunc, P3_FUNCDEF);
2723b3bce662Sdanielk1977   }
272413449892Sdrh }
272513449892Sdrh 
272613449892Sdrh /*
272713449892Sdrh ** Update the accumulator memory cells for an aggregate based on
272813449892Sdrh ** the current cursor position.
272913449892Sdrh */
273013449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
273113449892Sdrh   Vdbe *v = pParse->pVdbe;
273213449892Sdrh   int i;
273313449892Sdrh   struct AggInfo_func *pF;
273413449892Sdrh   struct AggInfo_col *pC;
273513449892Sdrh 
273613449892Sdrh   pAggInfo->directMode = 1;
273713449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
273813449892Sdrh     int nArg;
2739c99130fdSdrh     int addrNext = 0;
274013449892Sdrh     ExprList *pList = pF->pExpr->pList;
274113449892Sdrh     if( pList ){
274213449892Sdrh       nArg = pList->nExpr;
274313449892Sdrh       sqlite3ExprCodeExprList(pParse, pList);
274413449892Sdrh     }else{
274513449892Sdrh       nArg = 0;
274613449892Sdrh     }
2747c99130fdSdrh     if( pF->iDistinct>=0 ){
2748c99130fdSdrh       addrNext = sqlite3VdbeMakeLabel(v);
2749c99130fdSdrh       assert( nArg==1 );
2750f8875400Sdrh       codeDistinct(v, pF->iDistinct, addrNext, 1);
2751c99130fdSdrh     }
275213449892Sdrh     if( pF->pFunc->needCollSeq ){
275313449892Sdrh       CollSeq *pColl = 0;
275413449892Sdrh       struct ExprList_item *pItem;
275513449892Sdrh       int j;
275643617e9aSdrh       assert( pList!=0 );  /* pList!=0 if pF->pFunc->needCollSeq is true */
275743617e9aSdrh       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
275813449892Sdrh         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
275913449892Sdrh       }
276013449892Sdrh       if( !pColl ){
276113449892Sdrh         pColl = pParse->db->pDfltColl;
276213449892Sdrh       }
276313449892Sdrh       sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
276413449892Sdrh     }
276513449892Sdrh     sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF);
2766c99130fdSdrh     if( addrNext ){
2767c99130fdSdrh       sqlite3VdbeResolveLabel(v, addrNext);
2768c99130fdSdrh     }
276913449892Sdrh   }
277013449892Sdrh   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
27715774b806Sdrh     sqlite3ExprCode(pParse, pC->pExpr);
277213449892Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1);
277313449892Sdrh   }
277413449892Sdrh   pAggInfo->directMode = 0;
277513449892Sdrh }
277613449892Sdrh 
2777b3bce662Sdanielk1977 
2778b3bce662Sdanielk1977 /*
27799bb61fe7Sdrh ** Generate code for the given SELECT statement.
27809bb61fe7Sdrh **
2781fef5208cSdrh ** The results are distributed in various ways depending on the
2782fef5208cSdrh ** value of eDest and iParm.
2783fef5208cSdrh **
2784fef5208cSdrh **     eDest Value       Result
2785fef5208cSdrh **     ------------    -------------------------------------------
2786fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
2787fef5208cSdrh **
2788fef5208cSdrh **     SRT_Mem         Store first result in memory cell iParm
2789fef5208cSdrh **
2790e014a838Sdanielk1977 **     SRT_Set         Store results as keys of table iParm.
2791fef5208cSdrh **
279282c3d636Sdrh **     SRT_Union       Store results as a key in a temporary table iParm
279382c3d636Sdrh **
27944b11c6d3Sjplyon **     SRT_Except      Remove results from the temporary table iParm.
2795c4a3c779Sdrh **
2796c4a3c779Sdrh **     SRT_Table       Store results in temporary table iParm
27979bb61fe7Sdrh **
2798e78e8284Sdrh ** The table above is incomplete.  Additional eDist value have be added
2799e78e8284Sdrh ** since this comment was written.  See the selectInnerLoop() function for
2800e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings.
2801e78e8284Sdrh **
28029bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
28039bb61fe7Sdrh ** encountered, then an appropriate error message is left in
28049bb61fe7Sdrh ** pParse->zErrMsg.
28059bb61fe7Sdrh **
28069bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
28079bb61fe7Sdrh ** calling function needs to do that.
28081b2e0329Sdrh **
28091b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
28101b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
28111b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
28121b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
28131b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
28141b2e0329Sdrh ** can be changed.
2815e78e8284Sdrh **
2816e78e8284Sdrh ** Example 1:   The meaning of the pParent parameter.
2817e78e8284Sdrh **
2818e78e8284Sdrh **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2819e78e8284Sdrh **    \                      \_______ subquery _______/        /
2820e78e8284Sdrh **     \                                                      /
2821e78e8284Sdrh **      \____________________ outer query ___________________/
2822e78e8284Sdrh **
2823e78e8284Sdrh ** This routine is called for the outer query first.   For that call,
2824e78e8284Sdrh ** pParent will be NULL.  During the processing of the outer query, this
2825e78e8284Sdrh ** routine is called recursively to handle the subquery.  For the recursive
2826e78e8284Sdrh ** call, pParent will point to the outer query.  Because the subquery is
2827e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will
2828e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.)
28299bb61fe7Sdrh */
28304adee20fSdanielk1977 int sqlite3Select(
2831cce7d176Sdrh   Parse *pParse,         /* The parser context */
28329bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
2833e78e8284Sdrh   int eDest,             /* How to dispose of the results */
2834e78e8284Sdrh   int iParm,             /* A parameter used by the eDest disposal method */
2835832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
2836832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
283784ac9d02Sdanielk1977   int *pParentAgg,       /* True if pParent uses aggregate functions */
2838b3bce662Sdanielk1977   char *aff              /* If eDest is SRT_Union, the affinity string */
2839cce7d176Sdrh ){
284013449892Sdrh   int i, j;              /* Loop counters */
284113449892Sdrh   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
284213449892Sdrh   Vdbe *v;               /* The virtual machine under construction */
2843b3bce662Sdanielk1977   int isAgg;             /* True for select lists like "count(*)" */
2844a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
2845ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
28469bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
28479bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
28482282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
28492282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
285019a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
285119a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
28521d83f052Sdrh   int rc = 1;            /* Value to return from this function */
2853b9bb7c18Sdrh   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
285413449892Sdrh   AggInfo sAggInfo;      /* Information used by aggregate queries */
2855ec7429aeSdrh   int iEnd;              /* Address of the end of the query */
28569bb61fe7Sdrh 
28579e12800dSdanielk1977   if( p==0 || sqlite3MallocFailed() || pParse->nErr ){
28586f7adc8aSdrh     return 1;
28596f7adc8aSdrh   }
28604adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
286113449892Sdrh   memset(&sAggInfo, 0, sizeof(sAggInfo));
2862daffd0e5Sdrh 
2863b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
286482c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
286582c3d636Sdrh   */
286682c3d636Sdrh   if( p->pPrior ){
28670342b1f5Sdrh     if( p->pRightmost==0 ){
28680342b1f5Sdrh       Select *pLoop;
28690342b1f5Sdrh       for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
28700342b1f5Sdrh         pLoop->pRightmost = p;
28710342b1f5Sdrh       }
28720342b1f5Sdrh     }
287384ac9d02Sdanielk1977     return multiSelect(pParse, p, eDest, iParm, aff);
287482c3d636Sdrh   }
2875b7f9164eSdrh #endif
287682c3d636Sdrh 
2877b3bce662Sdanielk1977   pOrderBy = p->pOrderBy;
287813449892Sdrh   if( IgnorableOrderby(eDest) ){
2879b3bce662Sdanielk1977     p->pOrderBy = 0;
2880b3bce662Sdanielk1977   }
2881b3bce662Sdanielk1977   if( sqlite3SelectResolve(pParse, p, 0) ){
2882b3bce662Sdanielk1977     goto select_end;
2883b3bce662Sdanielk1977   }
2884b3bce662Sdanielk1977   p->pOrderBy = pOrderBy;
2885b3bce662Sdanielk1977 
288682c3d636Sdrh   /* Make local copies of the parameters for this query.
288782c3d636Sdrh   */
28889bb61fe7Sdrh   pTabList = p->pSrc;
28899bb61fe7Sdrh   pWhere = p->pWhere;
28902282792aSdrh   pGroupBy = p->pGroupBy;
28912282792aSdrh   pHaving = p->pHaving;
2892b3bce662Sdanielk1977   isAgg = p->isAgg;
289319a775c2Sdrh   isDistinct = p->isDistinct;
2894b3bce662Sdanielk1977   pEList = p->pEList;
2895b3bce662Sdanielk1977   if( pEList==0 ) goto select_end;
28969bb61fe7Sdrh 
28979bb61fe7Sdrh   /*
28989bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
28999bb61fe7Sdrh   ** errors before this routine starts.
29009bb61fe7Sdrh   */
29011d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
2902cce7d176Sdrh 
29032282792aSdrh   /* If writing to memory or generating a set
29042282792aSdrh   ** only a single column may be output.
290519a775c2Sdrh   */
290693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
2907e305f43fSdrh   if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){
29081d83f052Sdrh     goto select_end;
290919a775c2Sdrh   }
291093758c8dSdanielk1977 #endif
291119a775c2Sdrh 
2912c926afbcSdrh   /* ORDER BY is ignored for some destinations.
29132282792aSdrh   */
291413449892Sdrh   if( IgnorableOrderby(eDest) ){
2915acd4c695Sdrh     pOrderBy = 0;
29162282792aSdrh   }
29172282792aSdrh 
2918d820cb1bSdrh   /* Begin generating code.
2919d820cb1bSdrh   */
29204adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
2921d820cb1bSdrh   if( v==0 ) goto select_end;
2922d820cb1bSdrh 
2923d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
2924d820cb1bSdrh   */
292551522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
2926ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
2927742f947bSdanielk1977     const char *zSavedAuthContext = 0;
2928c31c2eb8Sdrh     int needRestoreContext;
292913449892Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
2930c31c2eb8Sdrh 
29311787ccabSdanielk1977     if( pItem->pSelect==0 || pItem->isPopulated ) continue;
293213449892Sdrh     if( pItem->zName!=0 ){
29335cf590c1Sdrh       zSavedAuthContext = pParse->zAuthContext;
293413449892Sdrh       pParse->zAuthContext = pItem->zName;
2935c31c2eb8Sdrh       needRestoreContext = 1;
2936c31c2eb8Sdrh     }else{
2937c31c2eb8Sdrh       needRestoreContext = 0;
29385cf590c1Sdrh     }
2939fc976065Sdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0
2940fc976065Sdanielk1977     /* Increment Parse.nHeight by the height of the largest expression
2941fc976065Sdanielk1977     ** tree refered to by this, the parent select. The child select
2942fc976065Sdanielk1977     ** may contain expression trees of at most
2943fc976065Sdanielk1977     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
2944fc976065Sdanielk1977     ** more conservative than necessary, but much easier than enforcing
2945fc976065Sdanielk1977     ** an exact limit.
2946fc976065Sdanielk1977     */
2947fc976065Sdanielk1977     pParse->nHeight += sqlite3SelectExprHeight(p);
2948fc976065Sdanielk1977 #endif
2949b9bb7c18Sdrh     sqlite3Select(pParse, pItem->pSelect, SRT_EphemTab,
295013449892Sdrh                  pItem->iCursor, p, i, &isAgg, 0);
2951fc976065Sdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0
2952fc976065Sdanielk1977     pParse->nHeight -= sqlite3SelectExprHeight(p);
2953fc976065Sdanielk1977 #endif
2954c31c2eb8Sdrh     if( needRestoreContext ){
29555cf590c1Sdrh       pParse->zAuthContext = zSavedAuthContext;
29565cf590c1Sdrh     }
2957832508b7Sdrh     pTabList = p->pSrc;
2958832508b7Sdrh     pWhere = p->pWhere;
295913449892Sdrh     if( !IgnorableOrderby(eDest) ){
2960832508b7Sdrh       pOrderBy = p->pOrderBy;
2961acd4c695Sdrh     }
2962832508b7Sdrh     pGroupBy = p->pGroupBy;
2963832508b7Sdrh     pHaving = p->pHaving;
2964832508b7Sdrh     isDistinct = p->isDistinct;
29651b2e0329Sdrh   }
296651522cd3Sdrh #endif
29671b2e0329Sdrh 
29686e17529eSdrh   /* Check for the special case of a min() or max() function by itself
29696e17529eSdrh   ** in the result set.
29706e17529eSdrh   */
29716e17529eSdrh   if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
29726e17529eSdrh     rc = 0;
29736e17529eSdrh     goto select_end;
29746e17529eSdrh   }
29756e17529eSdrh 
29761b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
29771b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
29781b2e0329Sdrh   */
2979b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
29801b2e0329Sdrh   if( pParent && pParentAgg &&
298174161705Sdrh       flattenSubquery(pParent, parentTab, *pParentAgg, isAgg) ){
29821b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
2983b3bce662Sdanielk1977     goto select_end;
29841b2e0329Sdrh   }
2985b7f9164eSdrh #endif
2986832508b7Sdrh 
29878b4c40d8Sdrh   /* If there is an ORDER BY clause, then this sorting
29888b4c40d8Sdrh   ** index might end up being unused if the data can be
29899d2985c7Sdrh   ** extracted in pre-sorted order.  If that is the case, then the
2990b9bb7c18Sdrh   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
29919d2985c7Sdrh   ** we figure out that the sorting index is not needed.  The addrSortIndex
29929d2985c7Sdrh   ** variable is used to facilitate that change.
29937cedc8d4Sdanielk1977   */
29947cedc8d4Sdanielk1977   if( pOrderBy ){
29950342b1f5Sdrh     KeyInfo *pKeyInfo;
29967cedc8d4Sdanielk1977     if( pParse->nErr ){
29977cedc8d4Sdanielk1977       goto select_end;
29987cedc8d4Sdanielk1977     }
29990342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
30009d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
3001b9bb7c18Sdrh     p->addrOpenEphm[2] = addrSortIndex =
30021e31e0b2Sdrh       sqlite3VdbeOp3(v, OP_OpenEphemeral, pOrderBy->iECursor, pOrderBy->nExpr+2,                     (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
30039d2985c7Sdrh   }else{
30049d2985c7Sdrh     addrSortIndex = -1;
30057cedc8d4Sdanielk1977   }
30067cedc8d4Sdanielk1977 
30072d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
30082d0794e3Sdrh   */
3009b9bb7c18Sdrh   if( eDest==SRT_EphemTab ){
3010b9bb7c18Sdrh     sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, pEList->nExpr);
30112d0794e3Sdrh   }
30122d0794e3Sdrh 
3013f42bacc2Sdrh   /* Set the limiter.
3014f42bacc2Sdrh   */
3015f42bacc2Sdrh   iEnd = sqlite3VdbeMakeLabel(v);
3016f42bacc2Sdrh   computeLimitRegisters(pParse, p, iEnd);
3017f42bacc2Sdrh 
3018dece1a84Sdrh   /* Open a virtual index to use for the distinct set.
3019cce7d176Sdrh   */
302019a775c2Sdrh   if( isDistinct ){
30210342b1f5Sdrh     KeyInfo *pKeyInfo;
3022832508b7Sdrh     distinct = pParse->nTab++;
30230342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
3024b9bb7c18Sdrh     sqlite3VdbeOp3(v, OP_OpenEphemeral, distinct, 0,
30250342b1f5Sdrh                         (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
3026832508b7Sdrh   }else{
3027832508b7Sdrh     distinct = -1;
3028efb7251dSdrh   }
3029832508b7Sdrh 
303013449892Sdrh   /* Aggregate and non-aggregate queries are handled differently */
303113449892Sdrh   if( !isAgg && pGroupBy==0 ){
303213449892Sdrh     /* This case is for non-aggregate queries
303313449892Sdrh     ** Begin the database scan
3034832508b7Sdrh     */
303513449892Sdrh     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy);
30361d83f052Sdrh     if( pWInfo==0 ) goto select_end;
3037cce7d176Sdrh 
3038b9bb7c18Sdrh     /* If sorting index that was created by a prior OP_OpenEphemeral
3039b9bb7c18Sdrh     ** instruction ended up not being needed, then change the OP_OpenEphemeral
30409d2985c7Sdrh     ** into an OP_Noop.
30419d2985c7Sdrh     */
30429d2985c7Sdrh     if( addrSortIndex>=0 && pOrderBy==0 ){
3043f8875400Sdrh       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
3044b9bb7c18Sdrh       p->addrOpenEphm[2] = -1;
30459d2985c7Sdrh     }
30469d2985c7Sdrh 
304713449892Sdrh     /* Use the standard inner loop
3048cce7d176Sdrh     */
3049df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
305084ac9d02Sdanielk1977                     iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
30511d83f052Sdrh        goto select_end;
3052cce7d176Sdrh     }
30532282792aSdrh 
3054cce7d176Sdrh     /* End the database scan loop.
3055cce7d176Sdrh     */
30564adee20fSdanielk1977     sqlite3WhereEnd(pWInfo);
305713449892Sdrh   }else{
305813449892Sdrh     /* This is the processing for aggregate queries */
305913449892Sdrh     NameContext sNC;    /* Name context for processing aggregate information */
306013449892Sdrh     int iAMem;          /* First Mem address for storing current GROUP BY */
306113449892Sdrh     int iBMem;          /* First Mem address for previous GROUP BY */
306213449892Sdrh     int iUseFlag;       /* Mem address holding flag indicating that at least
306313449892Sdrh                         ** one row of the input to the aggregator has been
306413449892Sdrh                         ** processed */
306513449892Sdrh     int iAbortFlag;     /* Mem address which causes query abort if positive */
306613449892Sdrh     int groupBySort;    /* Rows come from source in GROUP BY order */
3067cce7d176Sdrh 
306813449892Sdrh 
306913449892Sdrh     /* The following variables hold addresses or labels for parts of the
307013449892Sdrh     ** virtual machine program we are putting together */
307113449892Sdrh     int addrOutputRow;      /* Start of subroutine that outputs a result row */
307213449892Sdrh     int addrSetAbort;       /* Set the abort flag and return */
307313449892Sdrh     int addrInitializeLoop; /* Start of code that initializes the input loop */
307413449892Sdrh     int addrTopOfLoop;      /* Top of the input loop */
307513449892Sdrh     int addrGroupByChange;  /* Code that runs when any GROUP BY term changes */
307613449892Sdrh     int addrProcessRow;     /* Code to process a single input row */
307713449892Sdrh     int addrEnd;            /* End of all processing */
3078b9bb7c18Sdrh     int addrSortingIdx;     /* The OP_OpenEphemeral for the sorting index */
3079e313382eSdrh     int addrReset;          /* Subroutine for resetting the accumulator */
308013449892Sdrh 
308113449892Sdrh     addrEnd = sqlite3VdbeMakeLabel(v);
308213449892Sdrh 
308313449892Sdrh     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
308413449892Sdrh     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
308513449892Sdrh     ** SELECT statement.
30862282792aSdrh     */
308713449892Sdrh     memset(&sNC, 0, sizeof(sNC));
308813449892Sdrh     sNC.pParse = pParse;
308913449892Sdrh     sNC.pSrcList = pTabList;
309013449892Sdrh     sNC.pAggInfo = &sAggInfo;
309113449892Sdrh     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
30929d2985c7Sdrh     sAggInfo.pGroupBy = pGroupBy;
309313449892Sdrh     if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){
30941d83f052Sdrh       goto select_end;
30952282792aSdrh     }
309613449892Sdrh     if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){
309713449892Sdrh       goto select_end;
30982282792aSdrh     }
309913449892Sdrh     if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
310013449892Sdrh       goto select_end;
310113449892Sdrh     }
310213449892Sdrh     sAggInfo.nAccumulator = sAggInfo.nColumn;
310313449892Sdrh     for(i=0; i<sAggInfo.nFunc; i++){
310413449892Sdrh       if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
310513449892Sdrh         goto select_end;
310613449892Sdrh       }
310713449892Sdrh     }
31089e12800dSdanielk1977     if( sqlite3MallocFailed() ) goto select_end;
310913449892Sdrh 
311013449892Sdrh     /* Processing for aggregates with GROUP BY is very different and
311113449892Sdrh     ** much more complex tha aggregates without a GROUP BY.
311213449892Sdrh     */
311313449892Sdrh     if( pGroupBy ){
311413449892Sdrh       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
311513449892Sdrh 
311613449892Sdrh       /* Create labels that we will be needing
311713449892Sdrh       */
311813449892Sdrh 
311913449892Sdrh       addrInitializeLoop = sqlite3VdbeMakeLabel(v);
312013449892Sdrh       addrGroupByChange = sqlite3VdbeMakeLabel(v);
312113449892Sdrh       addrProcessRow = sqlite3VdbeMakeLabel(v);
312213449892Sdrh 
312313449892Sdrh       /* If there is a GROUP BY clause we might need a sorting index to
312413449892Sdrh       ** implement it.  Allocate that sorting index now.  If it turns out
3125b9bb7c18Sdrh       ** that we do not need it after all, the OpenEphemeral instruction
312613449892Sdrh       ** will be converted into a Noop.
312713449892Sdrh       */
312813449892Sdrh       sAggInfo.sortingIdx = pParse->nTab++;
312913449892Sdrh       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
313013449892Sdrh       addrSortingIdx =
3131b9bb7c18Sdrh           sqlite3VdbeOp3(v, OP_OpenEphemeral, sAggInfo.sortingIdx,
313213449892Sdrh                          sAggInfo.nSortingColumn,
313313449892Sdrh                          (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
313413449892Sdrh 
313513449892Sdrh       /* Initialize memory locations used by GROUP BY aggregate processing
313613449892Sdrh       */
313713449892Sdrh       iUseFlag = pParse->nMem++;
313813449892Sdrh       iAbortFlag = pParse->nMem++;
313913449892Sdrh       iAMem = pParse->nMem;
314013449892Sdrh       pParse->nMem += pGroupBy->nExpr;
314113449892Sdrh       iBMem = pParse->nMem;
314213449892Sdrh       pParse->nMem += pGroupBy->nExpr;
3143d654be80Sdrh       sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag);
3144de29e3e9Sdrh       VdbeComment((v, "# clear abort flag"));
3145d654be80Sdrh       sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag);
3146de29e3e9Sdrh       VdbeComment((v, "# indicate accumulator empty"));
314713449892Sdrh       sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop);
314813449892Sdrh 
314913449892Sdrh       /* Generate a subroutine that outputs a single row of the result
315013449892Sdrh       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
315113449892Sdrh       ** is less than or equal to zero, the subroutine is a no-op.  If
315213449892Sdrh       ** the processing calls for the query to abort, this subroutine
315313449892Sdrh       ** increments the iAbortFlag memory location before returning in
315413449892Sdrh       ** order to signal the caller to abort.
315513449892Sdrh       */
315613449892Sdrh       addrSetAbort = sqlite3VdbeCurrentAddr(v);
3157de29e3e9Sdrh       sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag);
3158de29e3e9Sdrh       VdbeComment((v, "# set abort flag"));
315913449892Sdrh       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
316013449892Sdrh       addrOutputRow = sqlite3VdbeCurrentAddr(v);
316113449892Sdrh       sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2);
3162de29e3e9Sdrh       VdbeComment((v, "# Groupby result generator entry point"));
316313449892Sdrh       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
316413449892Sdrh       finalizeAggFunctions(pParse, &sAggInfo);
316513449892Sdrh       if( pHaving ){
316613449892Sdrh         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1);
316713449892Sdrh       }
316813449892Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
316913449892Sdrh                            distinct, eDest, iParm,
317013449892Sdrh                            addrOutputRow+1, addrSetAbort, aff);
317113449892Sdrh       if( rc ){
317213449892Sdrh         goto select_end;
317313449892Sdrh       }
317413449892Sdrh       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
3175de29e3e9Sdrh       VdbeComment((v, "# end groupby result generator"));
317613449892Sdrh 
3177e313382eSdrh       /* Generate a subroutine that will reset the group-by accumulator
3178e313382eSdrh       */
3179e313382eSdrh       addrReset = sqlite3VdbeCurrentAddr(v);
3180e313382eSdrh       resetAccumulator(pParse, &sAggInfo);
3181e313382eSdrh       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
3182e313382eSdrh 
318313449892Sdrh       /* Begin a loop that will extract all source rows in GROUP BY order.
318413449892Sdrh       ** This might involve two separate loops with an OP_Sort in between, or
318513449892Sdrh       ** it might be a single loop that uses an index to extract information
318613449892Sdrh       ** in the right order to begin with.
318713449892Sdrh       */
318813449892Sdrh       sqlite3VdbeResolveLabel(v, addrInitializeLoop);
3189e313382eSdrh       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
319013449892Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy);
31915360ad34Sdrh       if( pWInfo==0 ) goto select_end;
319213449892Sdrh       if( pGroupBy==0 ){
319313449892Sdrh         /* The optimizer is able to deliver rows in group by order so
3194b9bb7c18Sdrh         ** we do not have to sort.  The OP_OpenEphemeral table will be
319513449892Sdrh         ** cancelled later because we still need to use the pKeyInfo
319613449892Sdrh         */
319713449892Sdrh         pGroupBy = p->pGroupBy;
319813449892Sdrh         groupBySort = 0;
319913449892Sdrh       }else{
320013449892Sdrh         /* Rows are coming out in undetermined order.  We have to push
320113449892Sdrh         ** each row into a sorting index, terminate the first loop,
320213449892Sdrh         ** then loop over the sorting index in order to get the output
320313449892Sdrh         ** in sorted order
320413449892Sdrh         */
320513449892Sdrh         groupBySort = 1;
320613449892Sdrh         sqlite3ExprCodeExprList(pParse, pGroupBy);
320713449892Sdrh         sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0);
320813449892Sdrh         j = pGroupBy->nExpr+1;
320913449892Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
321013449892Sdrh           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
321113449892Sdrh           if( pCol->iSorterColumn<j ) continue;
3212945498f3Sdrh           sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn, pCol->iTable);
321313449892Sdrh           j++;
321413449892Sdrh         }
321513449892Sdrh         sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0);
321613449892Sdrh         sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0);
321713449892Sdrh         sqlite3WhereEnd(pWInfo);
321897571957Sdrh         sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
3219de29e3e9Sdrh         VdbeComment((v, "# GROUP BY sort"));
322013449892Sdrh         sAggInfo.useSortingIdx = 1;
322113449892Sdrh       }
322213449892Sdrh 
322313449892Sdrh       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
322413449892Sdrh       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
322513449892Sdrh       ** Then compare the current GROUP BY terms against the GROUP BY terms
322613449892Sdrh       ** from the previous row currently stored in a0, a1, a2...
322713449892Sdrh       */
322813449892Sdrh       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
322913449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
323013449892Sdrh         if( groupBySort ){
323113449892Sdrh           sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j);
323213449892Sdrh         }else{
323313449892Sdrh           sAggInfo.directMode = 1;
323413449892Sdrh           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr);
323513449892Sdrh         }
323613449892Sdrh         sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1);
323713449892Sdrh       }
323813449892Sdrh       for(j=pGroupBy->nExpr-1; j>=0; j--){
323913449892Sdrh         if( j<pGroupBy->nExpr-1 ){
324013449892Sdrh           sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0);
324113449892Sdrh         }
324213449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0);
324313449892Sdrh         if( j==0 ){
3244e313382eSdrh           sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow);
324513449892Sdrh         }else{
32464f686238Sdrh           sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange);
324713449892Sdrh         }
324813449892Sdrh         sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ);
324913449892Sdrh       }
325013449892Sdrh 
325113449892Sdrh       /* Generate code that runs whenever the GROUP BY changes.
325213449892Sdrh       ** Change in the GROUP BY are detected by the previous code
325313449892Sdrh       ** block.  If there were no changes, this block is skipped.
325413449892Sdrh       **
325513449892Sdrh       ** This code copies current group by terms in b0,b1,b2,...
325613449892Sdrh       ** over to a0,a1,a2.  It then calls the output subroutine
325713449892Sdrh       ** and resets the aggregate accumulator registers in preparation
325813449892Sdrh       ** for the next GROUP BY batch.
325913449892Sdrh       */
326013449892Sdrh       sqlite3VdbeResolveLabel(v, addrGroupByChange);
326113449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
3262d654be80Sdrh         sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j);
326313449892Sdrh       }
326413449892Sdrh       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
3265de29e3e9Sdrh       VdbeComment((v, "# output one row"));
326613449892Sdrh       sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd);
3267de29e3e9Sdrh       VdbeComment((v, "# check abort flag"));
3268e313382eSdrh       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
3269de29e3e9Sdrh       VdbeComment((v, "# reset accumulator"));
327013449892Sdrh 
327113449892Sdrh       /* Update the aggregate accumulators based on the content of
327213449892Sdrh       ** the current row
327313449892Sdrh       */
327413449892Sdrh       sqlite3VdbeResolveLabel(v, addrProcessRow);
327513449892Sdrh       updateAccumulator(pParse, &sAggInfo);
3276de29e3e9Sdrh       sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag);
3277de29e3e9Sdrh       VdbeComment((v, "# indicate data in accumulator"));
327813449892Sdrh 
327913449892Sdrh       /* End of the loop
328013449892Sdrh       */
328113449892Sdrh       if( groupBySort ){
328213449892Sdrh         sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
328313449892Sdrh       }else{
328413449892Sdrh         sqlite3WhereEnd(pWInfo);
3285f8875400Sdrh         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
328613449892Sdrh       }
328713449892Sdrh 
328813449892Sdrh       /* Output the final row of result
328913449892Sdrh       */
329013449892Sdrh       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
3291de29e3e9Sdrh       VdbeComment((v, "# output final row"));
329213449892Sdrh 
329313449892Sdrh     } /* endif pGroupBy */
329413449892Sdrh     else {
329513449892Sdrh       /* This case runs if the aggregate has no GROUP BY clause.  The
329613449892Sdrh       ** processing is much simpler since there is only a single row
329713449892Sdrh       ** of output.
329813449892Sdrh       */
329913449892Sdrh       resetAccumulator(pParse, &sAggInfo);
330013449892Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
33015360ad34Sdrh       if( pWInfo==0 ) goto select_end;
330213449892Sdrh       updateAccumulator(pParse, &sAggInfo);
330313449892Sdrh       sqlite3WhereEnd(pWInfo);
330413449892Sdrh       finalizeAggFunctions(pParse, &sAggInfo);
330513449892Sdrh       pOrderBy = 0;
33065774b806Sdrh       if( pHaving ){
33075774b806Sdrh         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1);
33085774b806Sdrh       }
330913449892Sdrh       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
331013449892Sdrh                       eDest, iParm, addrEnd, addrEnd, aff);
331113449892Sdrh     }
331213449892Sdrh     sqlite3VdbeResolveLabel(v, addrEnd);
331313449892Sdrh 
331413449892Sdrh   } /* endif aggregate query */
33152282792aSdrh 
3316cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
3317cce7d176Sdrh   ** and send them to the callback one by one.
3318cce7d176Sdrh   */
3319cce7d176Sdrh   if( pOrderBy ){
3320cdd536f0Sdrh     generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
3321cce7d176Sdrh   }
33226a535340Sdrh 
332393758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
3324f620b4e2Sdrh   /* If this was a subquery, we have now converted the subquery into a
33251787ccabSdanielk1977   ** temporary table.  So set the SrcList_item.isPopulated flag to prevent
33261787ccabSdanielk1977   ** this subquery from being evaluated again and to force the use of
33271787ccabSdanielk1977   ** the temporary table.
3328f620b4e2Sdrh   */
3329f620b4e2Sdrh   if( pParent ){
3330f620b4e2Sdrh     assert( pParent->pSrc->nSrc>parentTab );
3331f620b4e2Sdrh     assert( pParent->pSrc->a[parentTab].pSelect==p );
33321787ccabSdanielk1977     pParent->pSrc->a[parentTab].isPopulated = 1;
3333f620b4e2Sdrh   }
333493758c8dSdanielk1977 #endif
3335f620b4e2Sdrh 
3336ec7429aeSdrh   /* Jump here to skip this query
3337ec7429aeSdrh   */
3338ec7429aeSdrh   sqlite3VdbeResolveLabel(v, iEnd);
3339ec7429aeSdrh 
33401d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
33411d83f052Sdrh   ** to indicate no errors.
33421d83f052Sdrh   */
33431d83f052Sdrh   rc = 0;
33441d83f052Sdrh 
33451d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
33461d83f052Sdrh   ** successful coding of the SELECT.
33471d83f052Sdrh   */
33481d83f052Sdrh select_end:
3349955de52cSdanielk1977 
3350955de52cSdanielk1977   /* Identify column names if we will be using them in a callback.  This
3351955de52cSdanielk1977   ** step is skipped if the output is going to some other destination.
3352955de52cSdanielk1977   */
3353955de52cSdanielk1977   if( rc==SQLITE_OK && eDest==SRT_Callback ){
3354955de52cSdanielk1977     generateColumnNames(pParse, pTabList, pEList);
3355955de52cSdanielk1977   }
3356955de52cSdanielk1977 
335713449892Sdrh   sqliteFree(sAggInfo.aCol);
335813449892Sdrh   sqliteFree(sAggInfo.aFunc);
33591d83f052Sdrh   return rc;
3360cce7d176Sdrh }
3361485f0039Sdrh 
336277a2a5e7Sdrh #if defined(SQLITE_DEBUG)
3363485f0039Sdrh /*
3364485f0039Sdrh *******************************************************************************
3365485f0039Sdrh ** The following code is used for testing and debugging only.  The code
3366485f0039Sdrh ** that follows does not appear in normal builds.
3367485f0039Sdrh **
3368485f0039Sdrh ** These routines are used to print out the content of all or part of a
3369485f0039Sdrh ** parse structures such as Select or Expr.  Such printouts are useful
3370485f0039Sdrh ** for helping to understand what is happening inside the code generator
3371485f0039Sdrh ** during the execution of complex SELECT statements.
3372485f0039Sdrh **
3373485f0039Sdrh ** These routine are not called anywhere from within the normal
3374485f0039Sdrh ** code base.  Then are intended to be called from within the debugger
3375485f0039Sdrh ** or from temporary "printf" statements inserted for debugging.
3376485f0039Sdrh */
3377485f0039Sdrh void sqlite3PrintExpr(Expr *p){
3378485f0039Sdrh   if( p->token.z && p->token.n>0 ){
3379485f0039Sdrh     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
3380485f0039Sdrh   }else{
3381485f0039Sdrh     sqlite3DebugPrintf("(%d", p->op);
3382485f0039Sdrh   }
3383485f0039Sdrh   if( p->pLeft ){
3384485f0039Sdrh     sqlite3DebugPrintf(" ");
3385485f0039Sdrh     sqlite3PrintExpr(p->pLeft);
3386485f0039Sdrh   }
3387485f0039Sdrh   if( p->pRight ){
3388485f0039Sdrh     sqlite3DebugPrintf(" ");
3389485f0039Sdrh     sqlite3PrintExpr(p->pRight);
3390485f0039Sdrh   }
3391485f0039Sdrh   sqlite3DebugPrintf(")");
3392485f0039Sdrh }
3393485f0039Sdrh void sqlite3PrintExprList(ExprList *pList){
3394485f0039Sdrh   int i;
3395485f0039Sdrh   for(i=0; i<pList->nExpr; i++){
3396485f0039Sdrh     sqlite3PrintExpr(pList->a[i].pExpr);
3397485f0039Sdrh     if( i<pList->nExpr-1 ){
3398485f0039Sdrh       sqlite3DebugPrintf(", ");
3399485f0039Sdrh     }
3400485f0039Sdrh   }
3401485f0039Sdrh }
3402485f0039Sdrh void sqlite3PrintSelect(Select *p, int indent){
3403485f0039Sdrh   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
3404485f0039Sdrh   sqlite3PrintExprList(p->pEList);
3405485f0039Sdrh   sqlite3DebugPrintf("\n");
3406485f0039Sdrh   if( p->pSrc ){
3407485f0039Sdrh     char *zPrefix;
3408485f0039Sdrh     int i;
3409485f0039Sdrh     zPrefix = "FROM";
3410485f0039Sdrh     for(i=0; i<p->pSrc->nSrc; i++){
3411485f0039Sdrh       struct SrcList_item *pItem = &p->pSrc->a[i];
3412485f0039Sdrh       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
3413485f0039Sdrh       zPrefix = "";
3414485f0039Sdrh       if( pItem->pSelect ){
3415485f0039Sdrh         sqlite3DebugPrintf("(\n");
3416485f0039Sdrh         sqlite3PrintSelect(pItem->pSelect, indent+10);
3417485f0039Sdrh         sqlite3DebugPrintf("%*s)", indent+8, "");
3418485f0039Sdrh       }else if( pItem->zName ){
3419485f0039Sdrh         sqlite3DebugPrintf("%s", pItem->zName);
3420485f0039Sdrh       }
3421485f0039Sdrh       if( pItem->pTab ){
3422485f0039Sdrh         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
3423485f0039Sdrh       }
3424485f0039Sdrh       if( pItem->zAlias ){
3425485f0039Sdrh         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
3426485f0039Sdrh       }
3427485f0039Sdrh       if( i<p->pSrc->nSrc-1 ){
3428485f0039Sdrh         sqlite3DebugPrintf(",");
3429485f0039Sdrh       }
3430485f0039Sdrh       sqlite3DebugPrintf("\n");
3431485f0039Sdrh     }
3432485f0039Sdrh   }
3433485f0039Sdrh   if( p->pWhere ){
3434485f0039Sdrh     sqlite3DebugPrintf("%*s WHERE ", indent, "");
3435485f0039Sdrh     sqlite3PrintExpr(p->pWhere);
3436485f0039Sdrh     sqlite3DebugPrintf("\n");
3437485f0039Sdrh   }
3438485f0039Sdrh   if( p->pGroupBy ){
3439485f0039Sdrh     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
3440485f0039Sdrh     sqlite3PrintExprList(p->pGroupBy);
3441485f0039Sdrh     sqlite3DebugPrintf("\n");
3442485f0039Sdrh   }
3443485f0039Sdrh   if( p->pHaving ){
3444485f0039Sdrh     sqlite3DebugPrintf("%*s HAVING ", indent, "");
3445485f0039Sdrh     sqlite3PrintExpr(p->pHaving);
3446485f0039Sdrh     sqlite3DebugPrintf("\n");
3447485f0039Sdrh   }
3448485f0039Sdrh   if( p->pOrderBy ){
3449485f0039Sdrh     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
3450485f0039Sdrh     sqlite3PrintExprList(p->pOrderBy);
3451485f0039Sdrh     sqlite3DebugPrintf("\n");
3452485f0039Sdrh   }
3453485f0039Sdrh }
3454485f0039Sdrh /* End of the structure debug printing code
3455485f0039Sdrh *****************************************************************************/
3456485f0039Sdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
3457