xref: /sqlite-3.40.0/src/select.c (revision bb999ef6)
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*bb999ef6Sdrh ** $Id: select.c,v 1.126 2003/02/02 12:41:26 drh Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19315555caSdrh 
20cce7d176Sdrh /*
219bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that
229bb61fe7Sdrh ** structure.
23cce7d176Sdrh */
249bb61fe7Sdrh Select *sqliteSelectNew(
25daffd0e5Sdrh   ExprList *pEList,     /* which columns to include in the result */
26ad3cab52Sdrh   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
27daffd0e5Sdrh   Expr *pWhere,         /* the WHERE clause */
28daffd0e5Sdrh   ExprList *pGroupBy,   /* the GROUP BY clause */
29daffd0e5Sdrh   Expr *pHaving,        /* the HAVING clause */
30daffd0e5Sdrh   ExprList *pOrderBy,   /* the ORDER BY clause */
319bbca4c1Sdrh   int isDistinct,       /* true if the DISTINCT keyword is present */
329bbca4c1Sdrh   int nLimit,           /* LIMIT value.  -1 means not used */
339bbca4c1Sdrh   int nOffset           /* OFFSET value.  -1 means not used */
349bb61fe7Sdrh ){
359bb61fe7Sdrh   Select *pNew;
369bb61fe7Sdrh   pNew = sqliteMalloc( sizeof(*pNew) );
37daffd0e5Sdrh   if( pNew==0 ){
38daffd0e5Sdrh     sqliteExprListDelete(pEList);
39ad3cab52Sdrh     sqliteSrcListDelete(pSrc);
40daffd0e5Sdrh     sqliteExprDelete(pWhere);
41daffd0e5Sdrh     sqliteExprListDelete(pGroupBy);
42daffd0e5Sdrh     sqliteExprDelete(pHaving);
43daffd0e5Sdrh     sqliteExprListDelete(pOrderBy);
44daffd0e5Sdrh   }else{
459bb61fe7Sdrh     pNew->pEList = pEList;
469bb61fe7Sdrh     pNew->pSrc = pSrc;
479bb61fe7Sdrh     pNew->pWhere = pWhere;
489bb61fe7Sdrh     pNew->pGroupBy = pGroupBy;
499bb61fe7Sdrh     pNew->pHaving = pHaving;
509bb61fe7Sdrh     pNew->pOrderBy = pOrderBy;
519bb61fe7Sdrh     pNew->isDistinct = isDistinct;
5282c3d636Sdrh     pNew->op = TK_SELECT;
539bbca4c1Sdrh     pNew->nLimit = nLimit;
549bbca4c1Sdrh     pNew->nOffset = nOffset;
55daffd0e5Sdrh   }
569bb61fe7Sdrh   return pNew;
579bb61fe7Sdrh }
589bb61fe7Sdrh 
599bb61fe7Sdrh /*
6001f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
6101f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
6201f3f253Sdrh ** in terms of the following bit values:
6301f3f253Sdrh **
6401f3f253Sdrh **     JT_INNER
6501f3f253Sdrh **     JT_OUTER
6601f3f253Sdrh **     JT_NATURAL
6701f3f253Sdrh **     JT_LEFT
6801f3f253Sdrh **     JT_RIGHT
6901f3f253Sdrh **
7001f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
7101f3f253Sdrh **
7201f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
7301f3f253Sdrh ** a join type, but put an error in the pParse structure.
7401f3f253Sdrh */
7501f3f253Sdrh int sqliteJoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
7601f3f253Sdrh   int jointype = 0;
7701f3f253Sdrh   Token *apAll[3];
7801f3f253Sdrh   Token *p;
7901f3f253Sdrh   static struct {
8001f3f253Sdrh     const char *zKeyword;
8101f3f253Sdrh     int nChar;
8201f3f253Sdrh     int code;
8301f3f253Sdrh   } keywords[] = {
8401f3f253Sdrh     { "natural", 7, JT_NATURAL },
85195e6967Sdrh     { "left",    4, JT_LEFT|JT_OUTER },
86195e6967Sdrh     { "right",   5, JT_RIGHT|JT_OUTER },
87195e6967Sdrh     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
8801f3f253Sdrh     { "outer",   5, JT_OUTER },
8901f3f253Sdrh     { "inner",   5, JT_INNER },
9001f3f253Sdrh     { "cross",   5, JT_INNER },
9101f3f253Sdrh   };
9201f3f253Sdrh   int i, j;
9301f3f253Sdrh   apAll[0] = pA;
9401f3f253Sdrh   apAll[1] = pB;
9501f3f253Sdrh   apAll[2] = pC;
96195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
9701f3f253Sdrh     p = apAll[i];
9801f3f253Sdrh     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
9901f3f253Sdrh       if( p->n==keywords[j].nChar
10001f3f253Sdrh           && sqliteStrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
10101f3f253Sdrh         jointype |= keywords[j].code;
10201f3f253Sdrh         break;
10301f3f253Sdrh       }
10401f3f253Sdrh     }
10501f3f253Sdrh     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
10601f3f253Sdrh       jointype |= JT_ERROR;
10701f3f253Sdrh       break;
10801f3f253Sdrh     }
10901f3f253Sdrh   }
110ad2d8307Sdrh   if(
111ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
112195e6967Sdrh      (jointype & JT_ERROR)!=0
113ad2d8307Sdrh   ){
11401f3f253Sdrh     static Token dummy = { 0, 0 };
11501f3f253Sdrh     char *zSp1 = " ", *zSp2 = " ";
11601f3f253Sdrh     if( pB==0 ){ pB = &dummy; zSp1 = 0; }
11701f3f253Sdrh     if( pC==0 ){ pC = &dummy; zSp2 = 0; }
11801f3f253Sdrh     sqliteSetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
11901f3f253Sdrh        pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0);
12001f3f253Sdrh     pParse->nErr++;
12101f3f253Sdrh     jointype = JT_INNER;
122195e6967Sdrh   }else if( jointype & JT_RIGHT ){
123195e6967Sdrh     sqliteSetString(&pParse->zErrMsg,
124195e6967Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported", 0);
125195e6967Sdrh     pParse->nErr++;
126195e6967Sdrh     jointype = JT_INNER;
12701f3f253Sdrh   }
12801f3f253Sdrh   return jointype;
12901f3f253Sdrh }
13001f3f253Sdrh 
13101f3f253Sdrh /*
132ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
133ad2d8307Sdrh ** is not contained in the table.
134ad2d8307Sdrh */
135ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
136ad2d8307Sdrh   int i;
137ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
138ad2d8307Sdrh     if( sqliteStrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
139ad2d8307Sdrh   }
140ad2d8307Sdrh   return -1;
141ad2d8307Sdrh }
142ad2d8307Sdrh 
143ad2d8307Sdrh /*
144ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the
145ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2.
146ad2d8307Sdrh */
147ad2d8307Sdrh static void addWhereTerm(
148ad2d8307Sdrh   const char *zCol,        /* Name of the column */
149ad2d8307Sdrh   const Table *pTab1,      /* First table */
150ad2d8307Sdrh   const Table *pTab2,      /* Second table */
151ad2d8307Sdrh   Expr **ppExpr            /* Add the equality term to this expression */
152ad2d8307Sdrh ){
153ad2d8307Sdrh   Token dummy;
154ad2d8307Sdrh   Expr *pE1a, *pE1b, *pE1c;
155ad2d8307Sdrh   Expr *pE2a, *pE2b, *pE2c;
156ad2d8307Sdrh   Expr *pE;
157ad2d8307Sdrh 
158ad2d8307Sdrh   dummy.z = zCol;
159ad2d8307Sdrh   dummy.n = strlen(zCol);
1604b59ab5eSdrh   dummy.dyn = 0;
161ad2d8307Sdrh   pE1a = sqliteExpr(TK_ID, 0, 0, &dummy);
162ad2d8307Sdrh   pE2a = sqliteExpr(TK_ID, 0, 0, &dummy);
163ad2d8307Sdrh   dummy.z = pTab1->zName;
164ad2d8307Sdrh   dummy.n = strlen(dummy.z);
165ad2d8307Sdrh   pE1b = sqliteExpr(TK_ID, 0, 0, &dummy);
166ad2d8307Sdrh   dummy.z = pTab2->zName;
167ad2d8307Sdrh   dummy.n = strlen(dummy.z);
168ad2d8307Sdrh   pE2b = sqliteExpr(TK_ID, 0, 0, &dummy);
169ad2d8307Sdrh   pE1c = sqliteExpr(TK_DOT, pE1b, pE1a, 0);
170ad2d8307Sdrh   pE2c = sqliteExpr(TK_DOT, pE2b, pE2a, 0);
171ad2d8307Sdrh   pE = sqliteExpr(TK_EQ, pE1c, pE2c, 0);
1721f16230bSdrh   ExprSetProperty(pE, EP_FromJoin);
173ad2d8307Sdrh   if( *ppExpr ){
174ad2d8307Sdrh     *ppExpr = sqliteExpr(TK_AND, *ppExpr, pE, 0);
175ad2d8307Sdrh   }else{
176ad2d8307Sdrh     *ppExpr = pE;
177ad2d8307Sdrh   }
178ad2d8307Sdrh }
179ad2d8307Sdrh 
180ad2d8307Sdrh /*
1811f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
1821cc093c2Sdrh **
183e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
1841cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
1851f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
1861f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
1871f16230bSdrh ** WHERE clause during join processing but we need to remember that they
1881f16230bSdrh ** originated in the ON or USING clause.
1891cc093c2Sdrh */
1901cc093c2Sdrh static void setJoinExpr(Expr *p){
1911cc093c2Sdrh   while( p ){
1921f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
1931cc093c2Sdrh     setJoinExpr(p->pLeft);
1941cc093c2Sdrh     p = p->pRight;
1951cc093c2Sdrh   }
1961cc093c2Sdrh }
1971cc093c2Sdrh 
1981cc093c2Sdrh /*
199ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
200ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
201ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
202ad2d8307Sdrh **
203ad2d8307Sdrh ** This routine returns the number of errors encountered.
204ad2d8307Sdrh */
205ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
206ad2d8307Sdrh   SrcList *pSrc;
207ad2d8307Sdrh   int i, j;
208ad2d8307Sdrh   pSrc = p->pSrc;
209ad2d8307Sdrh   for(i=0; i<pSrc->nSrc-1; i++){
210ad2d8307Sdrh     struct SrcList_item *pTerm = &pSrc->a[i];
211ad2d8307Sdrh     struct SrcList_item *pOther = &pSrc->a[i+1];
212ad2d8307Sdrh 
213ad2d8307Sdrh     if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
214ad2d8307Sdrh 
215ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
216ad2d8307Sdrh     ** every column that the two tables have in common.
217ad2d8307Sdrh     */
218ad2d8307Sdrh     if( pTerm->jointype & JT_NATURAL ){
219ad2d8307Sdrh       Table *pTab;
220ad2d8307Sdrh       if( pTerm->pOn || pTerm->pUsing ){
221ad2d8307Sdrh         sqliteSetString(&pParse->zErrMsg, "a NATURAL join may not have "
222ad2d8307Sdrh            "an ON or USING clause", 0);
223ad2d8307Sdrh         pParse->nErr++;
224ad2d8307Sdrh         return 1;
225ad2d8307Sdrh       }
226ad2d8307Sdrh       pTab = pTerm->pTab;
227ad2d8307Sdrh       for(j=0; j<pTab->nCol; j++){
228ad2d8307Sdrh         if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
229ad2d8307Sdrh           addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
230ad2d8307Sdrh         }
231ad2d8307Sdrh       }
232ad2d8307Sdrh     }
233ad2d8307Sdrh 
234ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
235ad2d8307Sdrh     */
236ad2d8307Sdrh     if( pTerm->pOn && pTerm->pUsing ){
237ad2d8307Sdrh       sqliteSetString(&pParse->zErrMsg, "cannot have both ON and USING "
238ad2d8307Sdrh         "clauses in the same join", 0);
239ad2d8307Sdrh       pParse->nErr++;
240ad2d8307Sdrh       return 1;
241ad2d8307Sdrh     }
242ad2d8307Sdrh 
243ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
244ad2d8307Sdrh     ** and AND operator.
245ad2d8307Sdrh     */
246ad2d8307Sdrh     if( pTerm->pOn ){
2471cc093c2Sdrh       setJoinExpr(pTerm->pOn);
248ad2d8307Sdrh       if( p->pWhere==0 ){
249ad2d8307Sdrh         p->pWhere = pTerm->pOn;
250ad2d8307Sdrh       }else{
251ad2d8307Sdrh         p->pWhere = sqliteExpr(TK_AND, p->pWhere, pTerm->pOn, 0);
252ad2d8307Sdrh       }
253ad2d8307Sdrh       pTerm->pOn = 0;
254ad2d8307Sdrh     }
255ad2d8307Sdrh 
256ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
257ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
258ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
259ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
260ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
261ad2d8307Sdrh     ** not contained in both tables to be joined.
262ad2d8307Sdrh     */
263ad2d8307Sdrh     if( pTerm->pUsing ){
264ad2d8307Sdrh       IdList *pList;
265ad2d8307Sdrh       int j;
266ad2d8307Sdrh       assert( i<pSrc->nSrc-1 );
267ad2d8307Sdrh       pList = pTerm->pUsing;
268ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
269bf5cd97eSdrh         if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
270bf5cd97eSdrh             columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
271ad2d8307Sdrh           sqliteSetString(&pParse->zErrMsg, "cannot join using column ",
272bf5cd97eSdrh             pList->a[j].zName, " - column not present in both tables", 0);
273ad2d8307Sdrh           pParse->nErr++;
274ad2d8307Sdrh           return 1;
275ad2d8307Sdrh         }
276bf5cd97eSdrh         addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
277ad2d8307Sdrh       }
278ad2d8307Sdrh     }
279ad2d8307Sdrh   }
280ad2d8307Sdrh   return 0;
281ad2d8307Sdrh }
282ad2d8307Sdrh 
283ad2d8307Sdrh /*
2841f16230bSdrh ** This routine implements a minimal Oracle8 join syntax immulation.
2851f16230bSdrh ** The precise oracle8 syntax is not implemented - it is easy enough
2861f16230bSdrh ** to get this routine confused.  But this routine does make it possible
2871f16230bSdrh ** to write a single SQL statement that does a left outer join in both
2881f16230bSdrh ** oracle8 and in SQLite.
2891f16230bSdrh **
2901f16230bSdrh ** This routine looks for TK_COLUMN expression nodes that are marked
2911f16230bSdrh ** with the EP_Oracle8Join property.  Such nodes are generated by a
2921f16230bSdrh ** column name (either "column" or "table.column") that is followed by
2931f16230bSdrh ** the special "(+)" operator.  If the table of the column marked with
2941f16230bSdrh ** the (+) operator is the second are subsequent table in a join, then
2951f16230bSdrh ** that table becomes the left table in a LEFT OUTER JOIN.  The expression
2961f16230bSdrh ** that uses that table becomes part of the ON clause for the join.
2971f16230bSdrh **
2981f16230bSdrh ** It is important to enphasize that this is not exactly how oracle8
2991f16230bSdrh ** works.  But it is close enough so that one can construct queries that
3001f16230bSdrh ** will work correctly for both SQLite and Oracle8.
3011f16230bSdrh */
3021f16230bSdrh static int sqliteOracle8JoinFixup(
3031f16230bSdrh   int base,         /* VDBE cursor number for first table in pSrc */
3041f16230bSdrh   SrcList *pSrc,    /* List of tables being joined */
3051f16230bSdrh   Expr *pWhere      /* The WHERE clause of the SELECT statement */
3061f16230bSdrh ){
3071f16230bSdrh   int rc = 0;
3081f16230bSdrh   if( ExprHasProperty(pWhere, EP_Oracle8Join) && pWhere->op==TK_COLUMN ){
3091f16230bSdrh     int idx = pWhere->iTable - base;
3101f16230bSdrh     assert( idx>=0 && idx<pSrc->nSrc );
3111f16230bSdrh     if( idx>0 ){
3121f16230bSdrh       pSrc->a[idx-1].jointype &= ~JT_INNER;
3131f16230bSdrh       pSrc->a[idx-1].jointype |= JT_OUTER|JT_LEFT;
3141f16230bSdrh       return 1;
3151f16230bSdrh     }
3161f16230bSdrh   }
3171f16230bSdrh   if( pWhere->pRight ){
3181f16230bSdrh     rc = sqliteOracle8JoinFixup(base, pSrc, pWhere->pRight);
3191f16230bSdrh   }
3201f16230bSdrh   if( pWhere->pLeft ){
3211f16230bSdrh     rc |= sqliteOracle8JoinFixup(base, pSrc, pWhere->pLeft);
3221f16230bSdrh   }
3231f16230bSdrh   if( pWhere->pList ){
3241f16230bSdrh     int i;
3251f16230bSdrh     ExprList *pList = pWhere->pList;
3261f16230bSdrh     for(i=0; i<pList->nExpr && rc==0; i++){
3271f16230bSdrh       rc |= sqliteOracle8JoinFixup(base, pSrc, pList->a[i].pExpr);
3281f16230bSdrh     }
3291f16230bSdrh   }
3301f16230bSdrh   if( rc==1 && (pWhere->op==TK_AND || pWhere->op==TK_EQ) ){
3311f16230bSdrh     setJoinExpr(pWhere);
3321f16230bSdrh     rc = 0;
3331f16230bSdrh   }
3341f16230bSdrh   return rc;
3351f16230bSdrh }
3361f16230bSdrh 
3371f16230bSdrh /*
3389bb61fe7Sdrh ** Delete the given Select structure and all of its substructures.
3399bb61fe7Sdrh */
3409bb61fe7Sdrh void sqliteSelectDelete(Select *p){
34182c3d636Sdrh   if( p==0 ) return;
3429bb61fe7Sdrh   sqliteExprListDelete(p->pEList);
343ad3cab52Sdrh   sqliteSrcListDelete(p->pSrc);
3449bb61fe7Sdrh   sqliteExprDelete(p->pWhere);
3459bb61fe7Sdrh   sqliteExprListDelete(p->pGroupBy);
3469bb61fe7Sdrh   sqliteExprDelete(p->pHaving);
3479bb61fe7Sdrh   sqliteExprListDelete(p->pOrderBy);
34882c3d636Sdrh   sqliteSelectDelete(p->pPrior);
349a76b5dfcSdrh   sqliteFree(p->zSelect);
3509bb61fe7Sdrh   sqliteFree(p);
3519bb61fe7Sdrh }
3529bb61fe7Sdrh 
3539bb61fe7Sdrh /*
3542282792aSdrh ** Delete the aggregate information from the parse structure.
3552282792aSdrh */
3561d83f052Sdrh static void sqliteAggregateInfoReset(Parse *pParse){
3572282792aSdrh   sqliteFree(pParse->aAgg);
3582282792aSdrh   pParse->aAgg = 0;
3592282792aSdrh   pParse->nAgg = 0;
3602282792aSdrh   pParse->useAgg = 0;
3612282792aSdrh }
3622282792aSdrh 
3632282792aSdrh /*
364c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
365c926afbcSdrh ** stack into the sorter.
366c926afbcSdrh */
367c926afbcSdrh static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
368c926afbcSdrh   char *zSortOrder;
369c926afbcSdrh   int i;
370c926afbcSdrh   zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
371c926afbcSdrh   if( zSortOrder==0 ) return;
372c926afbcSdrh   for(i=0; i<pOrderBy->nExpr; i++){
37338640e15Sdrh     int order = pOrderBy->a[i].sortOrder;
37438640e15Sdrh     int type;
37538640e15Sdrh     int c;
37638640e15Sdrh     if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
37738640e15Sdrh       type = SQLITE_SO_TEXT;
37838640e15Sdrh     }else if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_NUM ){
37938640e15Sdrh       type = SQLITE_SO_NUM;
380491791a8Sdrh     }else if( pParse->db->file_format>=4 ){
38138640e15Sdrh       type = sqliteExprType(pOrderBy->a[i].pExpr);
38238640e15Sdrh     }else{
38338640e15Sdrh       type = SQLITE_SO_NUM;
38438640e15Sdrh     }
38538640e15Sdrh     if( (order & SQLITE_SO_DIRMASK)==SQLITE_SO_ASC ){
38638640e15Sdrh       c = type==SQLITE_SO_TEXT ? 'A' : '+';
38738640e15Sdrh     }else{
38838640e15Sdrh       c = type==SQLITE_SO_TEXT ? 'D' : '-';
38938640e15Sdrh     }
39038640e15Sdrh     zSortOrder[i] = c;
391c926afbcSdrh     sqliteExprCode(pParse, pOrderBy->a[i].pExpr);
392c926afbcSdrh   }
393c926afbcSdrh   zSortOrder[pOrderBy->nExpr] = 0;
394c926afbcSdrh   sqliteVdbeAddOp(v, OP_SortMakeKey, pOrderBy->nExpr, 0);
395c926afbcSdrh   sqliteVdbeChangeP3(v, -1, zSortOrder, strlen(zSortOrder));
396c926afbcSdrh   sqliteFree(zSortOrder);
397c926afbcSdrh   sqliteVdbeAddOp(v, OP_SortPut, 0, 0);
398c926afbcSdrh }
399c926afbcSdrh 
400c926afbcSdrh /*
40138640e15Sdrh ** This routine adds a P3 argument to the last VDBE opcode that was
40238640e15Sdrh ** inserted. The P3 argument added is a string suitable for the
40338640e15Sdrh ** OP_MakeKey or OP_MakeIdxKey opcodes.  The string consists of
40438640e15Sdrh ** characters 't' or 'n' depending on whether or not the various
40538640e15Sdrh ** fields of the key to be generated should be treated as numeric
40638640e15Sdrh ** or as text.  See the OP_MakeKey and OP_MakeIdxKey opcode
40738640e15Sdrh ** documentation for additional information about the P3 string.
40838640e15Sdrh ** See also the sqliteAddIdxKeyType() routine.
40938640e15Sdrh */
41038640e15Sdrh void sqliteAddKeyType(Vdbe *v, ExprList *pEList){
41138640e15Sdrh   int nColumn = pEList->nExpr;
41238640e15Sdrh   char *zType = sqliteMalloc( nColumn+1 );
41338640e15Sdrh   int i;
41438640e15Sdrh   if( zType==0 ) return;
41538640e15Sdrh   for(i=0; i<nColumn; i++){
41638640e15Sdrh     zType[i] = sqliteExprType(pEList->a[i].pExpr)==SQLITE_SO_NUM ? 'n' : 't';
41738640e15Sdrh   }
41838640e15Sdrh   zType[i] = 0;
41938640e15Sdrh   sqliteVdbeChangeP3(v, -1, zType, nColumn);
42038640e15Sdrh   sqliteFree(zType);
42138640e15Sdrh }
42238640e15Sdrh 
42338640e15Sdrh /*
4242282792aSdrh ** This routine generates the code for the inside of the inner loop
4252282792aSdrh ** of a SELECT.
42682c3d636Sdrh **
42738640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
42838640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
42938640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
43038640e15Sdrh ** datatypes for each column.
4312282792aSdrh */
4322282792aSdrh static int selectInnerLoop(
4332282792aSdrh   Parse *pParse,          /* The parser context */
434df199a25Sdrh   Select *p,              /* The complete select statement being coded */
4352282792aSdrh   ExprList *pEList,       /* List of values being extracted */
43682c3d636Sdrh   int srcTab,             /* Pull data from this table */
437967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
4382282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
4392282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
4402282792aSdrh   int eDest,              /* How to dispose of the results */
4412282792aSdrh   int iParm,              /* An argument to the disposal method */
4422282792aSdrh   int iContinue,          /* Jump here to continue with next row */
4432282792aSdrh   int iBreak              /* Jump here to break out of the inner loop */
4442282792aSdrh ){
4452282792aSdrh   Vdbe *v = pParse->pVdbe;
4462282792aSdrh   int i;
44738640e15Sdrh 
448daffd0e5Sdrh   if( v==0 ) return 0;
44938640e15Sdrh   assert( pEList!=0 );
4502282792aSdrh 
451df199a25Sdrh   /* If there was a LIMIT clause on the SELECT statement, then do the check
452df199a25Sdrh   ** to see if this row should be output.
453df199a25Sdrh   */
454df199a25Sdrh   if( pOrderBy==0 ){
455df199a25Sdrh     if( p->nOffset>0 ){
456d11d382cSdrh       int addr = sqliteVdbeCurrentAddr(v);
457d11d382cSdrh       sqliteVdbeAddOp(v, OP_MemIncr, p->nOffset, addr+2);
458d11d382cSdrh       sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
459df199a25Sdrh     }
460d11d382cSdrh     if( p->nLimit>=0 ){
461d11d382cSdrh       sqliteVdbeAddOp(v, OP_MemIncr, p->nLimit, iBreak);
462df199a25Sdrh     }
463df199a25Sdrh   }
464df199a25Sdrh 
465967e8b73Sdrh   /* Pull the requested columns.
4662282792aSdrh   */
46738640e15Sdrh   if( nColumn>0 ){
468967e8b73Sdrh     for(i=0; i<nColumn; i++){
46999fcd718Sdrh       sqliteVdbeAddOp(v, OP_Column, srcTab, i);
47082c3d636Sdrh     }
47138640e15Sdrh   }else{
47238640e15Sdrh     nColumn = pEList->nExpr;
47338640e15Sdrh     for(i=0; i<pEList->nExpr; i++){
47438640e15Sdrh       sqliteExprCode(pParse, pEList->a[i].pExpr);
47538640e15Sdrh     }
47682c3d636Sdrh   }
4772282792aSdrh 
478daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
479daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
480daffd0e5Sdrh   ** part of the result.
4812282792aSdrh   */
482f5905aa7Sdrh   if( distinct>=0 && pEList && pEList->nExpr>0 ){
4830bd1f4eaSdrh #if NULL_ALWAYS_DISTINCT
4840bd1f4eaSdrh     sqliteVdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqliteVdbeCurrentAddr(v)+7);
4850bd1f4eaSdrh #endif
48699fcd718Sdrh     sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
487491791a8Sdrh     if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pEList);
488f5905aa7Sdrh     sqliteVdbeAddOp(v, OP_Distinct, distinct, sqliteVdbeCurrentAddr(v)+3);
48999fcd718Sdrh     sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
49099fcd718Sdrh     sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
49199fcd718Sdrh     sqliteVdbeAddOp(v, OP_String, 0, 0);
4926b12545fSdrh     sqliteVdbeAddOp(v, OP_PutStrKey, distinct, 0);
4932282792aSdrh   }
49482c3d636Sdrh 
495c926afbcSdrh   switch( eDest ){
49682c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
49782c3d636Sdrh     ** table iParm.
4982282792aSdrh     */
499c926afbcSdrh     case SRT_Union: {
5000bd1f4eaSdrh       sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
501f5905aa7Sdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
5026b12545fSdrh       sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
503c926afbcSdrh       break;
504c926afbcSdrh     }
50582c3d636Sdrh 
5065974a30fSdrh     /* Store the result as data using a unique key.
5075974a30fSdrh     */
508c926afbcSdrh     case SRT_Table:
509c926afbcSdrh     case SRT_TempTable: {
51099fcd718Sdrh       sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
511c926afbcSdrh       if( pOrderBy ){
512c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
513c926afbcSdrh       }else{
51499fcd718Sdrh         sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
51599fcd718Sdrh         sqliteVdbeAddOp(v, OP_Pull, 1, 0);
5166b12545fSdrh         sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
517c926afbcSdrh       }
518c926afbcSdrh       break;
519c926afbcSdrh     }
5205974a30fSdrh 
52182c3d636Sdrh     /* Construct a record from the query result, but instead of
52282c3d636Sdrh     ** saving that record, use it as a key to delete elements from
52382c3d636Sdrh     ** the temporary table iParm.
52482c3d636Sdrh     */
525c926afbcSdrh     case SRT_Except: {
5260bd1f4eaSdrh       int addr;
5270bd1f4eaSdrh       addr = sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
52899fcd718Sdrh       sqliteVdbeAddOp(v, OP_NotFound, iParm, addr+3);
52999fcd718Sdrh       sqliteVdbeAddOp(v, OP_Delete, iParm, 0);
530c926afbcSdrh       break;
531c926afbcSdrh     }
5322282792aSdrh 
5332282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
5342282792aSdrh     ** then there should be a single item on the stack.  Write this
5352282792aSdrh     ** item into the set table with bogus data.
5362282792aSdrh     */
537c926afbcSdrh     case SRT_Set: {
538a9f9d1c0Sdrh       int lbl = sqliteVdbeMakeLabel(v);
539967e8b73Sdrh       assert( nColumn==1 );
540a9f9d1c0Sdrh       sqliteVdbeAddOp(v, OP_IsNull, -1, lbl);
541c926afbcSdrh       if( pOrderBy ){
542c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
543c926afbcSdrh       }else{
544a9f9d1c0Sdrh         sqliteVdbeAddOp(v, OP_String, 0, 0);
5456b12545fSdrh         sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
546c926afbcSdrh       }
547a9f9d1c0Sdrh       sqliteVdbeResolveLabel(v, lbl);
548c926afbcSdrh       break;
549c926afbcSdrh     }
55082c3d636Sdrh 
5512282792aSdrh     /* If this is a scalar select that is part of an expression, then
5522282792aSdrh     ** store the results in the appropriate memory cell and break out
5532282792aSdrh     ** of the scan loop.
5542282792aSdrh     */
555c926afbcSdrh     case SRT_Mem: {
556967e8b73Sdrh       assert( nColumn==1 );
557c926afbcSdrh       if( pOrderBy ){
558c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
559c926afbcSdrh       }else{
5608721ce4aSdrh         sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
56199fcd718Sdrh         sqliteVdbeAddOp(v, OP_Goto, 0, iBreak);
562c926afbcSdrh       }
563c926afbcSdrh       break;
564c926afbcSdrh     }
5652282792aSdrh 
566f46f905aSdrh     /* Send the data to the callback function.
567f46f905aSdrh     */
568f46f905aSdrh     case SRT_Callback:
569f46f905aSdrh     case SRT_Sorter: {
570f46f905aSdrh       if( pOrderBy ){
571f46f905aSdrh         sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
572f46f905aSdrh         pushOntoSorter(pParse, v, pOrderBy);
573f46f905aSdrh       }else{
574f46f905aSdrh         assert( eDest==SRT_Callback );
575f46f905aSdrh         sqliteVdbeAddOp(v, OP_Callback, nColumn, 0);
576f46f905aSdrh       }
577f46f905aSdrh       break;
578f46f905aSdrh     }
579f46f905aSdrh 
580142e30dfSdrh     /* Invoke a subroutine to handle the results.  The subroutine itself
581142e30dfSdrh     ** is responsible for popping the results off of the stack.
582142e30dfSdrh     */
583142e30dfSdrh     case SRT_Subroutine: {
584ac82fcf5Sdrh       if( pOrderBy ){
585ac82fcf5Sdrh         sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
586ac82fcf5Sdrh         pushOntoSorter(pParse, v, pOrderBy);
587ac82fcf5Sdrh       }else{
588142e30dfSdrh         sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
589ac82fcf5Sdrh       }
590142e30dfSdrh       break;
591142e30dfSdrh     }
592142e30dfSdrh 
593d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
594d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
595d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
596d7489c39Sdrh     ** about the actual results of the select.
597d7489c39Sdrh     */
598c926afbcSdrh     default: {
599f46f905aSdrh       assert( eDest==SRT_Discard );
600f46f905aSdrh       sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
601c926afbcSdrh       break;
602c926afbcSdrh     }
603c926afbcSdrh   }
60482c3d636Sdrh   return 0;
60582c3d636Sdrh }
60682c3d636Sdrh 
60782c3d636Sdrh /*
608d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
609d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
610d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
611d8bc7086Sdrh ** routine generates the code needed to do that.
612d8bc7086Sdrh */
613c926afbcSdrh static void generateSortTail(
614c926afbcSdrh   Select *p,       /* The SELECT statement */
615c926afbcSdrh   Vdbe *v,         /* Generate code into this VDBE */
616c926afbcSdrh   int nColumn,     /* Number of columns of data */
617c926afbcSdrh   int eDest,       /* Write the sorted results here */
618c926afbcSdrh   int iParm        /* Optional parameter associated with eDest */
619c926afbcSdrh ){
620d8bc7086Sdrh   int end = sqliteVdbeMakeLabel(v);
621d8bc7086Sdrh   int addr;
622f46f905aSdrh   if( eDest==SRT_Sorter ) return;
62399fcd718Sdrh   sqliteVdbeAddOp(v, OP_Sort, 0, 0);
62499fcd718Sdrh   addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end);
625df199a25Sdrh   if( p->nOffset>0 ){
626d11d382cSdrh     sqliteVdbeAddOp(v, OP_MemIncr, p->nOffset, addr+4);
627d11d382cSdrh     sqliteVdbeAddOp(v, OP_Pop, 1, 0);
628d11d382cSdrh     sqliteVdbeAddOp(v, OP_Goto, 0, addr);
629df199a25Sdrh   }
630d11d382cSdrh   if( p->nLimit>=0 ){
631d11d382cSdrh     sqliteVdbeAddOp(v, OP_MemIncr, p->nLimit, end);
632df199a25Sdrh   }
633c926afbcSdrh   switch( eDest ){
634c926afbcSdrh     case SRT_Callback: {
635df199a25Sdrh       sqliteVdbeAddOp(v, OP_SortCallback, nColumn, 0);
636c926afbcSdrh       break;
637c926afbcSdrh     }
638c926afbcSdrh     case SRT_Table:
639c926afbcSdrh     case SRT_TempTable: {
640c926afbcSdrh       sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
641c926afbcSdrh       sqliteVdbeAddOp(v, OP_Pull, 1, 0);
642c926afbcSdrh       sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
643c926afbcSdrh       break;
644c926afbcSdrh     }
645c926afbcSdrh     case SRT_Set: {
646c926afbcSdrh       assert( nColumn==1 );
647c926afbcSdrh       sqliteVdbeAddOp(v, OP_IsNull, -1, sqliteVdbeCurrentAddr(v)+3);
648c926afbcSdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
649c926afbcSdrh       sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
650c926afbcSdrh       break;
651c926afbcSdrh     }
652c926afbcSdrh     case SRT_Mem: {
653c926afbcSdrh       assert( nColumn==1 );
654c926afbcSdrh       sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
655c926afbcSdrh       sqliteVdbeAddOp(v, OP_Goto, 0, end);
656c926afbcSdrh       break;
657c926afbcSdrh     }
658ac82fcf5Sdrh     case SRT_Subroutine: {
659ac82fcf5Sdrh       int i;
660ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
661ac82fcf5Sdrh         sqliteVdbeAddOp(v, OP_Column, -1-i, i);
662ac82fcf5Sdrh       }
663ac82fcf5Sdrh       sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
664ac82fcf5Sdrh       sqliteVdbeAddOp(v, OP_Pop, 1, 0);
665ac82fcf5Sdrh       break;
666ac82fcf5Sdrh     }
667c926afbcSdrh     default: {
668f46f905aSdrh       /* Do nothing */
669c926afbcSdrh       break;
670c926afbcSdrh     }
671c926afbcSdrh   }
67299fcd718Sdrh   sqliteVdbeAddOp(v, OP_Goto, 0, addr);
67399fcd718Sdrh   sqliteVdbeResolveLabel(v, end);
674a8b38d28Sdrh   sqliteVdbeAddOp(v, OP_SortReset, 0, 0);
675d8bc7086Sdrh }
676d8bc7086Sdrh 
677d8bc7086Sdrh /*
678fcb78a49Sdrh ** Generate code that will tell the VDBE the datatypes of
679fcb78a49Sdrh ** columns in the result set.
680e78e8284Sdrh **
681e78e8284Sdrh ** This routine only generates code if the "PRAGMA show_datatypes=on"
682e78e8284Sdrh ** has been executed.  The datatypes are reported out in the azCol
683e78e8284Sdrh ** parameter to the callback function.  The first N azCol[] entries
684e78e8284Sdrh ** are the names of the columns, and the second N entries are the
685e78e8284Sdrh ** datatypes for the columns.
686e78e8284Sdrh **
687e78e8284Sdrh ** The "datatype" for a result that is a column of a type is the
688e78e8284Sdrh ** datatype definition extracted from the CREATE TABLE statement.
689e78e8284Sdrh ** The datatype for an expression is either TEXT or NUMERIC.  The
690e78e8284Sdrh ** datatype for a ROWID field is INTEGER.
691fcb78a49Sdrh */
692fcb78a49Sdrh static void generateColumnTypes(
693fcb78a49Sdrh   Parse *pParse,      /* Parser context */
694fcb78a49Sdrh   int base,           /* VDBE cursor corresponding to first entry in pTabList */
695fcb78a49Sdrh   SrcList *pTabList,  /* List of tables */
696fcb78a49Sdrh   ExprList *pEList    /* Expressions defining the result set */
697fcb78a49Sdrh ){
698fcb78a49Sdrh   Vdbe *v = pParse->pVdbe;
699fcb78a49Sdrh   int i;
700326dce74Sdrh   if( pParse->useCallback && (pParse->db->flags & SQLITE_ReportTypes)==0 ){
701326dce74Sdrh     return;
702326dce74Sdrh   }
703fcb78a49Sdrh   for(i=0; i<pEList->nExpr; i++){
704fcb78a49Sdrh     Expr *p = pEList->a[i].pExpr;
705fcb78a49Sdrh     char *zType = 0;
706fcb78a49Sdrh     if( p==0 ) continue;
707fcb78a49Sdrh     if( p->op==TK_COLUMN && pTabList ){
708fcb78a49Sdrh       Table *pTab = pTabList->a[p->iTable - base].pTab;
709fcb78a49Sdrh       int iCol = p->iColumn;
710fcb78a49Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
711fcb78a49Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
712fcb78a49Sdrh       if( iCol<0 ){
713fcb78a49Sdrh         zType = "INTEGER";
714fcb78a49Sdrh       }else{
715fcb78a49Sdrh         zType = pTab->aCol[iCol].zType;
716fcb78a49Sdrh       }
717fcb78a49Sdrh     }else{
718fcb78a49Sdrh       if( sqliteExprType(p)==SQLITE_SO_TEXT ){
719fcb78a49Sdrh         zType = "TEXT";
720fcb78a49Sdrh       }else{
721fcb78a49Sdrh         zType = "NUMERIC";
722fcb78a49Sdrh       }
723fcb78a49Sdrh     }
724fcb78a49Sdrh     sqliteVdbeAddOp(v, OP_ColumnName, i + pEList->nExpr, 0);
725fcb78a49Sdrh     sqliteVdbeChangeP3(v, -1, zType, P3_STATIC);
726fcb78a49Sdrh   }
727fcb78a49Sdrh }
728fcb78a49Sdrh 
729fcb78a49Sdrh /*
730fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
731fcb78a49Sdrh ** in the result set.  This information is used to provide the
732fcb78a49Sdrh ** azCol[] vaolues in the callback.
73382c3d636Sdrh */
734832508b7Sdrh static void generateColumnNames(
735832508b7Sdrh   Parse *pParse,      /* Parser context */
736832508b7Sdrh   int base,           /* VDBE cursor corresponding to first entry in pTabList */
737ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
738832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
739832508b7Sdrh ){
740d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
74182c3d636Sdrh   int i;
742daffd0e5Sdrh   if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return;
743d8bc7086Sdrh   pParse->colNamesSet = 1;
74482c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
74582c3d636Sdrh     Expr *p;
746b1363206Sdrh     char *zType = 0;
7471bee3d7bSdrh     int showFullNames;
7485a38705eSdrh     p = pEList->a[i].pExpr;
7495a38705eSdrh     if( p==0 ) continue;
75082c3d636Sdrh     if( pEList->a[i].zName ){
75182c3d636Sdrh       char *zName = pEList->a[i].zName;
75299fcd718Sdrh       sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
75399fcd718Sdrh       sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
75482c3d636Sdrh       continue;
75582c3d636Sdrh     }
7561bee3d7bSdrh     showFullNames = (pParse->db->flags & SQLITE_FullColNames)!=0;
757fa173a76Sdrh     if( p->op==TK_COLUMN && pTabList ){
758832508b7Sdrh       Table *pTab = pTabList->a[p->iTable - base].pTab;
75997665873Sdrh       char *zCol;
7608aff1015Sdrh       int iCol = p->iColumn;
7618aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
76297665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
763b1363206Sdrh       if( iCol<0 ){
764b1363206Sdrh         zCol = "_ROWID_";
765b1363206Sdrh         zType = "INTEGER";
766b1363206Sdrh       }else{
767b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
768b1363206Sdrh         zType = pTab->aCol[iCol].zType;
769b1363206Sdrh       }
7706977fea8Sdrh       if( p->span.z && p->span.z[0] && !showFullNames ){
771fa173a76Sdrh         int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
7726977fea8Sdrh         sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
773fa173a76Sdrh         sqliteVdbeCompressSpace(v, addr);
774fa173a76Sdrh       }else if( pTabList->nSrc>1 || showFullNames ){
77582c3d636Sdrh         char *zName = 0;
77682c3d636Sdrh         char *zTab;
77782c3d636Sdrh 
778832508b7Sdrh         zTab = pTabList->a[p->iTable - base].zAlias;
77901a34661Sdrh         if( showFullNames || zTab==0 ) zTab = pTab->zName;
78097665873Sdrh         sqliteSetString(&zName, zTab, ".", zCol, 0);
78199fcd718Sdrh         sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
78299fcd718Sdrh         sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
78382c3d636Sdrh         sqliteFree(zName);
78482c3d636Sdrh       }else{
78599fcd718Sdrh         sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
78622f70c32Sdrh         sqliteVdbeChangeP3(v, -1, zCol, 0);
78782c3d636Sdrh       }
7886977fea8Sdrh     }else if( p->span.z && p->span.z[0] ){
789fa173a76Sdrh       int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
7906977fea8Sdrh       sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
7911bee3d7bSdrh       sqliteVdbeCompressSpace(v, addr);
7921bee3d7bSdrh     }else{
7931bee3d7bSdrh       char zName[30];
7941bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
7951bee3d7bSdrh       sprintf(zName, "column%d", i+1);
7961bee3d7bSdrh       sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
7971bee3d7bSdrh       sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
79882c3d636Sdrh     }
79982c3d636Sdrh   }
8005080aaa7Sdrh }
80182c3d636Sdrh 
80282c3d636Sdrh /*
803d8bc7086Sdrh ** Name of the connection operator, used for error messages.
804d8bc7086Sdrh */
805d8bc7086Sdrh static const char *selectOpName(int id){
806d8bc7086Sdrh   char *z;
807d8bc7086Sdrh   switch( id ){
808d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
809d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
810d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
811d8bc7086Sdrh     default:           z = "UNION";       break;
812d8bc7086Sdrh   }
813d8bc7086Sdrh   return z;
814d8bc7086Sdrh }
815d8bc7086Sdrh 
816d8bc7086Sdrh /*
817315555caSdrh ** Forward declaration
818315555caSdrh */
819315555caSdrh static int fillInColumnList(Parse*, Select*);
820315555caSdrh 
821315555caSdrh /*
82222f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
82322f70c32Sdrh ** the result set of that SELECT.
82422f70c32Sdrh */
82522f70c32Sdrh Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
82622f70c32Sdrh   Table *pTab;
82722f70c32Sdrh   int i;
82822f70c32Sdrh   ExprList *pEList;
82922f70c32Sdrh 
83022f70c32Sdrh   if( fillInColumnList(pParse, pSelect) ){
83122f70c32Sdrh     return 0;
83222f70c32Sdrh   }
83322f70c32Sdrh   pTab = sqliteMalloc( sizeof(Table) );
83422f70c32Sdrh   if( pTab==0 ){
83522f70c32Sdrh     return 0;
83622f70c32Sdrh   }
83722f70c32Sdrh   pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
83822f70c32Sdrh   pEList = pSelect->pEList;
83922f70c32Sdrh   pTab->nCol = pEList->nExpr;
840417be79cSdrh   assert( pTab->nCol>0 );
84122f70c32Sdrh   pTab->aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
84222f70c32Sdrh   for(i=0; i<pTab->nCol; i++){
84322f70c32Sdrh     Expr *p;
84422f70c32Sdrh     if( pEList->a[i].zName ){
84522f70c32Sdrh       pTab->aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
8466977fea8Sdrh     }else if( (p=pEList->a[i].pExpr)->span.z && p->span.z[0] ){
8476977fea8Sdrh       sqliteSetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
848d820cb1bSdrh     }else if( p->op==TK_DOT && p->pRight && p->pRight->token.z &&
849d820cb1bSdrh            p->pRight->token.z[0] ){
850d820cb1bSdrh       sqliteSetNString(&pTab->aCol[i].zName,
851d820cb1bSdrh            p->pRight->token.z, p->pRight->token.n, 0);
85222f70c32Sdrh     }else{
85322f70c32Sdrh       char zBuf[30];
85422f70c32Sdrh       sprintf(zBuf, "column%d", i+1);
85522f70c32Sdrh       pTab->aCol[i].zName = sqliteStrDup(zBuf);
85622f70c32Sdrh     }
85722f70c32Sdrh   }
85822f70c32Sdrh   pTab->iPKey = -1;
85922f70c32Sdrh   return pTab;
86022f70c32Sdrh }
86122f70c32Sdrh 
86222f70c32Sdrh /*
863ad2d8307Sdrh ** For the given SELECT statement, do three things.
864d8bc7086Sdrh **
865ad3cab52Sdrh **    (1)  Fill in the pTabList->a[].pTab fields in the SrcList that
866967e8b73Sdrh **         defines the set of tables that should be scanned.
867d8bc7086Sdrh **
868ad2d8307Sdrh **    (2)  Add terms to the WHERE clause to accomodate the NATURAL keyword
869ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
870ad2d8307Sdrh **
871ad2d8307Sdrh **    (3)  Scan the list of columns in the result set (pEList) looking
87254473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
87354473229Sdrh **         If found, expand each "*" to be every column in every table
87454473229Sdrh **         and TABLE.* to be every column in TABLE.
875d8bc7086Sdrh **
876d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
877d8bc7086Sdrh ** in pParse and return non-zero.
878d8bc7086Sdrh */
879d8bc7086Sdrh static int fillInColumnList(Parse *pParse, Select *p){
88054473229Sdrh   int i, j, k, rc;
881ad3cab52Sdrh   SrcList *pTabList;
882daffd0e5Sdrh   ExprList *pEList;
883a76b5dfcSdrh   Table *pTab;
884daffd0e5Sdrh 
885daffd0e5Sdrh   if( p==0 || p->pSrc==0 ) return 1;
886daffd0e5Sdrh   pTabList = p->pSrc;
887daffd0e5Sdrh   pEList = p->pEList;
888d8bc7086Sdrh 
889d8bc7086Sdrh   /* Look up every table in the table list.
890d8bc7086Sdrh   */
891ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
892d8bc7086Sdrh     if( pTabList->a[i].pTab ){
893d8bc7086Sdrh       /* This routine has run before!  No need to continue */
894d8bc7086Sdrh       return 0;
895d8bc7086Sdrh     }
896daffd0e5Sdrh     if( pTabList->a[i].zName==0 ){
89722f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
89822f70c32Sdrh       assert( pTabList->a[i].pSelect!=0 );
899ad2d8307Sdrh       if( pTabList->a[i].zAlias==0 ){
900ad2d8307Sdrh         char zFakeName[60];
901ad2d8307Sdrh         sprintf(zFakeName, "sqlite_subquery_%p_",
902ad2d8307Sdrh            (void*)pTabList->a[i].pSelect);
903ad2d8307Sdrh         sqliteSetString(&pTabList->a[i].zAlias, zFakeName, 0);
904ad2d8307Sdrh       }
90522f70c32Sdrh       pTabList->a[i].pTab = pTab =
90622f70c32Sdrh         sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias,
90722f70c32Sdrh                                         pTabList->a[i].pSelect);
90822f70c32Sdrh       if( pTab==0 ){
909daffd0e5Sdrh         return 1;
910daffd0e5Sdrh       }
91122f70c32Sdrh       pTab->isTransient = 1;
91222f70c32Sdrh     }else{
913a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
914a76b5dfcSdrh       pTabList->a[i].pTab = pTab =
915a76b5dfcSdrh         sqliteFindTable(pParse->db, pTabList->a[i].zName);
916a76b5dfcSdrh       if( pTab==0 ){
917d8bc7086Sdrh         sqliteSetString(&pParse->zErrMsg, "no such table: ",
918d8bc7086Sdrh            pTabList->a[i].zName, 0);
919d8bc7086Sdrh         pParse->nErr++;
920d8bc7086Sdrh         return 1;
921d8bc7086Sdrh       }
922a76b5dfcSdrh       if( pTab->pSelect ){
923417be79cSdrh         if( sqliteViewGetColumnNames(pParse, pTab) ){
924417be79cSdrh           return 1;
925417be79cSdrh         }
926d94a6698Sdrh         sqliteSelectDelete(pTabList->a[i].pSelect);
927ff78bd2fSdrh         pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect);
928a76b5dfcSdrh       }
929d8bc7086Sdrh     }
93022f70c32Sdrh   }
931d8bc7086Sdrh 
932ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
933ad2d8307Sdrh   */
934ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
935ad2d8307Sdrh 
9367c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
93754473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
93854473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
9397c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
9407c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
9417c917d19Sdrh   ** each one to the list of all columns in all tables.
94254473229Sdrh   **
94354473229Sdrh   ** The first loop just checks to see if there are any "*" operators
94454473229Sdrh   ** that need expanding.
945d8bc7086Sdrh   */
9467c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
94754473229Sdrh     Expr *pE = pEList->a[k].pExpr;
94854473229Sdrh     if( pE->op==TK_ALL ) break;
94954473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
95054473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
9517c917d19Sdrh   }
95254473229Sdrh   rc = 0;
9537c917d19Sdrh   if( k<pEList->nExpr ){
95454473229Sdrh     /*
95554473229Sdrh     ** If we get here it means the result set contains one or more "*"
95654473229Sdrh     ** operators that need to be expanded.  Loop through each expression
95754473229Sdrh     ** in the result set and expand them one by one.
95854473229Sdrh     */
9597c917d19Sdrh     struct ExprList_item *a = pEList->a;
9607c917d19Sdrh     ExprList *pNew = 0;
9617c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
96254473229Sdrh       Expr *pE = a[k].pExpr;
96354473229Sdrh       if( pE->op!=TK_ALL &&
96454473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
96554473229Sdrh         /* This particular expression does not need to be expanded.
96654473229Sdrh         */
9677c917d19Sdrh         pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
9687c917d19Sdrh         pNew->a[pNew->nExpr-1].zName = a[k].zName;
9697c917d19Sdrh         a[k].pExpr = 0;
9707c917d19Sdrh         a[k].zName = 0;
9717c917d19Sdrh       }else{
97254473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
97354473229Sdrh         ** expanded. */
97454473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
97554473229Sdrh         Token *pName;           /* text of name of TABLE */
97654473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
97754473229Sdrh           pName = &pE->pLeft->token;
97854473229Sdrh         }else{
97954473229Sdrh           pName = 0;
98054473229Sdrh         }
981ad3cab52Sdrh         for(i=0; i<pTabList->nSrc; i++){
982d8bc7086Sdrh           Table *pTab = pTabList->a[i].pTab;
98354473229Sdrh           char *zTabName = pTabList->a[i].zAlias;
98454473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
98554473229Sdrh             zTabName = pTab->zName;
98654473229Sdrh           }
98754473229Sdrh           if( pName && (zTabName==0 || zTabName[0]==0 ||
988c754fa54Sdrh                  sqliteStrNICmp(pName->z, zTabName, pName->n)!=0 ||
989c754fa54Sdrh                  zTabName[pName->n]!=0) ){
99054473229Sdrh             continue;
99154473229Sdrh           }
99254473229Sdrh           tableSeen = 1;
993d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
99422f70c32Sdrh             Expr *pExpr, *pLeft, *pRight;
995ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
996ad2d8307Sdrh 
997ad2d8307Sdrh             if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
998ad2d8307Sdrh                 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
999ad2d8307Sdrh               /* In a NATURAL join, omit the join columns from the
1000ad2d8307Sdrh               ** table on the right */
1001ad2d8307Sdrh               continue;
1002ad2d8307Sdrh             }
1003ad2d8307Sdrh             if( i>0 && sqliteIdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
1004ad2d8307Sdrh               /* In a join with a USING clause, omit columns in the
1005ad2d8307Sdrh               ** using clause from the table on the right. */
1006ad2d8307Sdrh               continue;
1007ad2d8307Sdrh             }
100822f70c32Sdrh             pRight = sqliteExpr(TK_ID, 0, 0, 0);
100922f70c32Sdrh             if( pRight==0 ) break;
1010ad2d8307Sdrh             pRight->token.z = zName;
1011ad2d8307Sdrh             pRight->token.n = strlen(zName);
10124b59ab5eSdrh             pRight->token.dyn = 0;
10134b59ab5eSdrh             if( zTabName && pTabList->nSrc>1 ){
101422f70c32Sdrh               pLeft = sqliteExpr(TK_ID, 0, 0, 0);
101522f70c32Sdrh               pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
101622f70c32Sdrh               if( pExpr==0 ) break;
10174b59ab5eSdrh               pLeft->token.z = zTabName;
10184b59ab5eSdrh               pLeft->token.n = strlen(zTabName);
10194b59ab5eSdrh               pLeft->token.dyn = 0;
10206977fea8Sdrh               sqliteSetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
10216977fea8Sdrh               pExpr->span.n = strlen(pExpr->span.z);
10226977fea8Sdrh               pExpr->span.dyn = 1;
10236977fea8Sdrh               pExpr->token.z = 0;
10246977fea8Sdrh               pExpr->token.n = 0;
10256977fea8Sdrh               pExpr->token.dyn = 0;
102622f70c32Sdrh             }else{
102722f70c32Sdrh               pExpr = pRight;
10286977fea8Sdrh               pExpr->span = pExpr->token;
102922f70c32Sdrh             }
10307c917d19Sdrh             pNew = sqliteExprListAppend(pNew, pExpr, 0);
1031d8bc7086Sdrh           }
1032d8bc7086Sdrh         }
103354473229Sdrh         if( !tableSeen ){
1034f5db2d3eSdrh           if( pName ){
103554473229Sdrh             sqliteSetNString(&pParse->zErrMsg, "no such table: ", -1,
103654473229Sdrh               pName->z, pName->n, 0);
1037f5db2d3eSdrh           }else{
1038f5db2d3eSdrh             sqliteSetString(&pParse->zErrMsg, "no tables specified", 0);
1039f5db2d3eSdrh           }
104054473229Sdrh           rc = 1;
104154473229Sdrh         }
10427c917d19Sdrh       }
10437c917d19Sdrh     }
10447c917d19Sdrh     sqliteExprListDelete(pEList);
10457c917d19Sdrh     p->pEList = pNew;
1046d8bc7086Sdrh   }
104754473229Sdrh   return rc;
1048d8bc7086Sdrh }
1049d8bc7086Sdrh 
1050d8bc7086Sdrh /*
1051ff78bd2fSdrh ** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1052ff78bd2fSdrh ** in a select structure.  It just sets the pointers to NULL.  This
1053ff78bd2fSdrh ** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1054ff78bd2fSdrh ** pointer is not NULL, this routine is called recursively on that pointer.
1055ff78bd2fSdrh **
1056ff78bd2fSdrh ** This routine is called on the Select structure that defines a
1057ff78bd2fSdrh ** VIEW in order to undo any bindings to tables.  This is necessary
1058ff78bd2fSdrh ** because those tables might be DROPed by a subsequent SQL command.
1059ff78bd2fSdrh */
1060ff78bd2fSdrh void sqliteSelectUnbind(Select *p){
1061ff78bd2fSdrh   int i;
1062ad3cab52Sdrh   SrcList *pSrc = p->pSrc;
1063ff78bd2fSdrh   Table *pTab;
1064ff78bd2fSdrh   if( p==0 ) return;
1065ad3cab52Sdrh   for(i=0; i<pSrc->nSrc; i++){
1066ff78bd2fSdrh     if( (pTab = pSrc->a[i].pTab)!=0 ){
1067ff78bd2fSdrh       if( pTab->isTransient ){
1068ff78bd2fSdrh         sqliteDeleteTable(0, pTab);
10694b59ab5eSdrh #if 0
1070ff78bd2fSdrh         sqliteSelectDelete(pSrc->a[i].pSelect);
1071ff78bd2fSdrh         pSrc->a[i].pSelect = 0;
10724b59ab5eSdrh #endif
1073ff78bd2fSdrh       }
1074ff78bd2fSdrh       pSrc->a[i].pTab = 0;
1075ff78bd2fSdrh       if( pSrc->a[i].pSelect ){
1076ff78bd2fSdrh         sqliteSelectUnbind(pSrc->a[i].pSelect);
1077ff78bd2fSdrh       }
1078ff78bd2fSdrh     }
1079ff78bd2fSdrh   }
1080ff78bd2fSdrh }
1081ff78bd2fSdrh 
1082ff78bd2fSdrh /*
1083d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with
1084d8bc7086Sdrh ** columns in a result.  For each ORDER BY expression, the opcode of
1085967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of
1086d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable
1087d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter.
1088d8bc7086Sdrh **
1089d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first.  A match
1090d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT.
1091d8bc7086Sdrh **
1092d8bc7086Sdrh ** Any entry that does not match is flagged as an error.  The number
1093d8bc7086Sdrh ** of errors is returned.
1094fcb78a49Sdrh **
1095fcb78a49Sdrh ** This routine does NOT correctly initialize the Expr.dataType  field
1096fcb78a49Sdrh ** of the ORDER BY expressions.  The multiSelectSortOrder() routine
1097fcb78a49Sdrh ** must be called to do that after the individual select statements
1098fcb78a49Sdrh ** have all been analyzed.  This routine is unable to compute Expr.dataType
1099fcb78a49Sdrh ** because it must be called before the individual select statements
1100fcb78a49Sdrh ** have been analyzed.
1101d8bc7086Sdrh */
1102d8bc7086Sdrh static int matchOrderbyToColumn(
1103d8bc7086Sdrh   Parse *pParse,          /* A place to leave error messages */
1104d8bc7086Sdrh   Select *pSelect,        /* Match to result columns of this SELECT */
1105d8bc7086Sdrh   ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
1106e4de1febSdrh   int iTable,             /* Insert this value in iTable */
1107d8bc7086Sdrh   int mustComplete        /* If TRUE all ORDER BYs must match */
1108d8bc7086Sdrh ){
1109d8bc7086Sdrh   int nErr = 0;
1110d8bc7086Sdrh   int i, j;
1111d8bc7086Sdrh   ExprList *pEList;
1112d8bc7086Sdrh 
1113daffd0e5Sdrh   if( pSelect==0 || pOrderBy==0 ) return 1;
1114d8bc7086Sdrh   if( mustComplete ){
1115d8bc7086Sdrh     for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1116d8bc7086Sdrh   }
1117d8bc7086Sdrh   if( fillInColumnList(pParse, pSelect) ){
1118d8bc7086Sdrh     return 1;
1119d8bc7086Sdrh   }
1120d8bc7086Sdrh   if( pSelect->pPrior ){
112192cd52f5Sdrh     if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
112292cd52f5Sdrh       return 1;
112392cd52f5Sdrh     }
1124d8bc7086Sdrh   }
1125d8bc7086Sdrh   pEList = pSelect->pEList;
1126d8bc7086Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
1127d8bc7086Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
1128e4de1febSdrh     int iCol = -1;
1129d8bc7086Sdrh     if( pOrderBy->a[i].done ) continue;
1130e4de1febSdrh     if( sqliteExprIsInteger(pE, &iCol) ){
1131e4de1febSdrh       if( iCol<=0 || iCol>pEList->nExpr ){
1132e4de1febSdrh         char zBuf[200];
1133e4de1febSdrh         sprintf(zBuf,"ORDER BY position %d should be between 1 and %d",
1134e4de1febSdrh            iCol, pEList->nExpr);
1135e4de1febSdrh         sqliteSetString(&pParse->zErrMsg, zBuf, 0);
1136e4de1febSdrh         pParse->nErr++;
1137e4de1febSdrh         nErr++;
1138e4de1febSdrh         break;
1139e4de1febSdrh       }
1140fcb78a49Sdrh       if( !mustComplete ) continue;
1141e4de1febSdrh       iCol--;
1142e4de1febSdrh     }
1143e4de1febSdrh     for(j=0; iCol<0 && j<pEList->nExpr; j++){
11444cfa7934Sdrh       if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
1145a76b5dfcSdrh         char *zName, *zLabel;
1146a76b5dfcSdrh         zName = pEList->a[j].zName;
1147a76b5dfcSdrh         assert( pE->token.z );
1148a76b5dfcSdrh         zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
1149d8bc7086Sdrh         sqliteDequote(zLabel);
1150d8bc7086Sdrh         if( sqliteStrICmp(zName, zLabel)==0 ){
1151e4de1febSdrh           iCol = j;
1152d8bc7086Sdrh         }
11536e142f54Sdrh         sqliteFree(zLabel);
1154d8bc7086Sdrh       }
1155e4de1febSdrh       if( iCol<0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
1156e4de1febSdrh         iCol = j;
1157d8bc7086Sdrh       }
1158e4de1febSdrh     }
1159e4de1febSdrh     if( iCol>=0 ){
1160967e8b73Sdrh       pE->op = TK_COLUMN;
1161e4de1febSdrh       pE->iColumn = iCol;
1162d8bc7086Sdrh       pE->iTable = iTable;
1163d8bc7086Sdrh       pOrderBy->a[i].done = 1;
1164d8bc7086Sdrh     }
1165e4de1febSdrh     if( iCol<0 && mustComplete ){
1166d8bc7086Sdrh       char zBuf[30];
1167d8bc7086Sdrh       sprintf(zBuf,"%d",i+1);
1168d8bc7086Sdrh       sqliteSetString(&pParse->zErrMsg, "ORDER BY term number ", zBuf,
1169d8bc7086Sdrh         " does not match any result column", 0);
1170d8bc7086Sdrh       pParse->nErr++;
1171d8bc7086Sdrh       nErr++;
1172d8bc7086Sdrh       break;
1173d8bc7086Sdrh     }
1174d8bc7086Sdrh   }
1175d8bc7086Sdrh   return nErr;
1176d8bc7086Sdrh }
1177d8bc7086Sdrh 
1178d8bc7086Sdrh /*
1179d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1180d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1181d8bc7086Sdrh */
1182d8bc7086Sdrh Vdbe *sqliteGetVdbe(Parse *pParse){
1183d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1184d8bc7086Sdrh   if( v==0 ){
11854c504391Sdrh     v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
1186d8bc7086Sdrh   }
1187d8bc7086Sdrh   return v;
1188d8bc7086Sdrh }
1189d8bc7086Sdrh 
1190fcb78a49Sdrh /*
1191fcb78a49Sdrh ** This routine sets the Expr.dataType field on all elements of
1192fcb78a49Sdrh ** the pOrderBy expression list.  The pOrderBy list will have been
1193fcb78a49Sdrh ** set up by matchOrderbyToColumn().  Hence each expression has
1194fcb78a49Sdrh ** a TK_COLUMN as its root node.  The Expr.iColumn refers to a
1195fcb78a49Sdrh ** column in the result set.   The datatype is set to SQLITE_SO_TEXT
1196fcb78a49Sdrh ** if the corresponding column in p and every SELECT to the left of
1197fcb78a49Sdrh ** p has a datatype of SQLITE_SO_TEXT.  If the cooressponding column
1198fcb78a49Sdrh ** in p or any of the left SELECTs is SQLITE_SO_NUM, then the datatype
1199fcb78a49Sdrh ** of the order-by expression is set to SQLITE_SO_NUM.
1200fcb78a49Sdrh **
1201fcb78a49Sdrh ** Examples:
1202fcb78a49Sdrh **
1203e78e8284Sdrh **     CREATE TABLE one(a INTEGER, b TEXT);
1204e78e8284Sdrh **     CREATE TABLE two(c VARCHAR(5), d FLOAT);
1205e78e8284Sdrh **
1206e78e8284Sdrh **     SELECT b, b FROM one UNION SELECT d, c FROM two ORDER BY 1, 2;
1207e78e8284Sdrh **
1208e78e8284Sdrh ** The primary sort key will use SQLITE_SO_NUM because the "d" in
1209e78e8284Sdrh ** the second SELECT is numeric.  The 1st column of the first SELECT
1210e78e8284Sdrh ** is text but that does not matter because a numeric always overrides
1211e78e8284Sdrh ** a text.
1212e78e8284Sdrh **
1213e78e8284Sdrh ** The secondary key will use the SQLITE_SO_TEXT sort order because
1214e78e8284Sdrh ** both the (second) "b" in the first SELECT and the "c" in the second
1215e78e8284Sdrh ** SELECT have a datatype of text.
1216fcb78a49Sdrh */
1217fcb78a49Sdrh static void multiSelectSortOrder(Select *p, ExprList *pOrderBy){
1218fcb78a49Sdrh   int i;
1219fcb78a49Sdrh   ExprList *pEList;
1220fcb78a49Sdrh   if( pOrderBy==0 ) return;
1221fcb78a49Sdrh   if( p==0 ){
1222fcb78a49Sdrh     for(i=0; i<pOrderBy->nExpr; i++){
1223fcb78a49Sdrh       pOrderBy->a[i].pExpr->dataType = SQLITE_SO_TEXT;
1224fcb78a49Sdrh     }
1225fcb78a49Sdrh     return;
1226fcb78a49Sdrh   }
1227fcb78a49Sdrh   multiSelectSortOrder(p->pPrior, pOrderBy);
1228fcb78a49Sdrh   pEList = p->pEList;
1229fcb78a49Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
1230fcb78a49Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
1231fcb78a49Sdrh     if( pE->dataType==SQLITE_SO_NUM ) continue;
1232fcb78a49Sdrh     assert( pE->iColumn>=0 );
1233fcb78a49Sdrh     if( pEList->nExpr>pE->iColumn ){
1234fcb78a49Sdrh       pE->dataType = sqliteExprType(pEList->a[pE->iColumn].pExpr);
1235fcb78a49Sdrh     }
1236fcb78a49Sdrh   }
1237fcb78a49Sdrh }
1238d8bc7086Sdrh 
1239d8bc7086Sdrh /*
124082c3d636Sdrh ** This routine is called to process a query that is really the union
124182c3d636Sdrh ** or intersection of two or more separate queries.
1242c926afbcSdrh **
1243e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1244e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1245e78e8284Sdrh ** in which case this routine will be called recursively.
1246e78e8284Sdrh **
1247e78e8284Sdrh ** The results of the total query are to be written into a destination
1248e78e8284Sdrh ** of type eDest with parameter iParm.
1249e78e8284Sdrh **
1250e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1251e78e8284Sdrh **
1252e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1253e78e8284Sdrh **
1254e78e8284Sdrh ** This statement is parsed up as follows:
1255e78e8284Sdrh **
1256e78e8284Sdrh **     SELECT c FROM t3
1257e78e8284Sdrh **      |
1258e78e8284Sdrh **      `----->  SELECT b FROM t2
1259e78e8284Sdrh **                |
1260e78e8284Sdrh **                `------>  SELECT c FROM t1
1261e78e8284Sdrh **
1262e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1263e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1264e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1265e78e8284Sdrh **
1266e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1267e78e8284Sdrh ** individual selects always group from left to right.
126882c3d636Sdrh */
126982c3d636Sdrh static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
127010e5e3cfSdrh   int rc;             /* Success code from a subroutine */
127110e5e3cfSdrh   Select *pPrior;     /* Another SELECT immediately to our left */
127210e5e3cfSdrh   Vdbe *v;            /* Generate code to this VDBE */
127382c3d636Sdrh 
1274d8bc7086Sdrh   /* Make sure there is no ORDER BY clause on prior SELECTs.  Only the
1275d8bc7086Sdrh   ** last SELECT in the series may have an ORDER BY.
127682c3d636Sdrh   */
1277daffd0e5Sdrh   if( p==0 || p->pPrior==0 ) return 1;
1278d8bc7086Sdrh   pPrior = p->pPrior;
1279d8bc7086Sdrh   if( pPrior->pOrderBy ){
1280d8bc7086Sdrh     sqliteSetString(&pParse->zErrMsg,"ORDER BY clause should come after ",
1281d8bc7086Sdrh       selectOpName(p->op), " not before", 0);
128282c3d636Sdrh     pParse->nErr++;
128382c3d636Sdrh     return 1;
128482c3d636Sdrh   }
128582c3d636Sdrh 
1286d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
1287d8bc7086Sdrh   */
1288d8bc7086Sdrh   v = sqliteGetVdbe(pParse);
1289d8bc7086Sdrh   if( v==0 ) return 1;
1290d8bc7086Sdrh 
12911cc3d75fSdrh   /* Create the destination temporary table if necessary
12921cc3d75fSdrh   */
12931cc3d75fSdrh   if( eDest==SRT_TempTable ){
12941cc3d75fSdrh     sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
12951cc3d75fSdrh     eDest = SRT_Table;
12961cc3d75fSdrh   }
12971cc3d75fSdrh 
1298f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1299d8bc7086Sdrh   */
130082c3d636Sdrh   switch( p->op ){
1301f46f905aSdrh     case TK_ALL: {
1302f46f905aSdrh       if( p->pOrderBy==0 ){
1303f46f905aSdrh         rc = sqliteSelect(pParse, pPrior, eDest, iParm, 0, 0, 0);
1304f46f905aSdrh         if( rc ) return rc;
1305f46f905aSdrh         p->pPrior = 0;
1306f46f905aSdrh         rc = sqliteSelect(pParse, p, eDest, iParm, 0, 0, 0);
1307f46f905aSdrh         p->pPrior = pPrior;
1308f46f905aSdrh         if( rc ) return rc;
1309f46f905aSdrh         break;
1310f46f905aSdrh       }
1311f46f905aSdrh       /* For UNION ALL ... ORDER BY fall through to the next case */
1312f46f905aSdrh     }
131382c3d636Sdrh     case TK_EXCEPT:
131482c3d636Sdrh     case TK_UNION: {
1315d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1316d8bc7086Sdrh       int op;          /* One of the SRT_ operations to apply to self */
1317d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
1318c926afbcSdrh       ExprList *pOrderBy;  /* The ORDER BY clause for the right SELECT */
131982c3d636Sdrh 
1320d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
1321c926afbcSdrh       if( eDest==priorOp && p->pOrderBy==0 ){
1322d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1323c926afbcSdrh         ** right.
1324d8bc7086Sdrh         */
132582c3d636Sdrh         unionTab = iParm;
132682c3d636Sdrh       }else{
1327d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1328d8bc7086Sdrh         ** intermediate results.
1329d8bc7086Sdrh         */
133082c3d636Sdrh         unionTab = pParse->nTab++;
1331d8bc7086Sdrh         if( p->pOrderBy
1332d8bc7086Sdrh         && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
1333d8bc7086Sdrh           return 1;
1334d8bc7086Sdrh         }
1335d8bc7086Sdrh         if( p->op!=TK_ALL ){
1336c6b52df3Sdrh           sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
133799fcd718Sdrh           sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
1338345fda3eSdrh         }else{
133999fcd718Sdrh           sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
134082c3d636Sdrh         }
1341d8bc7086Sdrh       }
1342d8bc7086Sdrh 
1343d8bc7086Sdrh       /* Code the SELECT statements to our left
1344d8bc7086Sdrh       */
1345832508b7Sdrh       rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
134682c3d636Sdrh       if( rc ) return rc;
1347d8bc7086Sdrh 
1348d8bc7086Sdrh       /* Code the current SELECT statement
1349d8bc7086Sdrh       */
1350d8bc7086Sdrh       switch( p->op ){
1351d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
1352d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
1353d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
1354d8bc7086Sdrh       }
135582c3d636Sdrh       p->pPrior = 0;
1356c926afbcSdrh       pOrderBy = p->pOrderBy;
1357c926afbcSdrh       p->pOrderBy = 0;
1358832508b7Sdrh       rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0);
135982c3d636Sdrh       p->pPrior = pPrior;
1360c926afbcSdrh       p->pOrderBy = pOrderBy;
136182c3d636Sdrh       if( rc ) return rc;
1362d8bc7086Sdrh 
1363d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1364d8bc7086Sdrh       ** it is that we currently need.
1365d8bc7086Sdrh       */
1366c926afbcSdrh       if( eDest!=priorOp || unionTab!=iParm ){
13676b56344dSdrh         int iCont, iBreak, iStart;
136882c3d636Sdrh         assert( p->pEList );
136941202ccaSdrh         if( eDest==SRT_Callback ){
1370832508b7Sdrh           generateColumnNames(pParse, p->base, 0, p->pEList);
1371fcb78a49Sdrh           generateColumnTypes(pParse, p->base, p->pSrc, p->pEList);
137241202ccaSdrh         }
137382c3d636Sdrh         iBreak = sqliteVdbeMakeLabel(v);
13746b56344dSdrh         iCont = sqliteVdbeMakeLabel(v);
13756b56344dSdrh         sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
13766b56344dSdrh         iStart = sqliteVdbeCurrentAddr(v);
1377fcb78a49Sdrh         multiSelectSortOrder(p, p->pOrderBy);
137838640e15Sdrh         rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
1379d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
138082c3d636Sdrh                              iCont, iBreak);
138182c3d636Sdrh         if( rc ) return 1;
13826b56344dSdrh         sqliteVdbeResolveLabel(v, iCont);
13836b56344dSdrh         sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
138499fcd718Sdrh         sqliteVdbeResolveLabel(v, iBreak);
138599fcd718Sdrh         sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
1386d8bc7086Sdrh         if( p->pOrderBy ){
1387c926afbcSdrh           generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
1388d8bc7086Sdrh         }
138982c3d636Sdrh       }
139082c3d636Sdrh       break;
139182c3d636Sdrh     }
139282c3d636Sdrh     case TK_INTERSECT: {
139382c3d636Sdrh       int tab1, tab2;
13946b56344dSdrh       int iCont, iBreak, iStart;
139582c3d636Sdrh 
1396d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
13976206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
1398d8bc7086Sdrh       ** by allocating the tables we will need.
1399d8bc7086Sdrh       */
140082c3d636Sdrh       tab1 = pParse->nTab++;
140182c3d636Sdrh       tab2 = pParse->nTab++;
1402d8bc7086Sdrh       if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
1403d8bc7086Sdrh         return 1;
1404d8bc7086Sdrh       }
1405c6b52df3Sdrh       sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
140699fcd718Sdrh       sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
1407d8bc7086Sdrh 
1408d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1409d8bc7086Sdrh       */
1410832508b7Sdrh       rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
141182c3d636Sdrh       if( rc ) return rc;
1412d8bc7086Sdrh 
1413d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1414d8bc7086Sdrh       */
1415c6b52df3Sdrh       sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
141699fcd718Sdrh       sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
141782c3d636Sdrh       p->pPrior = 0;
1418832508b7Sdrh       rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0);
141982c3d636Sdrh       p->pPrior = pPrior;
142082c3d636Sdrh       if( rc ) return rc;
1421d8bc7086Sdrh 
1422d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1423d8bc7086Sdrh       ** tables.
1424d8bc7086Sdrh       */
142582c3d636Sdrh       assert( p->pEList );
142641202ccaSdrh       if( eDest==SRT_Callback ){
1427832508b7Sdrh         generateColumnNames(pParse, p->base, 0, p->pEList);
1428fcb78a49Sdrh         generateColumnTypes(pParse, p->base, p->pSrc, p->pEList);
142941202ccaSdrh       }
143082c3d636Sdrh       iBreak = sqliteVdbeMakeLabel(v);
14316b56344dSdrh       iCont = sqliteVdbeMakeLabel(v);
14326b56344dSdrh       sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
14336b56344dSdrh       iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
143499fcd718Sdrh       sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
1435fcb78a49Sdrh       multiSelectSortOrder(p, p->pOrderBy);
143638640e15Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
1437d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
143882c3d636Sdrh                              iCont, iBreak);
143982c3d636Sdrh       if( rc ) return 1;
14406b56344dSdrh       sqliteVdbeResolveLabel(v, iCont);
14416b56344dSdrh       sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
144299fcd718Sdrh       sqliteVdbeResolveLabel(v, iBreak);
144399fcd718Sdrh       sqliteVdbeAddOp(v, OP_Close, tab2, 0);
144499fcd718Sdrh       sqliteVdbeAddOp(v, OP_Close, tab1, 0);
1445d8bc7086Sdrh       if( p->pOrderBy ){
1446c926afbcSdrh         generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
1447d8bc7086Sdrh       }
144882c3d636Sdrh       break;
144982c3d636Sdrh     }
145082c3d636Sdrh   }
145182c3d636Sdrh   assert( p->pEList && pPrior->pEList );
145282c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
1453d8bc7086Sdrh     sqliteSetString(&pParse->zErrMsg, "SELECTs to the left and right of ",
1454d8bc7086Sdrh       selectOpName(p->op), " do not have the same number of result columns", 0);
145582c3d636Sdrh     pParse->nErr++;
145682c3d636Sdrh     return 1;
14572282792aSdrh   }
1458fcb78a49Sdrh 
1459fcb78a49Sdrh   /* Issue a null callback if that is what the user wants.
1460fcb78a49Sdrh   */
1461326dce74Sdrh   if( eDest==SRT_Callback &&
1462326dce74Sdrh     (pParse->useCallback==0 || (pParse->db->flags & SQLITE_NullCallback)!=0)
1463326dce74Sdrh   ){
1464fcb78a49Sdrh     sqliteVdbeAddOp(v, OP_NullCallback, p->pEList->nExpr, 0);
1465fcb78a49Sdrh   }
14662282792aSdrh   return 0;
14672282792aSdrh }
14682282792aSdrh 
14692282792aSdrh /*
1470832508b7Sdrh ** Recursively scan through an expression tree.  For every reference
1471832508b7Sdrh ** to a column in table number iFrom, change that reference to the
1472832508b7Sdrh ** same column in table number iTo.
1473832508b7Sdrh */
1474315555caSdrh static void changeTablesInList(ExprList*, int, int);  /* Forward Declaration */
1475832508b7Sdrh static void changeTables(Expr *pExpr, int iFrom, int iTo){
1476832508b7Sdrh   if( pExpr==0 ) return;
1477832508b7Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iFrom ){
1478832508b7Sdrh     pExpr->iTable = iTo;
1479832508b7Sdrh   }else{
1480832508b7Sdrh     changeTables(pExpr->pLeft, iFrom, iTo);
1481832508b7Sdrh     changeTables(pExpr->pRight, iFrom, iTo);
14821b2e0329Sdrh     changeTablesInList(pExpr->pList, iFrom, iTo);
1483832508b7Sdrh   }
1484832508b7Sdrh }
14851b2e0329Sdrh static void changeTablesInList(ExprList *pList, int iFrom, int iTo){
14861b2e0329Sdrh   if( pList ){
14871b2e0329Sdrh     int i;
14881b2e0329Sdrh     for(i=0; i<pList->nExpr; i++){
14891b2e0329Sdrh       changeTables(pList->a[i].pExpr, iFrom, iTo);
14901b2e0329Sdrh     }
1491832508b7Sdrh   }
1492832508b7Sdrh }
1493832508b7Sdrh 
1494832508b7Sdrh /*
1495832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
1496832508b7Sdrh ** a column in table number iTable with a copy of the corresponding
149784e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
149884e59207Sdrh ** unchanged.)  When making a copy of an expression in pEList, change
149984e59207Sdrh ** references to columns in table iSub into references to table iTable.
1500832508b7Sdrh **
1501832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
1502832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
1503832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
1504832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
1505832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
1506832508b7Sdrh ** of the subquery rather the result set of the subquery.
1507832508b7Sdrh */
1508315555caSdrh static void substExprList(ExprList*,int,ExprList*,int);  /* Forward Decl */
1509832508b7Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList, int iSub){
1510832508b7Sdrh   if( pExpr==0 ) return;
151184e59207Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable && pExpr->iColumn>=0 ){
1512832508b7Sdrh     Expr *pNew;
151384e59207Sdrh     assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1514832508b7Sdrh     assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1515832508b7Sdrh     pNew = pEList->a[pExpr->iColumn].pExpr;
1516832508b7Sdrh     assert( pNew!=0 );
1517832508b7Sdrh     pExpr->op = pNew->op;
1518fcb78a49Sdrh     pExpr->dataType = pNew->dataType;
1519d94a6698Sdrh     assert( pExpr->pLeft==0 );
1520832508b7Sdrh     pExpr->pLeft = sqliteExprDup(pNew->pLeft);
1521d94a6698Sdrh     assert( pExpr->pRight==0 );
1522832508b7Sdrh     pExpr->pRight = sqliteExprDup(pNew->pRight);
1523d94a6698Sdrh     assert( pExpr->pList==0 );
1524832508b7Sdrh     pExpr->pList = sqliteExprListDup(pNew->pList);
1525832508b7Sdrh     pExpr->iTable = pNew->iTable;
1526832508b7Sdrh     pExpr->iColumn = pNew->iColumn;
1527832508b7Sdrh     pExpr->iAgg = pNew->iAgg;
15284b59ab5eSdrh     sqliteTokenCopy(&pExpr->token, &pNew->token);
15296977fea8Sdrh     sqliteTokenCopy(&pExpr->span, &pNew->span);
1530832508b7Sdrh     if( iSub!=iTable ){
1531832508b7Sdrh       changeTables(pExpr, iSub, iTable);
1532832508b7Sdrh     }
1533832508b7Sdrh   }else{
1534832508b7Sdrh     substExpr(pExpr->pLeft, iTable, pEList, iSub);
1535832508b7Sdrh     substExpr(pExpr->pRight, iTable, pEList, iSub);
1536832508b7Sdrh     substExprList(pExpr->pList, iTable, pEList, iSub);
1537832508b7Sdrh   }
1538832508b7Sdrh }
1539832508b7Sdrh static void
1540832508b7Sdrh substExprList(ExprList *pList, int iTable, ExprList *pEList, int iSub){
1541832508b7Sdrh   int i;
1542832508b7Sdrh   if( pList==0 ) return;
1543832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
1544832508b7Sdrh     substExpr(pList->a[i].pExpr, iTable, pEList, iSub);
1545832508b7Sdrh   }
1546832508b7Sdrh }
1547832508b7Sdrh 
1548832508b7Sdrh /*
15491350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
15501350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
15511350b030Sdrh ** occurs.
15521350b030Sdrh **
15531350b030Sdrh ** To understand the concept of flattening, consider the following
15541350b030Sdrh ** query:
15551350b030Sdrh **
15561350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
15571350b030Sdrh **
15581350b030Sdrh ** The default way of implementing this query is to execute the
15591350b030Sdrh ** subquery first and store the results in a temporary table, then
15601350b030Sdrh ** run the outer query on that temporary table.  This requires two
15611350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
15621350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
1563832508b7Sdrh ** optimized.
15641350b030Sdrh **
1565832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
15661350b030Sdrh ** a single flat select, like this:
15671350b030Sdrh **
15681350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
15691350b030Sdrh **
15701350b030Sdrh ** The code generated for this simpification gives the same result
1571832508b7Sdrh ** but only has to scan the data once.  And because indices might
1572832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
1573832508b7Sdrh ** avoided.
15741350b030Sdrh **
1575832508b7Sdrh ** Flattening is only attempted if all of the following are true:
15761350b030Sdrh **
1577832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
15781350b030Sdrh **
1579832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
1580832508b7Sdrh **
1581832508b7Sdrh **   (3)  The subquery is not a join.
1582832508b7Sdrh **
1583832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
1584832508b7Sdrh **
1585832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
1586832508b7Sdrh **        aggregates.
1587832508b7Sdrh **
1588832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
1589832508b7Sdrh **        DISTINCT.
1590832508b7Sdrh **
159108192d5fSdrh **   (7)  The subquery has a FROM clause.
159208192d5fSdrh **
1593df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
1594df199a25Sdrh **
1595df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
1596df199a25Sdrh **        aggregates.
1597df199a25Sdrh **
1598df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
1599df199a25Sdrh **        use LIMIT.
1600df199a25Sdrh **
1601174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
1602174b6195Sdrh **
1603832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
1604832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
1605832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1606832508b7Sdrh **
1607832508b7Sdrh ** If flattening is not attempted, this routine is a no-op and return 0.
1608832508b7Sdrh ** If flattening is attempted this routine returns 1.
1609832508b7Sdrh **
1610832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
1611832508b7Sdrh ** the subquery before this routine runs.
16121350b030Sdrh */
16138c74a8caSdrh static int flattenSubquery(
16148c74a8caSdrh   Parse *pParse,       /* The parsing context */
16158c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
16168c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
16178c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
16188c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
16198c74a8caSdrh ){
16200bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
1621ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
1622ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
16230bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
1624832508b7Sdrh   int i;
1625832508b7Sdrh   int iParent, iSub;
1626832508b7Sdrh   Expr *pWhere;
16271350b030Sdrh 
1628832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
1629832508b7Sdrh   */
1630832508b7Sdrh   if( p==0 ) return 0;
1631832508b7Sdrh   pSrc = p->pSrc;
1632ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
1633832508b7Sdrh   pSub = pSrc->a[iFrom].pSelect;
1634832508b7Sdrh   assert( pSub!=0 );
1635832508b7Sdrh   if( isAgg && subqueryIsAgg ) return 0;
1636ad3cab52Sdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
1637832508b7Sdrh   pSubSrc = pSub->pSrc;
1638832508b7Sdrh   assert( pSubSrc );
1639ad3cab52Sdrh   if( pSubSrc->nSrc!=1 ) return 0;
1640df199a25Sdrh   if( (pSub->isDistinct || pSub->nLimit>=0) &&  (pSrc->nSrc>1 || isAgg) ){
1641df199a25Sdrh      return 0;
1642df199a25Sdrh   }
1643d11d382cSdrh   if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
1644174b6195Sdrh   if( p->pOrderBy && pSub->pOrderBy ) return 0;
1645832508b7Sdrh 
16460bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
1647832508b7Sdrh   ** i-th entry of the FROM clause in the outer query.
1648832508b7Sdrh   */
1649832508b7Sdrh   iParent = p->base + iFrom;
1650832508b7Sdrh   iSub = pSub->base;
1651832508b7Sdrh   substExprList(p->pEList, iParent, pSub->pEList, iSub);
1652832508b7Sdrh   pList = p->pEList;
1653832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
16546977fea8Sdrh     Expr *pExpr;
16556977fea8Sdrh     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
16566977fea8Sdrh       pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
1657832508b7Sdrh     }
1658832508b7Sdrh   }
16591b2e0329Sdrh   if( isAgg ){
1660832508b7Sdrh     substExprList(p->pGroupBy, iParent, pSub->pEList, iSub);
1661832508b7Sdrh     substExpr(p->pHaving, iParent, pSub->pEList, iSub);
16621b2e0329Sdrh   }
1663174b6195Sdrh   if( pSub->pOrderBy ){
1664174b6195Sdrh     assert( p->pOrderBy==0 );
1665174b6195Sdrh     p->pOrderBy = pSub->pOrderBy;
1666174b6195Sdrh     pSub->pOrderBy = 0;
1667174b6195Sdrh     changeTablesInList(p->pOrderBy, iSub, iParent);
1668174b6195Sdrh   }else if( p->pOrderBy ){
1669832508b7Sdrh     substExprList(p->pOrderBy, iParent, pSub->pEList, iSub);
1670174b6195Sdrh   }
1671832508b7Sdrh   if( pSub->pWhere ){
1672832508b7Sdrh     pWhere = sqliteExprDup(pSub->pWhere);
1673832508b7Sdrh     if( iParent!=iSub ){
1674832508b7Sdrh       changeTables(pWhere, iSub, iParent);
1675832508b7Sdrh     }
1676832508b7Sdrh   }else{
1677832508b7Sdrh     pWhere = 0;
1678832508b7Sdrh   }
1679832508b7Sdrh   if( subqueryIsAgg ){
1680832508b7Sdrh     assert( p->pHaving==0 );
16811b2e0329Sdrh     p->pHaving = p->pWhere;
16821b2e0329Sdrh     p->pWhere = pWhere;
1683832508b7Sdrh     substExpr(p->pHaving, iParent, pSub->pEList, iSub);
16841b2e0329Sdrh     if( pSub->pHaving ){
16851b2e0329Sdrh       Expr *pHaving = sqliteExprDup(pSub->pHaving);
16861b2e0329Sdrh       if( iParent!=iSub ){
16871b2e0329Sdrh         changeTables(pHaving, iSub, iParent);
16881b2e0329Sdrh       }
16891b2e0329Sdrh       if( p->pHaving ){
16901b2e0329Sdrh         p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0);
16911b2e0329Sdrh       }else{
16921b2e0329Sdrh         p->pHaving = pHaving;
16931b2e0329Sdrh       }
16941b2e0329Sdrh     }
16951b2e0329Sdrh     assert( p->pGroupBy==0 );
16961b2e0329Sdrh     p->pGroupBy = sqliteExprListDup(pSub->pGroupBy);
16971b2e0329Sdrh     if( iParent!=iSub ){
16981b2e0329Sdrh       changeTablesInList(p->pGroupBy, iSub, iParent);
16991b2e0329Sdrh     }
1700832508b7Sdrh   }else if( p->pWhere==0 ){
1701832508b7Sdrh     p->pWhere = pWhere;
1702832508b7Sdrh   }else{
1703832508b7Sdrh     substExpr(p->pWhere, iParent, pSub->pEList, iSub);
1704832508b7Sdrh     if( pWhere ){
1705832508b7Sdrh       p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0);
1706832508b7Sdrh     }
1707832508b7Sdrh   }
1708832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
17098c74a8caSdrh 
1710df199a25Sdrh   if( pSub->nLimit>=0 ){
1711df199a25Sdrh     if( p->nLimit<0 ){
1712df199a25Sdrh       p->nLimit = pSub->nLimit;
1713df199a25Sdrh     }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1714df199a25Sdrh       p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1715df199a25Sdrh     }
1716df199a25Sdrh   }
1717df199a25Sdrh   p->nOffset += pSub->nOffset;
17188c74a8caSdrh 
17198c74a8caSdrh   /* If the subquery contains subqueries of its own, that were not
17208c74a8caSdrh   ** flattened, then code will have already been generated to put
17218c74a8caSdrh   ** the results of those sub-subqueries into VDBE cursors relative
17228c74a8caSdrh   ** to the subquery.  We must translate the cursor number into values
17238c74a8caSdrh   ** suitable for use by the outer query.
17248c74a8caSdrh   */
17258c74a8caSdrh   for(i=0; i<pSubSrc->nSrc; i++){
17268c74a8caSdrh     Vdbe *v;
17278c74a8caSdrh     if( pSubSrc->a[i].pSelect==0 ) continue;
17288c74a8caSdrh     v = sqliteGetVdbe(pParse);
17298c74a8caSdrh     sqliteVdbeAddOp(v, OP_RenameCursor, pSub->base+i, p->base+i);
17308c74a8caSdrh   }
17318c74a8caSdrh 
1732832508b7Sdrh   if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
1733832508b7Sdrh     sqliteDeleteTable(0, pSrc->a[iFrom].pTab);
1734832508b7Sdrh   }
1735832508b7Sdrh   pSrc->a[iFrom].pTab = pSubSrc->a[0].pTab;
1736832508b7Sdrh   pSubSrc->a[0].pTab = 0;
1737d94a6698Sdrh   assert( pSrc->a[iFrom].pSelect==pSub );
1738832508b7Sdrh   pSrc->a[iFrom].pSelect = pSubSrc->a[0].pSelect;
1739832508b7Sdrh   pSubSrc->a[0].pSelect = 0;
1740832508b7Sdrh   sqliteSelectDelete(pSub);
1741832508b7Sdrh   return 1;
17421350b030Sdrh }
17431350b030Sdrh 
17441350b030Sdrh /*
17459562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it
17469562b551Sdrh ** is a simple min() or max() query.  If it is and this query can be
17479562b551Sdrh ** satisfied using a single seek to the beginning or end of an index,
1748e78e8284Sdrh ** then generate the code for this SELECT and return 1.  If this is not a
17499562b551Sdrh ** simple min() or max() query, then return 0;
17509562b551Sdrh **
17519562b551Sdrh ** A simply min() or max() query looks like this:
17529562b551Sdrh **
17539562b551Sdrh **    SELECT min(a) FROM table;
17549562b551Sdrh **    SELECT max(a) FROM table;
17559562b551Sdrh **
17569562b551Sdrh ** The query may have only a single table in its FROM argument.  There
17579562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
17589562b551Sdrh ** be the min() or max() of a single column of the table.  The column
17599562b551Sdrh ** in the min() or max() function must be indexed.
17609562b551Sdrh **
17619562b551Sdrh ** The parameters to this routine are the same as for sqliteSelect().
17629562b551Sdrh ** See the header comment on that routine for additional information.
17639562b551Sdrh */
17649562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
17659562b551Sdrh   Expr *pExpr;
17669562b551Sdrh   int iCol;
17679562b551Sdrh   Table *pTab;
17689562b551Sdrh   Index *pIdx;
17699562b551Sdrh   int base;
17709562b551Sdrh   Vdbe *v;
17719562b551Sdrh   int openOp;
17729562b551Sdrh   int seekOp;
17739562b551Sdrh   int cont;
17749562b551Sdrh   ExprList eList;
17759562b551Sdrh   struct ExprList_item eListItem;
17769562b551Sdrh 
17779562b551Sdrh   /* Check to see if this query is a simple min() or max() query.  Return
17789562b551Sdrh   ** zero if it is  not.
17799562b551Sdrh   */
17809562b551Sdrh   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
1781ad3cab52Sdrh   if( p->pSrc->nSrc!=1 ) return 0;
17829562b551Sdrh   if( p->pEList->nExpr!=1 ) return 0;
17839562b551Sdrh   pExpr = p->pEList->a[0].pExpr;
17849562b551Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
17859562b551Sdrh   if( pExpr->pList==0 || pExpr->pList->nExpr!=1 ) return 0;
17866977fea8Sdrh   if( pExpr->token.n!=3 ) return 0;
17870bce8354Sdrh   if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){
17880bce8354Sdrh     seekOp = OP_Rewind;
17890bce8354Sdrh   }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){
17900bce8354Sdrh     seekOp = OP_Last;
17910bce8354Sdrh   }else{
17920bce8354Sdrh     return 0;
17930bce8354Sdrh   }
17949562b551Sdrh   pExpr = pExpr->pList->a[0].pExpr;
17959562b551Sdrh   if( pExpr->op!=TK_COLUMN ) return 0;
17969562b551Sdrh   iCol = pExpr->iColumn;
17979562b551Sdrh   pTab = p->pSrc->a[0].pTab;
17989562b551Sdrh 
17999562b551Sdrh   /* If we get to here, it means the query is of the correct form.
180017f71934Sdrh   ** Check to make sure we have an index and make pIdx point to the
180117f71934Sdrh   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
180217f71934Sdrh   ** key column, no index is necessary so set pIdx to NULL.  If no
180317f71934Sdrh   ** usable index is found, return 0.
18049562b551Sdrh   */
18059562b551Sdrh   if( iCol<0 ){
18069562b551Sdrh     pIdx = 0;
18079562b551Sdrh   }else{
18089562b551Sdrh     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
18099562b551Sdrh       assert( pIdx->nColumn>=1 );
18109562b551Sdrh       if( pIdx->aiColumn[0]==iCol ) break;
18119562b551Sdrh     }
18129562b551Sdrh     if( pIdx==0 ) return 0;
18139562b551Sdrh   }
18149562b551Sdrh 
181517f71934Sdrh   /* Identify column names if we will be using the callback.  This
18169562b551Sdrh   ** step is skipped if the output is going to a table or a memory cell.
18179562b551Sdrh   */
18189562b551Sdrh   v = sqliteGetVdbe(pParse);
18199562b551Sdrh   if( v==0 ) return 0;
18209562b551Sdrh   if( eDest==SRT_Callback ){
1821832508b7Sdrh     generateColumnNames(pParse, p->base, p->pSrc, p->pEList);
1822fcb78a49Sdrh     generateColumnTypes(pParse, p->base, p->pSrc, p->pEList);
18239562b551Sdrh   }
18249562b551Sdrh 
182517f71934Sdrh   /* Generating code to find the min or the max.  Basically all we have
182617f71934Sdrh   ** to do is find the first or the last entry in the chosen index.  If
182717f71934Sdrh   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
182817f71934Sdrh   ** or last entry in the main table.
18299562b551Sdrh   */
18305cf8e8c7Sdrh   if( !pParse->schemaVerified && (pParse->db->flags & SQLITE_InTrans)==0 ){
18315cf8e8c7Sdrh     sqliteVdbeAddOp(v, OP_VerifyCookie, pParse->db->schema_cookie, 0);
18325cf8e8c7Sdrh     pParse->schemaVerified = 1;
18335cf8e8c7Sdrh   }
18349562b551Sdrh   openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
1835832508b7Sdrh   base = p->base;
18369562b551Sdrh   sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
18375cf8e8c7Sdrh   sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
18389562b551Sdrh   if( pIdx==0 ){
18399562b551Sdrh     sqliteVdbeAddOp(v, seekOp, base, 0);
18409562b551Sdrh   }else{
18419562b551Sdrh     sqliteVdbeAddOp(v, openOp, base+1, pIdx->tnum);
18425cf8e8c7Sdrh     sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
18439562b551Sdrh     sqliteVdbeAddOp(v, seekOp, base+1, 0);
18449562b551Sdrh     sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
18459562b551Sdrh     sqliteVdbeAddOp(v, OP_Close, base+1, 0);
18469562b551Sdrh     sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
18479562b551Sdrh   }
18485cf8e8c7Sdrh   eList.nExpr = 1;
18495cf8e8c7Sdrh   memset(&eListItem, 0, sizeof(eListItem));
18505cf8e8c7Sdrh   eList.a = &eListItem;
18515cf8e8c7Sdrh   eList.a[0].pExpr = pExpr;
18529562b551Sdrh   cont = sqliteVdbeMakeLabel(v);
185338640e15Sdrh   selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont);
18549562b551Sdrh   sqliteVdbeResolveLabel(v, cont);
18559562b551Sdrh   sqliteVdbeAddOp(v, OP_Close, base, 0);
18569562b551Sdrh   return 1;
18579562b551Sdrh }
18589562b551Sdrh 
18599562b551Sdrh /*
18609bb61fe7Sdrh ** Generate code for the given SELECT statement.
18619bb61fe7Sdrh **
1862fef5208cSdrh ** The results are distributed in various ways depending on the
1863fef5208cSdrh ** value of eDest and iParm.
1864fef5208cSdrh **
1865fef5208cSdrh **     eDest Value       Result
1866fef5208cSdrh **     ------------    -------------------------------------------
1867fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
1868fef5208cSdrh **
1869fef5208cSdrh **     SRT_Mem         Store first result in memory cell iParm
1870fef5208cSdrh **
1871fef5208cSdrh **     SRT_Set         Store results as keys of a table with cursor iParm
1872fef5208cSdrh **
187382c3d636Sdrh **     SRT_Union       Store results as a key in a temporary table iParm
187482c3d636Sdrh **
1875c4a3c779Sdrh **     SRT_Except      Remove results form the temporary table iParm.
1876c4a3c779Sdrh **
1877c4a3c779Sdrh **     SRT_Table       Store results in temporary table iParm
18789bb61fe7Sdrh **
1879e78e8284Sdrh ** The table above is incomplete.  Additional eDist value have be added
1880e78e8284Sdrh ** since this comment was written.  See the selectInnerLoop() function for
1881e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings.
1882e78e8284Sdrh **
18839bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
18849bb61fe7Sdrh ** encountered, then an appropriate error message is left in
18859bb61fe7Sdrh ** pParse->zErrMsg.
18869bb61fe7Sdrh **
18879bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
18889bb61fe7Sdrh ** calling function needs to do that.
18891b2e0329Sdrh **
18901b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
18911b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
18921b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
18931b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
18941b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
18951b2e0329Sdrh ** can be changed.
1896e78e8284Sdrh **
1897e78e8284Sdrh ** Example 1:   The meaning of the pParent parameter.
1898e78e8284Sdrh **
1899e78e8284Sdrh **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
1900e78e8284Sdrh **    \                      \_______ subquery _______/        /
1901e78e8284Sdrh **     \                                                      /
1902e78e8284Sdrh **      \____________________ outer query ___________________/
1903e78e8284Sdrh **
1904e78e8284Sdrh ** This routine is called for the outer query first.   For that call,
1905e78e8284Sdrh ** pParent will be NULL.  During the processing of the outer query, this
1906e78e8284Sdrh ** routine is called recursively to handle the subquery.  For the recursive
1907e78e8284Sdrh ** call, pParent will point to the outer query.  Because the subquery is
1908e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will
1909e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.)
19109bb61fe7Sdrh */
19119bb61fe7Sdrh int sqliteSelect(
1912cce7d176Sdrh   Parse *pParse,         /* The parser context */
19139bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
1914e78e8284Sdrh   int eDest,             /* How to dispose of the results */
1915e78e8284Sdrh   int iParm,             /* A parameter used by the eDest disposal method */
1916832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
1917832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
19181b2e0329Sdrh   int *pParentAgg        /* True if pParent uses aggregate functions */
1919cce7d176Sdrh ){
1920d8bc7086Sdrh   int i;
1921cce7d176Sdrh   WhereInfo *pWInfo;
1922cce7d176Sdrh   Vdbe *v;
1923cce7d176Sdrh   int isAgg = 0;         /* True for select lists like "count(*)" */
1924a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
1925ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
19269bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
19279bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
19282282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
19292282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
193019a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
193119a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
193210e5e3cfSdrh   int base;              /* First cursor available for use */
19331d83f052Sdrh   int rc = 1;            /* Value to return from this function */
19349bb61fe7Sdrh 
1935daffd0e5Sdrh   if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
1936e5f9c644Sdrh   if( sqliteAuthCheck(pParse, SQLITE_SELECT, 0, 0) ) return 1;
1937daffd0e5Sdrh 
193882c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
193982c3d636Sdrh   */
194082c3d636Sdrh   if( p->pPrior ){
194182c3d636Sdrh     return multiSelect(pParse, p, eDest, iParm);
194282c3d636Sdrh   }
194382c3d636Sdrh 
194482c3d636Sdrh   /* Make local copies of the parameters for this query.
194582c3d636Sdrh   */
19469bb61fe7Sdrh   pTabList = p->pSrc;
19479bb61fe7Sdrh   pWhere = p->pWhere;
19489bb61fe7Sdrh   pOrderBy = p->pOrderBy;
19492282792aSdrh   pGroupBy = p->pGroupBy;
19502282792aSdrh   pHaving = p->pHaving;
195119a775c2Sdrh   isDistinct = p->isDistinct;
19529bb61fe7Sdrh 
1953832508b7Sdrh   /* Allocate a block of VDBE cursors, one for each table in the FROM clause.
1954832508b7Sdrh   ** The WHERE processing requires that the cursors for the tables in the
1955832508b7Sdrh   ** FROM clause be consecutive.
195610e5e3cfSdrh   */
1957832508b7Sdrh   base = p->base = pParse->nTab;
1958ad3cab52Sdrh   pParse->nTab += pTabList->nSrc;
195910e5e3cfSdrh 
19609bb61fe7Sdrh   /*
19619bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
19629bb61fe7Sdrh   ** errors before this routine starts.
19639bb61fe7Sdrh   */
19641d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
1965cce7d176Sdrh 
1966e78e8284Sdrh   /* Expand any "*" terms in the result set.  (For example the "*" in
1967e78e8284Sdrh   ** "SELECT * FROM t1")  The fillInColumnlist() routine also does some
1968e78e8284Sdrh   ** other housekeeping - see the header comment for details.
1969cce7d176Sdrh   */
1970d8bc7086Sdrh   if( fillInColumnList(pParse, p) ){
19711d83f052Sdrh     goto select_end;
1972cce7d176Sdrh   }
1973ad2d8307Sdrh   pWhere = p->pWhere;
1974d8bc7086Sdrh   pEList = p->pEList;
19751d83f052Sdrh   if( pEList==0 ) goto select_end;
1976cce7d176Sdrh 
19772282792aSdrh   /* If writing to memory or generating a set
19782282792aSdrh   ** only a single column may be output.
197919a775c2Sdrh   */
1980fef5208cSdrh   if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
198119a775c2Sdrh     sqliteSetString(&pParse->zErrMsg, "only a single result allowed for "
198219a775c2Sdrh        "a SELECT that is part of an expression", 0);
198319a775c2Sdrh     pParse->nErr++;
19841d83f052Sdrh     goto select_end;
198519a775c2Sdrh   }
198619a775c2Sdrh 
1987c926afbcSdrh   /* ORDER BY is ignored for some destinations.
19882282792aSdrh   */
1989c926afbcSdrh   switch( eDest ){
1990c926afbcSdrh     case SRT_Union:
1991c926afbcSdrh     case SRT_Except:
1992c926afbcSdrh     case SRT_Discard:
1993acd4c695Sdrh       pOrderBy = 0;
1994c926afbcSdrh       break;
1995c926afbcSdrh     default:
1996c926afbcSdrh       break;
19972282792aSdrh   }
19982282792aSdrh 
199910e5e3cfSdrh   /* At this point, we should have allocated all the cursors that we
2000832508b7Sdrh   ** need to handle subquerys and temporary tables.
200110e5e3cfSdrh   **
2002967e8b73Sdrh   ** Resolve the column names and do a semantics check on all the expressions.
20032282792aSdrh   */
20044794b980Sdrh   for(i=0; i<pEList->nExpr; i++){
2005832508b7Sdrh     if( sqliteExprResolveIds(pParse, base, pTabList, 0, pEList->a[i].pExpr) ){
20061d83f052Sdrh       goto select_end;
2007cce7d176Sdrh     }
20082282792aSdrh     if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
20091d83f052Sdrh       goto select_end;
2010cce7d176Sdrh     }
2011cce7d176Sdrh   }
2012cce7d176Sdrh   if( pWhere ){
2013832508b7Sdrh     if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pWhere) ){
20141d83f052Sdrh       goto select_end;
2015cce7d176Sdrh     }
2016cce7d176Sdrh     if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
20171d83f052Sdrh       goto select_end;
2018cce7d176Sdrh     }
20191f16230bSdrh     sqliteOracle8JoinFixup(base, pTabList, pWhere);
2020cce7d176Sdrh   }
2021c66c5a26Sdrh   if( pHaving ){
2022c66c5a26Sdrh     if( pGroupBy==0 ){
2023c66c5a26Sdrh       sqliteSetString(&pParse->zErrMsg, "a GROUP BY clause is required "
2024c66c5a26Sdrh          "before HAVING", 0);
2025c66c5a26Sdrh       pParse->nErr++;
2026c66c5a26Sdrh       goto select_end;
2027c66c5a26Sdrh     }
2028c66c5a26Sdrh     if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pHaving) ){
2029c66c5a26Sdrh       goto select_end;
2030c66c5a26Sdrh     }
2031c66c5a26Sdrh     if( sqliteExprCheck(pParse, pHaving, 1, &isAgg) ){
2032c66c5a26Sdrh       goto select_end;
2033c66c5a26Sdrh     }
2034c66c5a26Sdrh   }
2035cce7d176Sdrh   if( pOrderBy ){
2036cce7d176Sdrh     for(i=0; i<pOrderBy->nExpr; i++){
2037e4de1febSdrh       int iCol;
203888eee38aSdrh       Expr *pE = pOrderBy->a[i].pExpr;
203988eee38aSdrh       if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
204088eee38aSdrh         sqliteExprDelete(pE);
204188eee38aSdrh         pE = pOrderBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
204288eee38aSdrh       }
204388eee38aSdrh       if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
204488eee38aSdrh         goto select_end;
204588eee38aSdrh       }
204688eee38aSdrh       if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
204788eee38aSdrh         goto select_end;
204888eee38aSdrh       }
204988eee38aSdrh       if( sqliteExprIsConstant(pE) ){
2050e4de1febSdrh         if( sqliteExprIsInteger(pE, &iCol)==0 ){
20519208643dSdrh           sqliteSetString(&pParse->zErrMsg,
2052e4de1febSdrh                "ORDER BY terms must not be non-integer constants", 0);
20539208643dSdrh           pParse->nErr++;
20541d83f052Sdrh           goto select_end;
2055e4de1febSdrh         }else if( iCol<=0 || iCol>pEList->nExpr ){
2056e4de1febSdrh           char zBuf[2000];
2057e4de1febSdrh           sprintf(zBuf,"ORDER BY column number %d out of range - should be "
2058e4de1febSdrh              "between 1 and %d", iCol, pEList->nExpr);
2059e4de1febSdrh           sqliteSetString(&pParse->zErrMsg, zBuf, 0);
2060e4de1febSdrh           pParse->nErr++;
2061e4de1febSdrh           goto select_end;
2062e4de1febSdrh         }
2063cce7d176Sdrh       }
2064cce7d176Sdrh     }
2065cce7d176Sdrh   }
20662282792aSdrh   if( pGroupBy ){
20672282792aSdrh     for(i=0; i<pGroupBy->nExpr; i++){
206888eee38aSdrh       int iCol;
20692282792aSdrh       Expr *pE = pGroupBy->a[i].pExpr;
207088eee38aSdrh       if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
207188eee38aSdrh         sqliteExprDelete(pE);
207288eee38aSdrh         pE = pGroupBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
20739208643dSdrh       }
2074832508b7Sdrh       if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
20751d83f052Sdrh         goto select_end;
20762282792aSdrh       }
20772282792aSdrh       if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
20781d83f052Sdrh         goto select_end;
20792282792aSdrh       }
208088eee38aSdrh       if( sqliteExprIsConstant(pE) ){
208188eee38aSdrh         if( sqliteExprIsInteger(pE, &iCol)==0 ){
208288eee38aSdrh           sqliteSetString(&pParse->zErrMsg,
208388eee38aSdrh                "GROUP BY terms must not be non-integer constants", 0);
208488eee38aSdrh           pParse->nErr++;
208588eee38aSdrh           goto select_end;
208688eee38aSdrh         }else if( iCol<=0 || iCol>pEList->nExpr ){
208788eee38aSdrh           char zBuf[2000];
208888eee38aSdrh           sprintf(zBuf,"GROUP BY column number %d out of range - should be "
208988eee38aSdrh              "between 1 and %d", iCol, pEList->nExpr);
209088eee38aSdrh           sqliteSetString(&pParse->zErrMsg, zBuf, 0);
209188eee38aSdrh           pParse->nErr++;
209288eee38aSdrh           goto select_end;
209388eee38aSdrh         }
209488eee38aSdrh       }
20952282792aSdrh     }
20962282792aSdrh   }
2097cce7d176Sdrh 
20989562b551Sdrh   /* Check for the special case of a min() or max() function by itself
20999562b551Sdrh   ** in the result set.
21009562b551Sdrh   */
21019562b551Sdrh   if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
21025cf8e8c7Sdrh     rc = 0;
21039562b551Sdrh     goto select_end;
21049562b551Sdrh   }
21059562b551Sdrh 
2106d820cb1bSdrh   /* Begin generating code.
2107d820cb1bSdrh   */
2108d820cb1bSdrh   v = sqliteGetVdbe(pParse);
2109d820cb1bSdrh   if( v==0 ) goto select_end;
2110d820cb1bSdrh 
2111e78e8284Sdrh   /* Identify column names if we will be using them in a callback.  This
2112e78e8284Sdrh   ** step is skipped if the output is going to some other destination.
21130bb28106Sdrh   */
21140bb28106Sdrh   if( eDest==SRT_Callback ){
21150bb28106Sdrh     generateColumnNames(pParse, p->base, pTabList, pEList);
21160bb28106Sdrh   }
21170bb28106Sdrh 
21180bb28106Sdrh   /* Set the limiter
21190bb28106Sdrh   */
21200bb28106Sdrh   if( p->nLimit<=0 ){
2121d11d382cSdrh     p->nLimit = -1;
21220bb28106Sdrh     p->nOffset = 0;
21230bb28106Sdrh   }else{
2124d11d382cSdrh     int iMem = pParse->nMem++;
2125d11d382cSdrh     sqliteVdbeAddOp(v, OP_Integer, -p->nLimit, 0);
2126bf5cd97eSdrh     sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
2127d11d382cSdrh     p->nLimit = iMem;
2128d11d382cSdrh     if( p->nOffset<=0 ){
2129d11d382cSdrh       p->nOffset = 0;
2130d11d382cSdrh     }else{
2131d11d382cSdrh       iMem = pParse->nMem++;
2132d11d382cSdrh       sqliteVdbeAddOp(v, OP_Integer, -p->nOffset, 0);
2133bf5cd97eSdrh       sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
2134d11d382cSdrh       p->nOffset = iMem;
2135d11d382cSdrh     }
21360bb28106Sdrh   }
21370bb28106Sdrh 
2138d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
2139d820cb1bSdrh   */
2140ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
2141a76b5dfcSdrh     if( pTabList->a[i].pSelect==0 ) continue;
21422d0794e3Sdrh     sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable, base+i,
21431b2e0329Sdrh                  p, i, &isAgg);
2144832508b7Sdrh     pTabList = p->pSrc;
2145832508b7Sdrh     pWhere = p->pWhere;
2146acd4c695Sdrh     if( eDest==SRT_Callback ){
2147832508b7Sdrh       pOrderBy = p->pOrderBy;
2148acd4c695Sdrh     }
2149832508b7Sdrh     pGroupBy = p->pGroupBy;
2150832508b7Sdrh     pHaving = p->pHaving;
2151832508b7Sdrh     isDistinct = p->isDistinct;
21521b2e0329Sdrh   }
21531b2e0329Sdrh 
21541b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
21551b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
21561b2e0329Sdrh   */
21571b2e0329Sdrh   if( pParent && pParentAgg &&
21588c74a8caSdrh       flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
21591b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
21601b2e0329Sdrh     return rc;
21611b2e0329Sdrh   }
2162832508b7Sdrh 
2163e78e8284Sdrh   /* Identify column types if we will be using a callback.  This
2164e78e8284Sdrh   ** step is skipped if the output is going to a destination other
2165e78e8284Sdrh   ** than a callback.
2166fcb78a49Sdrh   */
2167fcb78a49Sdrh   if( eDest==SRT_Callback ){
2168fcb78a49Sdrh     generateColumnTypes(pParse, p->base, pTabList, pEList);
2169fcb78a49Sdrh   }
2170fcb78a49Sdrh 
21712d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
21722d0794e3Sdrh   */
21732d0794e3Sdrh   if( eDest==SRT_TempTable ){
21742d0794e3Sdrh     sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
21752d0794e3Sdrh   }
21762d0794e3Sdrh 
21772282792aSdrh   /* Do an analysis of aggregate expressions.
2178efb7251dSdrh   */
2179d820cb1bSdrh   sqliteAggregateInfoReset(pParse);
2180*bb999ef6Sdrh   if( isAgg || pGroupBy ){
21810bce8354Sdrh     assert( pParse->nAgg==0 );
2182*bb999ef6Sdrh     isAgg = 1;
21832282792aSdrh     for(i=0; i<pEList->nExpr; i++){
21842282792aSdrh       if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
21851d83f052Sdrh         goto select_end;
21862282792aSdrh       }
21872282792aSdrh     }
21882282792aSdrh     if( pGroupBy ){
21892282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
21902282792aSdrh         if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
21911d83f052Sdrh           goto select_end;
21922282792aSdrh         }
21932282792aSdrh       }
21942282792aSdrh     }
21952282792aSdrh     if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
21961d83f052Sdrh       goto select_end;
21972282792aSdrh     }
2198191b690eSdrh     if( pOrderBy ){
2199191b690eSdrh       for(i=0; i<pOrderBy->nExpr; i++){
2200191b690eSdrh         if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
22011d83f052Sdrh           goto select_end;
2202191b690eSdrh         }
2203191b690eSdrh       }
2204191b690eSdrh     }
2205efb7251dSdrh   }
2206efb7251dSdrh 
22072282792aSdrh   /* Reset the aggregator
2208cce7d176Sdrh   */
2209cce7d176Sdrh   if( isAgg ){
221099fcd718Sdrh     sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
2211e5095355Sdrh     for(i=0; i<pParse->nAgg; i++){
22120bce8354Sdrh       FuncDef *pFunc;
22130bce8354Sdrh       if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
22141350b030Sdrh         sqliteVdbeAddOp(v, OP_AggInit, 0, i);
22150bce8354Sdrh         sqliteVdbeChangeP3(v, -1, (char*)pFunc, P3_POINTER);
2216e5095355Sdrh       }
2217e5095355Sdrh     }
22181bee3d7bSdrh     if( pGroupBy==0 ){
22191bee3d7bSdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
22201bee3d7bSdrh       sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
22211bee3d7bSdrh     }
2222cce7d176Sdrh   }
2223cce7d176Sdrh 
222419a775c2Sdrh   /* Initialize the memory cell to NULL
222519a775c2Sdrh   */
2226fef5208cSdrh   if( eDest==SRT_Mem ){
222799fcd718Sdrh     sqliteVdbeAddOp(v, OP_String, 0, 0);
22288721ce4aSdrh     sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
222919a775c2Sdrh   }
223019a775c2Sdrh 
2231832508b7Sdrh   /* Open a temporary table to use for the distinct set.
2232cce7d176Sdrh   */
223319a775c2Sdrh   if( isDistinct ){
2234832508b7Sdrh     distinct = pParse->nTab++;
2235c6b52df3Sdrh     sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
2236832508b7Sdrh   }else{
2237832508b7Sdrh     distinct = -1;
2238efb7251dSdrh   }
2239832508b7Sdrh 
2240832508b7Sdrh   /* Begin the database scan
2241832508b7Sdrh   */
224268d2e591Sdrh   pWInfo = sqliteWhereBegin(pParse, p->base, pTabList, pWhere, 0,
224368d2e591Sdrh                             pGroupBy ? 0 : &pOrderBy);
22441d83f052Sdrh   if( pWInfo==0 ) goto select_end;
2245cce7d176Sdrh 
22462282792aSdrh   /* Use the standard inner loop if we are not dealing with
22472282792aSdrh   ** aggregates
2248cce7d176Sdrh   */
2249da9d6c45Sdrh   if( !isAgg ){
2250df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2251df199a25Sdrh                     iParm, pWInfo->iContinue, pWInfo->iBreak) ){
22521d83f052Sdrh        goto select_end;
2253cce7d176Sdrh     }
2254da9d6c45Sdrh   }
2255cce7d176Sdrh 
2256e3184744Sdrh   /* If we are dealing with aggregates, then do the special aggregate
22572282792aSdrh   ** processing.
2258efb7251dSdrh   */
22592282792aSdrh   else{
22602282792aSdrh     if( pGroupBy ){
22611bee3d7bSdrh       int lbl1;
22622282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
22632282792aSdrh         sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
2264efb7251dSdrh       }
226599fcd718Sdrh       sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
2266491791a8Sdrh       if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pGroupBy);
22671bee3d7bSdrh       lbl1 = sqliteVdbeMakeLabel(v);
226899fcd718Sdrh       sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
22692282792aSdrh       for(i=0; i<pParse->nAgg; i++){
22702282792aSdrh         if( pParse->aAgg[i].isAgg ) continue;
22712282792aSdrh         sqliteExprCode(pParse, pParse->aAgg[i].pExpr);
227299fcd718Sdrh         sqliteVdbeAddOp(v, OP_AggSet, 0, i);
22732282792aSdrh       }
22742282792aSdrh       sqliteVdbeResolveLabel(v, lbl1);
22752282792aSdrh     }
22762282792aSdrh     for(i=0; i<pParse->nAgg; i++){
22772282792aSdrh       Expr *pE;
22780bce8354Sdrh       int j;
22792282792aSdrh       if( !pParse->aAgg[i].isAgg ) continue;
22802282792aSdrh       pE = pParse->aAgg[i].pExpr;
22812282792aSdrh       assert( pE->op==TK_AGG_FUNCTION );
22820bce8354Sdrh       if( pE->pList ){
2283e5095355Sdrh         for(j=0; j<pE->pList->nExpr; j++){
2284e5095355Sdrh           sqliteExprCode(pParse, pE->pList->a[j].pExpr);
2285e5095355Sdrh         }
22862282792aSdrh       }
22871350b030Sdrh       sqliteVdbeAddOp(v, OP_Integer, i, 0);
2288f55f25f0Sdrh       sqliteVdbeAddOp(v, OP_AggFunc, 0, pE->pList ? pE->pList->nExpr : 0);
22890bce8354Sdrh       assert( pParse->aAgg[i].pFunc!=0 );
22900bce8354Sdrh       assert( pParse->aAgg[i].pFunc->xStep!=0 );
22910bce8354Sdrh       sqliteVdbeChangeP3(v, -1, (char*)pParse->aAgg[i].pFunc, P3_POINTER);
22922282792aSdrh     }
22932282792aSdrh   }
22942282792aSdrh 
2295cce7d176Sdrh   /* End the database scan loop.
2296cce7d176Sdrh   */
2297cce7d176Sdrh   sqliteWhereEnd(pWInfo);
2298cce7d176Sdrh 
22992282792aSdrh   /* If we are processing aggregates, we need to set up a second loop
23002282792aSdrh   ** over all of the aggregate values and process them.
23012282792aSdrh   */
23022282792aSdrh   if( isAgg ){
23032282792aSdrh     int endagg = sqliteVdbeMakeLabel(v);
23042282792aSdrh     int startagg;
230599fcd718Sdrh     startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
23062282792aSdrh     pParse->useAgg = 1;
23072282792aSdrh     if( pHaving ){
2308f5905aa7Sdrh       sqliteExprIfFalse(pParse, pHaving, startagg, 1);
23092282792aSdrh     }
2310df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2311df199a25Sdrh                     iParm, startagg, endagg) ){
23121d83f052Sdrh       goto select_end;
23132282792aSdrh     }
231499fcd718Sdrh     sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
231599fcd718Sdrh     sqliteVdbeResolveLabel(v, endagg);
231699fcd718Sdrh     sqliteVdbeAddOp(v, OP_Noop, 0, 0);
23172282792aSdrh     pParse->useAgg = 0;
23182282792aSdrh   }
23192282792aSdrh 
2320cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
2321cce7d176Sdrh   ** and send them to the callback one by one.
2322cce7d176Sdrh   */
2323cce7d176Sdrh   if( pOrderBy ){
2324c926afbcSdrh     generateSortTail(p, v, pEList->nExpr, eDest, iParm);
2325cce7d176Sdrh   }
23266a535340Sdrh 
23276a535340Sdrh 
23286a535340Sdrh   /* Issue a null callback if that is what the user wants.
23296a535340Sdrh   */
2330326dce74Sdrh   if( eDest==SRT_Callback &&
2331326dce74Sdrh     (pParse->useCallback==0 || (pParse->db->flags & SQLITE_NullCallback)!=0)
2332326dce74Sdrh   ){
23336a535340Sdrh     sqliteVdbeAddOp(v, OP_NullCallback, pEList->nExpr, 0);
23346a535340Sdrh   }
23356a535340Sdrh 
23361d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
23371d83f052Sdrh   ** to indicate no errors.
23381d83f052Sdrh   */
23391d83f052Sdrh   rc = 0;
23401d83f052Sdrh 
23411d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
23421d83f052Sdrh   ** successful coding of the SELECT.
23431d83f052Sdrh   */
23441d83f052Sdrh select_end:
23451d83f052Sdrh   sqliteAggregateInfoReset(pParse);
23461d83f052Sdrh   return rc;
2347cce7d176Sdrh }
2348