xref: /sqlite-3.40.0/src/select.c (revision ef0cae50)
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*ef0cae50Sdrh ** $Id: select.c,v 1.142 2003/07/16 02:19:38 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 */
33*ef0cae50Sdrh   int nOffset           /* OFFSET value.  0 means no offset */
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 ){
123da93d238Sdrh     sqliteErrorMsg(pParse,
124da93d238Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported");
125195e6967Sdrh     jointype = JT_INNER;
12601f3f253Sdrh   }
12701f3f253Sdrh   return jointype;
12801f3f253Sdrh }
12901f3f253Sdrh 
13001f3f253Sdrh /*
131ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
132ad2d8307Sdrh ** is not contained in the table.
133ad2d8307Sdrh */
134ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
135ad2d8307Sdrh   int i;
136ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
137ad2d8307Sdrh     if( sqliteStrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
138ad2d8307Sdrh   }
139ad2d8307Sdrh   return -1;
140ad2d8307Sdrh }
141ad2d8307Sdrh 
142ad2d8307Sdrh /*
143ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the
144ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2.
145ad2d8307Sdrh */
146ad2d8307Sdrh static void addWhereTerm(
147ad2d8307Sdrh   const char *zCol,        /* Name of the column */
148ad2d8307Sdrh   const Table *pTab1,      /* First table */
149ad2d8307Sdrh   const Table *pTab2,      /* Second table */
150ad2d8307Sdrh   Expr **ppExpr            /* Add the equality term to this expression */
151ad2d8307Sdrh ){
152ad2d8307Sdrh   Token dummy;
153ad2d8307Sdrh   Expr *pE1a, *pE1b, *pE1c;
154ad2d8307Sdrh   Expr *pE2a, *pE2b, *pE2c;
155ad2d8307Sdrh   Expr *pE;
156ad2d8307Sdrh 
157ad2d8307Sdrh   dummy.z = zCol;
158ad2d8307Sdrh   dummy.n = strlen(zCol);
1594b59ab5eSdrh   dummy.dyn = 0;
160ad2d8307Sdrh   pE1a = sqliteExpr(TK_ID, 0, 0, &dummy);
161ad2d8307Sdrh   pE2a = sqliteExpr(TK_ID, 0, 0, &dummy);
162ad2d8307Sdrh   dummy.z = pTab1->zName;
163ad2d8307Sdrh   dummy.n = strlen(dummy.z);
164ad2d8307Sdrh   pE1b = sqliteExpr(TK_ID, 0, 0, &dummy);
165ad2d8307Sdrh   dummy.z = pTab2->zName;
166ad2d8307Sdrh   dummy.n = strlen(dummy.z);
167ad2d8307Sdrh   pE2b = sqliteExpr(TK_ID, 0, 0, &dummy);
168ad2d8307Sdrh   pE1c = sqliteExpr(TK_DOT, pE1b, pE1a, 0);
169ad2d8307Sdrh   pE2c = sqliteExpr(TK_DOT, pE2b, pE2a, 0);
170ad2d8307Sdrh   pE = sqliteExpr(TK_EQ, pE1c, pE2c, 0);
1711f16230bSdrh   ExprSetProperty(pE, EP_FromJoin);
172ad2d8307Sdrh   if( *ppExpr ){
173ad2d8307Sdrh     *ppExpr = sqliteExpr(TK_AND, *ppExpr, pE, 0);
174ad2d8307Sdrh   }else{
175ad2d8307Sdrh     *ppExpr = pE;
176ad2d8307Sdrh   }
177ad2d8307Sdrh }
178ad2d8307Sdrh 
179ad2d8307Sdrh /*
1801f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
1811cc093c2Sdrh **
182e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
1831cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
1841f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
1851f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
1861f16230bSdrh ** WHERE clause during join processing but we need to remember that they
1871f16230bSdrh ** originated in the ON or USING clause.
1881cc093c2Sdrh */
1891cc093c2Sdrh static void setJoinExpr(Expr *p){
1901cc093c2Sdrh   while( p ){
1911f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
1921cc093c2Sdrh     setJoinExpr(p->pLeft);
1931cc093c2Sdrh     p = p->pRight;
1941cc093c2Sdrh   }
1951cc093c2Sdrh }
1961cc093c2Sdrh 
1971cc093c2Sdrh /*
198ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
199ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
200ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
201ad2d8307Sdrh **
202ad2d8307Sdrh ** This routine returns the number of errors encountered.
203ad2d8307Sdrh */
204ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
205ad2d8307Sdrh   SrcList *pSrc;
206ad2d8307Sdrh   int i, j;
207ad2d8307Sdrh   pSrc = p->pSrc;
208ad2d8307Sdrh   for(i=0; i<pSrc->nSrc-1; i++){
209ad2d8307Sdrh     struct SrcList_item *pTerm = &pSrc->a[i];
210ad2d8307Sdrh     struct SrcList_item *pOther = &pSrc->a[i+1];
211ad2d8307Sdrh 
212ad2d8307Sdrh     if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
213ad2d8307Sdrh 
214ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
215ad2d8307Sdrh     ** every column that the two tables have in common.
216ad2d8307Sdrh     */
217ad2d8307Sdrh     if( pTerm->jointype & JT_NATURAL ){
218ad2d8307Sdrh       Table *pTab;
219ad2d8307Sdrh       if( pTerm->pOn || pTerm->pUsing ){
220da93d238Sdrh         sqliteErrorMsg(pParse, "a NATURAL join may not have "
221ad2d8307Sdrh            "an ON or USING clause", 0);
222ad2d8307Sdrh         return 1;
223ad2d8307Sdrh       }
224ad2d8307Sdrh       pTab = pTerm->pTab;
225ad2d8307Sdrh       for(j=0; j<pTab->nCol; j++){
226ad2d8307Sdrh         if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
227ad2d8307Sdrh           addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
228ad2d8307Sdrh         }
229ad2d8307Sdrh       }
230ad2d8307Sdrh     }
231ad2d8307Sdrh 
232ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
233ad2d8307Sdrh     */
234ad2d8307Sdrh     if( pTerm->pOn && pTerm->pUsing ){
235da93d238Sdrh       sqliteErrorMsg(pParse, "cannot have both ON and USING "
236da93d238Sdrh         "clauses in the same join");
237ad2d8307Sdrh       return 1;
238ad2d8307Sdrh     }
239ad2d8307Sdrh 
240ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
241ad2d8307Sdrh     ** and AND operator.
242ad2d8307Sdrh     */
243ad2d8307Sdrh     if( pTerm->pOn ){
2441cc093c2Sdrh       setJoinExpr(pTerm->pOn);
245ad2d8307Sdrh       if( p->pWhere==0 ){
246ad2d8307Sdrh         p->pWhere = pTerm->pOn;
247ad2d8307Sdrh       }else{
248ad2d8307Sdrh         p->pWhere = sqliteExpr(TK_AND, p->pWhere, pTerm->pOn, 0);
249ad2d8307Sdrh       }
250ad2d8307Sdrh       pTerm->pOn = 0;
251ad2d8307Sdrh     }
252ad2d8307Sdrh 
253ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
254ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
255ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
256ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
257ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
258ad2d8307Sdrh     ** not contained in both tables to be joined.
259ad2d8307Sdrh     */
260ad2d8307Sdrh     if( pTerm->pUsing ){
261ad2d8307Sdrh       IdList *pList;
262ad2d8307Sdrh       int j;
263ad2d8307Sdrh       assert( i<pSrc->nSrc-1 );
264ad2d8307Sdrh       pList = pTerm->pUsing;
265ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
266bf5cd97eSdrh         if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
267bf5cd97eSdrh             columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
268da93d238Sdrh           sqliteErrorMsg(pParse, "cannot join using column %s - column "
269da93d238Sdrh             "not present in both tables", pList->a[j].zName);
270ad2d8307Sdrh           return 1;
271ad2d8307Sdrh         }
272bf5cd97eSdrh         addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
273ad2d8307Sdrh       }
274ad2d8307Sdrh     }
275ad2d8307Sdrh   }
276ad2d8307Sdrh   return 0;
277ad2d8307Sdrh }
278ad2d8307Sdrh 
279ad2d8307Sdrh /*
2801f16230bSdrh ** This routine implements a minimal Oracle8 join syntax immulation.
2811f16230bSdrh ** The precise oracle8 syntax is not implemented - it is easy enough
2821f16230bSdrh ** to get this routine confused.  But this routine does make it possible
2831f16230bSdrh ** to write a single SQL statement that does a left outer join in both
2841f16230bSdrh ** oracle8 and in SQLite.
2851f16230bSdrh **
2861f16230bSdrh ** This routine looks for TK_COLUMN expression nodes that are marked
2871f16230bSdrh ** with the EP_Oracle8Join property.  Such nodes are generated by a
2881f16230bSdrh ** column name (either "column" or "table.column") that is followed by
2891f16230bSdrh ** the special "(+)" operator.  If the table of the column marked with
2901f16230bSdrh ** the (+) operator is the second are subsequent table in a join, then
2911f16230bSdrh ** that table becomes the left table in a LEFT OUTER JOIN.  The expression
2921f16230bSdrh ** that uses that table becomes part of the ON clause for the join.
2931f16230bSdrh **
2941f16230bSdrh ** It is important to enphasize that this is not exactly how oracle8
2951f16230bSdrh ** works.  But it is close enough so that one can construct queries that
2961f16230bSdrh ** will work correctly for both SQLite and Oracle8.
2971f16230bSdrh */
2981f16230bSdrh static int sqliteOracle8JoinFixup(
2991f16230bSdrh   SrcList *pSrc,    /* List of tables being joined */
3001f16230bSdrh   Expr *pWhere      /* The WHERE clause of the SELECT statement */
3011f16230bSdrh ){
3021f16230bSdrh   int rc = 0;
3031f16230bSdrh   if( ExprHasProperty(pWhere, EP_Oracle8Join) && pWhere->op==TK_COLUMN ){
3046a3ea0e6Sdrh     int idx;
3056a3ea0e6Sdrh     for(idx=0; idx<pSrc->nSrc; idx++){
3066a3ea0e6Sdrh       if( pSrc->a[idx].iCursor==pWhere->iTable ) break;
3076a3ea0e6Sdrh     }
3081f16230bSdrh     assert( idx>=0 && idx<pSrc->nSrc );
3091f16230bSdrh     if( idx>0 ){
3101f16230bSdrh       pSrc->a[idx-1].jointype &= ~JT_INNER;
3111f16230bSdrh       pSrc->a[idx-1].jointype |= JT_OUTER|JT_LEFT;
3121f16230bSdrh       return 1;
3131f16230bSdrh     }
3141f16230bSdrh   }
3151f16230bSdrh   if( pWhere->pRight ){
3166a3ea0e6Sdrh     rc = sqliteOracle8JoinFixup(pSrc, pWhere->pRight);
3171f16230bSdrh   }
3181f16230bSdrh   if( pWhere->pLeft ){
3196a3ea0e6Sdrh     rc |= sqliteOracle8JoinFixup(pSrc, pWhere->pLeft);
3201f16230bSdrh   }
3211f16230bSdrh   if( pWhere->pList ){
3221f16230bSdrh     int i;
3231f16230bSdrh     ExprList *pList = pWhere->pList;
3241f16230bSdrh     for(i=0; i<pList->nExpr && rc==0; i++){
3256a3ea0e6Sdrh       rc |= sqliteOracle8JoinFixup(pSrc, pList->a[i].pExpr);
3261f16230bSdrh     }
3271f16230bSdrh   }
3281f16230bSdrh   if( rc==1 && (pWhere->op==TK_AND || pWhere->op==TK_EQ) ){
3291f16230bSdrh     setJoinExpr(pWhere);
3301f16230bSdrh     rc = 0;
3311f16230bSdrh   }
3321f16230bSdrh   return rc;
3331f16230bSdrh }
3341f16230bSdrh 
3351f16230bSdrh /*
3369bb61fe7Sdrh ** Delete the given Select structure and all of its substructures.
3379bb61fe7Sdrh */
3389bb61fe7Sdrh void sqliteSelectDelete(Select *p){
33982c3d636Sdrh   if( p==0 ) return;
3409bb61fe7Sdrh   sqliteExprListDelete(p->pEList);
341ad3cab52Sdrh   sqliteSrcListDelete(p->pSrc);
3429bb61fe7Sdrh   sqliteExprDelete(p->pWhere);
3439bb61fe7Sdrh   sqliteExprListDelete(p->pGroupBy);
3449bb61fe7Sdrh   sqliteExprDelete(p->pHaving);
3459bb61fe7Sdrh   sqliteExprListDelete(p->pOrderBy);
34682c3d636Sdrh   sqliteSelectDelete(p->pPrior);
347a76b5dfcSdrh   sqliteFree(p->zSelect);
3489bb61fe7Sdrh   sqliteFree(p);
3499bb61fe7Sdrh }
3509bb61fe7Sdrh 
3519bb61fe7Sdrh /*
3522282792aSdrh ** Delete the aggregate information from the parse structure.
3532282792aSdrh */
3541d83f052Sdrh static void sqliteAggregateInfoReset(Parse *pParse){
3552282792aSdrh   sqliteFree(pParse->aAgg);
3562282792aSdrh   pParse->aAgg = 0;
3572282792aSdrh   pParse->nAgg = 0;
3582282792aSdrh   pParse->useAgg = 0;
3592282792aSdrh }
3602282792aSdrh 
3612282792aSdrh /*
362c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
363c926afbcSdrh ** stack into the sorter.
364c926afbcSdrh */
365c926afbcSdrh static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
366c926afbcSdrh   char *zSortOrder;
367c926afbcSdrh   int i;
368c926afbcSdrh   zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
369c926afbcSdrh   if( zSortOrder==0 ) return;
370c926afbcSdrh   for(i=0; i<pOrderBy->nExpr; i++){
37138640e15Sdrh     int order = pOrderBy->a[i].sortOrder;
37238640e15Sdrh     int type;
37338640e15Sdrh     int c;
37438640e15Sdrh     if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
37538640e15Sdrh       type = SQLITE_SO_TEXT;
37638640e15Sdrh     }else if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_NUM ){
37738640e15Sdrh       type = SQLITE_SO_NUM;
378491791a8Sdrh     }else if( pParse->db->file_format>=4 ){
37938640e15Sdrh       type = sqliteExprType(pOrderBy->a[i].pExpr);
38038640e15Sdrh     }else{
38138640e15Sdrh       type = SQLITE_SO_NUM;
38238640e15Sdrh     }
38338640e15Sdrh     if( (order & SQLITE_SO_DIRMASK)==SQLITE_SO_ASC ){
38438640e15Sdrh       c = type==SQLITE_SO_TEXT ? 'A' : '+';
38538640e15Sdrh     }else{
38638640e15Sdrh       c = type==SQLITE_SO_TEXT ? 'D' : '-';
38738640e15Sdrh     }
38838640e15Sdrh     zSortOrder[i] = c;
389c926afbcSdrh     sqliteExprCode(pParse, pOrderBy->a[i].pExpr);
390c926afbcSdrh   }
391c926afbcSdrh   zSortOrder[pOrderBy->nExpr] = 0;
392c926afbcSdrh   sqliteVdbeAddOp(v, OP_SortMakeKey, pOrderBy->nExpr, 0);
393c926afbcSdrh   sqliteVdbeChangeP3(v, -1, zSortOrder, strlen(zSortOrder));
394c926afbcSdrh   sqliteFree(zSortOrder);
395c926afbcSdrh   sqliteVdbeAddOp(v, OP_SortPut, 0, 0);
396c926afbcSdrh }
397c926afbcSdrh 
398c926afbcSdrh /*
39938640e15Sdrh ** This routine adds a P3 argument to the last VDBE opcode that was
40038640e15Sdrh ** inserted. The P3 argument added is a string suitable for the
40138640e15Sdrh ** OP_MakeKey or OP_MakeIdxKey opcodes.  The string consists of
40238640e15Sdrh ** characters 't' or 'n' depending on whether or not the various
40338640e15Sdrh ** fields of the key to be generated should be treated as numeric
40438640e15Sdrh ** or as text.  See the OP_MakeKey and OP_MakeIdxKey opcode
40538640e15Sdrh ** documentation for additional information about the P3 string.
40638640e15Sdrh ** See also the sqliteAddIdxKeyType() routine.
40738640e15Sdrh */
40838640e15Sdrh void sqliteAddKeyType(Vdbe *v, ExprList *pEList){
40938640e15Sdrh   int nColumn = pEList->nExpr;
41038640e15Sdrh   char *zType = sqliteMalloc( nColumn+1 );
41138640e15Sdrh   int i;
41238640e15Sdrh   if( zType==0 ) return;
41338640e15Sdrh   for(i=0; i<nColumn; i++){
41438640e15Sdrh     zType[i] = sqliteExprType(pEList->a[i].pExpr)==SQLITE_SO_NUM ? 'n' : 't';
41538640e15Sdrh   }
41638640e15Sdrh   zType[i] = 0;
41738640e15Sdrh   sqliteVdbeChangeP3(v, -1, zType, nColumn);
41838640e15Sdrh   sqliteFree(zType);
41938640e15Sdrh }
42038640e15Sdrh 
42138640e15Sdrh /*
4222282792aSdrh ** This routine generates the code for the inside of the inner loop
4232282792aSdrh ** of a SELECT.
42482c3d636Sdrh **
42538640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
42638640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
42738640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
42838640e15Sdrh ** datatypes for each column.
4292282792aSdrh */
4302282792aSdrh static int selectInnerLoop(
4312282792aSdrh   Parse *pParse,          /* The parser context */
432df199a25Sdrh   Select *p,              /* The complete select statement being coded */
4332282792aSdrh   ExprList *pEList,       /* List of values being extracted */
43482c3d636Sdrh   int srcTab,             /* Pull data from this table */
435967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
4362282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
4372282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
4382282792aSdrh   int eDest,              /* How to dispose of the results */
4392282792aSdrh   int iParm,              /* An argument to the disposal method */
4402282792aSdrh   int iContinue,          /* Jump here to continue with next row */
4412282792aSdrh   int iBreak              /* Jump here to break out of the inner loop */
4422282792aSdrh ){
4432282792aSdrh   Vdbe *v = pParse->pVdbe;
4442282792aSdrh   int i;
44538640e15Sdrh 
446daffd0e5Sdrh   if( v==0 ) return 0;
44738640e15Sdrh   assert( pEList!=0 );
4482282792aSdrh 
449df199a25Sdrh   /* If there was a LIMIT clause on the SELECT statement, then do the check
450df199a25Sdrh   ** to see if this row should be output.
451df199a25Sdrh   */
452df199a25Sdrh   if( pOrderBy==0 ){
453df199a25Sdrh     if( p->nOffset>0 ){
454d11d382cSdrh       int addr = sqliteVdbeCurrentAddr(v);
455d11d382cSdrh       sqliteVdbeAddOp(v, OP_MemIncr, p->nOffset, addr+2);
456d11d382cSdrh       sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
457df199a25Sdrh     }
458d11d382cSdrh     if( p->nLimit>=0 ){
459d11d382cSdrh       sqliteVdbeAddOp(v, OP_MemIncr, p->nLimit, iBreak);
460df199a25Sdrh     }
461df199a25Sdrh   }
462df199a25Sdrh 
463967e8b73Sdrh   /* Pull the requested columns.
4642282792aSdrh   */
46538640e15Sdrh   if( nColumn>0 ){
466967e8b73Sdrh     for(i=0; i<nColumn; i++){
46799fcd718Sdrh       sqliteVdbeAddOp(v, OP_Column, srcTab, i);
46882c3d636Sdrh     }
46938640e15Sdrh   }else{
47038640e15Sdrh     nColumn = pEList->nExpr;
47138640e15Sdrh     for(i=0; i<pEList->nExpr; i++){
47238640e15Sdrh       sqliteExprCode(pParse, pEList->a[i].pExpr);
47338640e15Sdrh     }
47482c3d636Sdrh   }
4752282792aSdrh 
476daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
477daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
478daffd0e5Sdrh   ** part of the result.
4792282792aSdrh   */
480f5905aa7Sdrh   if( distinct>=0 && pEList && pEList->nExpr>0 ){
4810bd1f4eaSdrh #if NULL_ALWAYS_DISTINCT
4820bd1f4eaSdrh     sqliteVdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqliteVdbeCurrentAddr(v)+7);
4830bd1f4eaSdrh #endif
48499fcd718Sdrh     sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
485491791a8Sdrh     if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pEList);
486f5905aa7Sdrh     sqliteVdbeAddOp(v, OP_Distinct, distinct, sqliteVdbeCurrentAddr(v)+3);
48799fcd718Sdrh     sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
48899fcd718Sdrh     sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
48999fcd718Sdrh     sqliteVdbeAddOp(v, OP_String, 0, 0);
4906b12545fSdrh     sqliteVdbeAddOp(v, OP_PutStrKey, distinct, 0);
4912282792aSdrh   }
49282c3d636Sdrh 
493c926afbcSdrh   switch( eDest ){
49482c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
49582c3d636Sdrh     ** table iParm.
4962282792aSdrh     */
497c926afbcSdrh     case SRT_Union: {
4980bd1f4eaSdrh       sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
499f5905aa7Sdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
5006b12545fSdrh       sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
501c926afbcSdrh       break;
502c926afbcSdrh     }
50382c3d636Sdrh 
5045974a30fSdrh     /* Store the result as data using a unique key.
5055974a30fSdrh     */
506c926afbcSdrh     case SRT_Table:
507c926afbcSdrh     case SRT_TempTable: {
50899fcd718Sdrh       sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
509c926afbcSdrh       if( pOrderBy ){
510c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
511c926afbcSdrh       }else{
51299fcd718Sdrh         sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
51399fcd718Sdrh         sqliteVdbeAddOp(v, OP_Pull, 1, 0);
5146b12545fSdrh         sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
515c926afbcSdrh       }
516c926afbcSdrh       break;
517c926afbcSdrh     }
5185974a30fSdrh 
51982c3d636Sdrh     /* Construct a record from the query result, but instead of
52082c3d636Sdrh     ** saving that record, use it as a key to delete elements from
52182c3d636Sdrh     ** the temporary table iParm.
52282c3d636Sdrh     */
523c926afbcSdrh     case SRT_Except: {
5240bd1f4eaSdrh       int addr;
5250bd1f4eaSdrh       addr = sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
52699fcd718Sdrh       sqliteVdbeAddOp(v, OP_NotFound, iParm, addr+3);
52799fcd718Sdrh       sqliteVdbeAddOp(v, OP_Delete, iParm, 0);
528c926afbcSdrh       break;
529c926afbcSdrh     }
5302282792aSdrh 
5312282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
5322282792aSdrh     ** then there should be a single item on the stack.  Write this
5332282792aSdrh     ** item into the set table with bogus data.
5342282792aSdrh     */
535c926afbcSdrh     case SRT_Set: {
536a9f9d1c0Sdrh       int lbl = sqliteVdbeMakeLabel(v);
537967e8b73Sdrh       assert( nColumn==1 );
538a9f9d1c0Sdrh       sqliteVdbeAddOp(v, OP_IsNull, -1, lbl);
539c926afbcSdrh       if( pOrderBy ){
540c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
541c926afbcSdrh       }else{
542a9f9d1c0Sdrh         sqliteVdbeAddOp(v, OP_String, 0, 0);
5436b12545fSdrh         sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
544c926afbcSdrh       }
545a9f9d1c0Sdrh       sqliteVdbeResolveLabel(v, lbl);
546c926afbcSdrh       break;
547c926afbcSdrh     }
54882c3d636Sdrh 
5492282792aSdrh     /* If this is a scalar select that is part of an expression, then
5502282792aSdrh     ** store the results in the appropriate memory cell and break out
5512282792aSdrh     ** of the scan loop.
5522282792aSdrh     */
553c926afbcSdrh     case SRT_Mem: {
554967e8b73Sdrh       assert( nColumn==1 );
555c926afbcSdrh       if( pOrderBy ){
556c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
557c926afbcSdrh       }else{
5588721ce4aSdrh         sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
55999fcd718Sdrh         sqliteVdbeAddOp(v, OP_Goto, 0, iBreak);
560c926afbcSdrh       }
561c926afbcSdrh       break;
562c926afbcSdrh     }
5632282792aSdrh 
564f46f905aSdrh     /* Send the data to the callback function.
565f46f905aSdrh     */
566f46f905aSdrh     case SRT_Callback:
567f46f905aSdrh     case SRT_Sorter: {
568f46f905aSdrh       if( pOrderBy ){
569f46f905aSdrh         sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
570f46f905aSdrh         pushOntoSorter(pParse, v, pOrderBy);
571f46f905aSdrh       }else{
572f46f905aSdrh         assert( eDest==SRT_Callback );
573f46f905aSdrh         sqliteVdbeAddOp(v, OP_Callback, nColumn, 0);
574f46f905aSdrh       }
575f46f905aSdrh       break;
576f46f905aSdrh     }
577f46f905aSdrh 
578142e30dfSdrh     /* Invoke a subroutine to handle the results.  The subroutine itself
579142e30dfSdrh     ** is responsible for popping the results off of the stack.
580142e30dfSdrh     */
581142e30dfSdrh     case SRT_Subroutine: {
582ac82fcf5Sdrh       if( pOrderBy ){
583ac82fcf5Sdrh         sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
584ac82fcf5Sdrh         pushOntoSorter(pParse, v, pOrderBy);
585ac82fcf5Sdrh       }else{
586142e30dfSdrh         sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
587ac82fcf5Sdrh       }
588142e30dfSdrh       break;
589142e30dfSdrh     }
590142e30dfSdrh 
591d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
592d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
593d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
594d7489c39Sdrh     ** about the actual results of the select.
595d7489c39Sdrh     */
596c926afbcSdrh     default: {
597f46f905aSdrh       assert( eDest==SRT_Discard );
598f46f905aSdrh       sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
599c926afbcSdrh       break;
600c926afbcSdrh     }
601c926afbcSdrh   }
60282c3d636Sdrh   return 0;
60382c3d636Sdrh }
60482c3d636Sdrh 
60582c3d636Sdrh /*
606d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
607d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
608d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
609d8bc7086Sdrh ** routine generates the code needed to do that.
610d8bc7086Sdrh */
611c926afbcSdrh static void generateSortTail(
612c926afbcSdrh   Select *p,       /* The SELECT statement */
613c926afbcSdrh   Vdbe *v,         /* Generate code into this VDBE */
614c926afbcSdrh   int nColumn,     /* Number of columns of data */
615c926afbcSdrh   int eDest,       /* Write the sorted results here */
616c926afbcSdrh   int iParm        /* Optional parameter associated with eDest */
617c926afbcSdrh ){
618d8bc7086Sdrh   int end = sqliteVdbeMakeLabel(v);
619d8bc7086Sdrh   int addr;
620f46f905aSdrh   if( eDest==SRT_Sorter ) return;
62199fcd718Sdrh   sqliteVdbeAddOp(v, OP_Sort, 0, 0);
62299fcd718Sdrh   addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end);
623df199a25Sdrh   if( p->nOffset>0 ){
624d11d382cSdrh     sqliteVdbeAddOp(v, OP_MemIncr, p->nOffset, addr+4);
625d11d382cSdrh     sqliteVdbeAddOp(v, OP_Pop, 1, 0);
626d11d382cSdrh     sqliteVdbeAddOp(v, OP_Goto, 0, addr);
627df199a25Sdrh   }
628d11d382cSdrh   if( p->nLimit>=0 ){
629d11d382cSdrh     sqliteVdbeAddOp(v, OP_MemIncr, p->nLimit, end);
630df199a25Sdrh   }
631c926afbcSdrh   switch( eDest ){
632c926afbcSdrh     case SRT_Callback: {
633df199a25Sdrh       sqliteVdbeAddOp(v, OP_SortCallback, nColumn, 0);
634c926afbcSdrh       break;
635c926afbcSdrh     }
636c926afbcSdrh     case SRT_Table:
637c926afbcSdrh     case SRT_TempTable: {
638c926afbcSdrh       sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
639c926afbcSdrh       sqliteVdbeAddOp(v, OP_Pull, 1, 0);
640c926afbcSdrh       sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
641c926afbcSdrh       break;
642c926afbcSdrh     }
643c926afbcSdrh     case SRT_Set: {
644c926afbcSdrh       assert( nColumn==1 );
645c926afbcSdrh       sqliteVdbeAddOp(v, OP_IsNull, -1, sqliteVdbeCurrentAddr(v)+3);
646c926afbcSdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
647c926afbcSdrh       sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
648c926afbcSdrh       break;
649c926afbcSdrh     }
650c926afbcSdrh     case SRT_Mem: {
651c926afbcSdrh       assert( nColumn==1 );
652c926afbcSdrh       sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
653c926afbcSdrh       sqliteVdbeAddOp(v, OP_Goto, 0, end);
654c926afbcSdrh       break;
655c926afbcSdrh     }
656ac82fcf5Sdrh     case SRT_Subroutine: {
657ac82fcf5Sdrh       int i;
658ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
659ac82fcf5Sdrh         sqliteVdbeAddOp(v, OP_Column, -1-i, i);
660ac82fcf5Sdrh       }
661ac82fcf5Sdrh       sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
662ac82fcf5Sdrh       sqliteVdbeAddOp(v, OP_Pop, 1, 0);
663ac82fcf5Sdrh       break;
664ac82fcf5Sdrh     }
665c926afbcSdrh     default: {
666f46f905aSdrh       /* Do nothing */
667c926afbcSdrh       break;
668c926afbcSdrh     }
669c926afbcSdrh   }
67099fcd718Sdrh   sqliteVdbeAddOp(v, OP_Goto, 0, addr);
67199fcd718Sdrh   sqliteVdbeResolveLabel(v, end);
672a8b38d28Sdrh   sqliteVdbeAddOp(v, OP_SortReset, 0, 0);
673d8bc7086Sdrh }
674d8bc7086Sdrh 
675d8bc7086Sdrh /*
676fcb78a49Sdrh ** Generate code that will tell the VDBE the datatypes of
677fcb78a49Sdrh ** columns in the result set.
678e78e8284Sdrh **
679e78e8284Sdrh ** This routine only generates code if the "PRAGMA show_datatypes=on"
680e78e8284Sdrh ** has been executed.  The datatypes are reported out in the azCol
681e78e8284Sdrh ** parameter to the callback function.  The first N azCol[] entries
682e78e8284Sdrh ** are the names of the columns, and the second N entries are the
683e78e8284Sdrh ** datatypes for the columns.
684e78e8284Sdrh **
685e78e8284Sdrh ** The "datatype" for a result that is a column of a type is the
686e78e8284Sdrh ** datatype definition extracted from the CREATE TABLE statement.
687e78e8284Sdrh ** The datatype for an expression is either TEXT or NUMERIC.  The
688e78e8284Sdrh ** datatype for a ROWID field is INTEGER.
689fcb78a49Sdrh */
690fcb78a49Sdrh static void generateColumnTypes(
691fcb78a49Sdrh   Parse *pParse,      /* Parser context */
692fcb78a49Sdrh   SrcList *pTabList,  /* List of tables */
693fcb78a49Sdrh   ExprList *pEList    /* Expressions defining the result set */
694fcb78a49Sdrh ){
695fcb78a49Sdrh   Vdbe *v = pParse->pVdbe;
6966a3ea0e6Sdrh   int i, j;
697326dce74Sdrh   if( pParse->useCallback && (pParse->db->flags & SQLITE_ReportTypes)==0 ){
698326dce74Sdrh     return;
699326dce74Sdrh   }
700fcb78a49Sdrh   for(i=0; i<pEList->nExpr; i++){
701fcb78a49Sdrh     Expr *p = pEList->a[i].pExpr;
702fcb78a49Sdrh     char *zType = 0;
703fcb78a49Sdrh     if( p==0 ) continue;
704fcb78a49Sdrh     if( p->op==TK_COLUMN && pTabList ){
7056a3ea0e6Sdrh       Table *pTab;
706fcb78a49Sdrh       int iCol = p->iColumn;
7076a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
7086a3ea0e6Sdrh       assert( j<pTabList->nSrc );
7096a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
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 */
736ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
737832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
738832508b7Sdrh ){
739d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
7406a3ea0e6Sdrh   int i, j;
741daffd0e5Sdrh   if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return;
742d8bc7086Sdrh   pParse->colNamesSet = 1;
74382c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
74482c3d636Sdrh     Expr *p;
745b1363206Sdrh     char *zType = 0;
7461bee3d7bSdrh     int showFullNames;
7475a38705eSdrh     p = pEList->a[i].pExpr;
7485a38705eSdrh     if( p==0 ) continue;
74982c3d636Sdrh     if( pEList->a[i].zName ){
75082c3d636Sdrh       char *zName = pEList->a[i].zName;
75199fcd718Sdrh       sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
75299fcd718Sdrh       sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
75382c3d636Sdrh       continue;
75482c3d636Sdrh     }
7551bee3d7bSdrh     showFullNames = (pParse->db->flags & SQLITE_FullColNames)!=0;
756fa173a76Sdrh     if( p->op==TK_COLUMN && pTabList ){
7576a3ea0e6Sdrh       Table *pTab;
75897665873Sdrh       char *zCol;
7598aff1015Sdrh       int iCol = p->iColumn;
7606a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
7616a3ea0e6Sdrh       assert( j<pTabList->nSrc );
7626a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
7638aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
76497665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
765b1363206Sdrh       if( iCol<0 ){
766b1363206Sdrh         zCol = "_ROWID_";
767b1363206Sdrh         zType = "INTEGER";
768b1363206Sdrh       }else{
769b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
770b1363206Sdrh         zType = pTab->aCol[iCol].zType;
771b1363206Sdrh       }
7726977fea8Sdrh       if( p->span.z && p->span.z[0] && !showFullNames ){
773fa173a76Sdrh         int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
7746977fea8Sdrh         sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
775fa173a76Sdrh         sqliteVdbeCompressSpace(v, addr);
776fa173a76Sdrh       }else if( pTabList->nSrc>1 || showFullNames ){
77782c3d636Sdrh         char *zName = 0;
77882c3d636Sdrh         char *zTab;
77982c3d636Sdrh 
7806a3ea0e6Sdrh         zTab = pTabList->a[j].zAlias;
78101a34661Sdrh         if( showFullNames || zTab==0 ) zTab = pTab->zName;
78297665873Sdrh         sqliteSetString(&zName, zTab, ".", zCol, 0);
78399fcd718Sdrh         sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
78499fcd718Sdrh         sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
78582c3d636Sdrh         sqliteFree(zName);
78682c3d636Sdrh       }else{
78799fcd718Sdrh         sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
78822f70c32Sdrh         sqliteVdbeChangeP3(v, -1, zCol, 0);
78982c3d636Sdrh       }
7906977fea8Sdrh     }else if( p->span.z && p->span.z[0] ){
791fa173a76Sdrh       int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
7926977fea8Sdrh       sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
7931bee3d7bSdrh       sqliteVdbeCompressSpace(v, addr);
7941bee3d7bSdrh     }else{
7951bee3d7bSdrh       char zName[30];
7961bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
7971bee3d7bSdrh       sprintf(zName, "column%d", i+1);
7981bee3d7bSdrh       sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
7991bee3d7bSdrh       sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
80082c3d636Sdrh     }
80182c3d636Sdrh   }
8025080aaa7Sdrh }
80382c3d636Sdrh 
80482c3d636Sdrh /*
805d8bc7086Sdrh ** Name of the connection operator, used for error messages.
806d8bc7086Sdrh */
807d8bc7086Sdrh static const char *selectOpName(int id){
808d8bc7086Sdrh   char *z;
809d8bc7086Sdrh   switch( id ){
810d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
811d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
812d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
813d8bc7086Sdrh     default:           z = "UNION";       break;
814d8bc7086Sdrh   }
815d8bc7086Sdrh   return z;
816d8bc7086Sdrh }
817d8bc7086Sdrh 
818d8bc7086Sdrh /*
819315555caSdrh ** Forward declaration
820315555caSdrh */
821315555caSdrh static int fillInColumnList(Parse*, Select*);
822315555caSdrh 
823315555caSdrh /*
82422f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
82522f70c32Sdrh ** the result set of that SELECT.
82622f70c32Sdrh */
82722f70c32Sdrh Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
82822f70c32Sdrh   Table *pTab;
82922f70c32Sdrh   int i;
83022f70c32Sdrh   ExprList *pEList;
83122f70c32Sdrh 
83222f70c32Sdrh   if( fillInColumnList(pParse, pSelect) ){
83322f70c32Sdrh     return 0;
83422f70c32Sdrh   }
83522f70c32Sdrh   pTab = sqliteMalloc( sizeof(Table) );
83622f70c32Sdrh   if( pTab==0 ){
83722f70c32Sdrh     return 0;
83822f70c32Sdrh   }
83922f70c32Sdrh   pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
84022f70c32Sdrh   pEList = pSelect->pEList;
84122f70c32Sdrh   pTab->nCol = pEList->nExpr;
842417be79cSdrh   assert( pTab->nCol>0 );
84322f70c32Sdrh   pTab->aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
84422f70c32Sdrh   for(i=0; i<pTab->nCol; i++){
84522f70c32Sdrh     Expr *p;
84622f70c32Sdrh     if( pEList->a[i].zName ){
84722f70c32Sdrh       pTab->aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
8486977fea8Sdrh     }else if( (p=pEList->a[i].pExpr)->span.z && p->span.z[0] ){
8496977fea8Sdrh       sqliteSetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
850d820cb1bSdrh     }else if( p->op==TK_DOT && p->pRight && p->pRight->token.z &&
851d820cb1bSdrh            p->pRight->token.z[0] ){
852d820cb1bSdrh       sqliteSetNString(&pTab->aCol[i].zName,
853d820cb1bSdrh            p->pRight->token.z, p->pRight->token.n, 0);
85422f70c32Sdrh     }else{
85522f70c32Sdrh       char zBuf[30];
85622f70c32Sdrh       sprintf(zBuf, "column%d", i+1);
85722f70c32Sdrh       pTab->aCol[i].zName = sqliteStrDup(zBuf);
85822f70c32Sdrh     }
85922f70c32Sdrh   }
86022f70c32Sdrh   pTab->iPKey = -1;
86122f70c32Sdrh   return pTab;
86222f70c32Sdrh }
86322f70c32Sdrh 
86422f70c32Sdrh /*
865ad2d8307Sdrh ** For the given SELECT statement, do three things.
866d8bc7086Sdrh **
867ad3cab52Sdrh **    (1)  Fill in the pTabList->a[].pTab fields in the SrcList that
86863eb5f29Sdrh **         defines the set of tables that should be scanned.  For views,
86963eb5f29Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
87063eb5f29Sdrh **         that implements the view.  A copy is made of the view's SELECT
87163eb5f29Sdrh **         statement so that we can freely modify or delete that statement
87263eb5f29Sdrh **         without worrying about messing up the presistent representation
87363eb5f29Sdrh **         of the view.
874d8bc7086Sdrh **
875ad2d8307Sdrh **    (2)  Add terms to the WHERE clause to accomodate the NATURAL keyword
876ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
877ad2d8307Sdrh **
878ad2d8307Sdrh **    (3)  Scan the list of columns in the result set (pEList) looking
87954473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
88054473229Sdrh **         If found, expand each "*" to be every column in every table
88154473229Sdrh **         and TABLE.* to be every column in TABLE.
882d8bc7086Sdrh **
883d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
884d8bc7086Sdrh ** in pParse and return non-zero.
885d8bc7086Sdrh */
886d8bc7086Sdrh static int fillInColumnList(Parse *pParse, Select *p){
88754473229Sdrh   int i, j, k, rc;
888ad3cab52Sdrh   SrcList *pTabList;
889daffd0e5Sdrh   ExprList *pEList;
890a76b5dfcSdrh   Table *pTab;
891daffd0e5Sdrh 
892daffd0e5Sdrh   if( p==0 || p->pSrc==0 ) return 1;
893daffd0e5Sdrh   pTabList = p->pSrc;
894daffd0e5Sdrh   pEList = p->pEList;
895d8bc7086Sdrh 
896d8bc7086Sdrh   /* Look up every table in the table list.
897d8bc7086Sdrh   */
898ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
899d8bc7086Sdrh     if( pTabList->a[i].pTab ){
900d8bc7086Sdrh       /* This routine has run before!  No need to continue */
901d8bc7086Sdrh       return 0;
902d8bc7086Sdrh     }
903daffd0e5Sdrh     if( pTabList->a[i].zName==0 ){
90422f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
90522f70c32Sdrh       assert( pTabList->a[i].pSelect!=0 );
906ad2d8307Sdrh       if( pTabList->a[i].zAlias==0 ){
907ad2d8307Sdrh         char zFakeName[60];
908ad2d8307Sdrh         sprintf(zFakeName, "sqlite_subquery_%p_",
909ad2d8307Sdrh            (void*)pTabList->a[i].pSelect);
910ad2d8307Sdrh         sqliteSetString(&pTabList->a[i].zAlias, zFakeName, 0);
911ad2d8307Sdrh       }
91222f70c32Sdrh       pTabList->a[i].pTab = pTab =
91322f70c32Sdrh         sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias,
91422f70c32Sdrh                                         pTabList->a[i].pSelect);
91522f70c32Sdrh       if( pTab==0 ){
916daffd0e5Sdrh         return 1;
917daffd0e5Sdrh       }
9185cf590c1Sdrh       /* The isTransient flag indicates that the Table structure has been
9195cf590c1Sdrh       ** dynamically allocated and may be freed at any time.  In other words,
9205cf590c1Sdrh       ** pTab is not pointing to a persistent table structure that defines
9215cf590c1Sdrh       ** part of the schema. */
92222f70c32Sdrh       pTab->isTransient = 1;
92322f70c32Sdrh     }else{
924a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
925a76b5dfcSdrh       pTabList->a[i].pTab = pTab =
926a69d9168Sdrh         sqliteLocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
927a76b5dfcSdrh       if( pTab==0 ){
928d8bc7086Sdrh         return 1;
929d8bc7086Sdrh       }
930a76b5dfcSdrh       if( pTab->pSelect ){
93163eb5f29Sdrh         /* We reach here if the named table is a really a view */
932417be79cSdrh         if( sqliteViewGetColumnNames(pParse, pTab) ){
933417be79cSdrh           return 1;
934417be79cSdrh         }
93563eb5f29Sdrh         /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
93663eb5f29Sdrh         ** view within a view.  The SELECT structure has already been
93763eb5f29Sdrh         ** copied by the outer view so we can skip the copy step here
93863eb5f29Sdrh         ** in the inner view.
93963eb5f29Sdrh         */
94063eb5f29Sdrh         if( pTabList->a[i].pSelect==0 ){
941ff78bd2fSdrh           pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect);
942a76b5dfcSdrh         }
943d8bc7086Sdrh       }
94422f70c32Sdrh     }
94563eb5f29Sdrh   }
946d8bc7086Sdrh 
947ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
948ad2d8307Sdrh   */
949ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
950ad2d8307Sdrh 
9517c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
95254473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
95354473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
9547c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
9557c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
9567c917d19Sdrh   ** each one to the list of all columns in all tables.
95754473229Sdrh   **
95854473229Sdrh   ** The first loop just checks to see if there are any "*" operators
95954473229Sdrh   ** that need expanding.
960d8bc7086Sdrh   */
9617c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
96254473229Sdrh     Expr *pE = pEList->a[k].pExpr;
96354473229Sdrh     if( pE->op==TK_ALL ) break;
96454473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
96554473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
9667c917d19Sdrh   }
96754473229Sdrh   rc = 0;
9687c917d19Sdrh   if( k<pEList->nExpr ){
96954473229Sdrh     /*
97054473229Sdrh     ** If we get here it means the result set contains one or more "*"
97154473229Sdrh     ** operators that need to be expanded.  Loop through each expression
97254473229Sdrh     ** in the result set and expand them one by one.
97354473229Sdrh     */
9747c917d19Sdrh     struct ExprList_item *a = pEList->a;
9757c917d19Sdrh     ExprList *pNew = 0;
9767c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
97754473229Sdrh       Expr *pE = a[k].pExpr;
97854473229Sdrh       if( pE->op!=TK_ALL &&
97954473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
98054473229Sdrh         /* This particular expression does not need to be expanded.
98154473229Sdrh         */
9827c917d19Sdrh         pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
9837c917d19Sdrh         pNew->a[pNew->nExpr-1].zName = a[k].zName;
9847c917d19Sdrh         a[k].pExpr = 0;
9857c917d19Sdrh         a[k].zName = 0;
9867c917d19Sdrh       }else{
98754473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
98854473229Sdrh         ** expanded. */
98954473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
99054473229Sdrh         Token *pName;           /* text of name of TABLE */
99154473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
99254473229Sdrh           pName = &pE->pLeft->token;
99354473229Sdrh         }else{
99454473229Sdrh           pName = 0;
99554473229Sdrh         }
996ad3cab52Sdrh         for(i=0; i<pTabList->nSrc; i++){
997d8bc7086Sdrh           Table *pTab = pTabList->a[i].pTab;
99854473229Sdrh           char *zTabName = pTabList->a[i].zAlias;
99954473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
100054473229Sdrh             zTabName = pTab->zName;
100154473229Sdrh           }
100254473229Sdrh           if( pName && (zTabName==0 || zTabName[0]==0 ||
1003c754fa54Sdrh                  sqliteStrNICmp(pName->z, zTabName, pName->n)!=0 ||
1004c754fa54Sdrh                  zTabName[pName->n]!=0) ){
100554473229Sdrh             continue;
100654473229Sdrh           }
100754473229Sdrh           tableSeen = 1;
1008d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
100922f70c32Sdrh             Expr *pExpr, *pLeft, *pRight;
1010ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
1011ad2d8307Sdrh 
1012ad2d8307Sdrh             if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
1013ad2d8307Sdrh                 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
1014ad2d8307Sdrh               /* In a NATURAL join, omit the join columns from the
1015ad2d8307Sdrh               ** table on the right */
1016ad2d8307Sdrh               continue;
1017ad2d8307Sdrh             }
1018ad2d8307Sdrh             if( i>0 && sqliteIdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
1019ad2d8307Sdrh               /* In a join with a USING clause, omit columns in the
1020ad2d8307Sdrh               ** using clause from the table on the right. */
1021ad2d8307Sdrh               continue;
1022ad2d8307Sdrh             }
102322f70c32Sdrh             pRight = sqliteExpr(TK_ID, 0, 0, 0);
102422f70c32Sdrh             if( pRight==0 ) break;
1025ad2d8307Sdrh             pRight->token.z = zName;
1026ad2d8307Sdrh             pRight->token.n = strlen(zName);
10274b59ab5eSdrh             pRight->token.dyn = 0;
10284b59ab5eSdrh             if( zTabName && pTabList->nSrc>1 ){
102922f70c32Sdrh               pLeft = sqliteExpr(TK_ID, 0, 0, 0);
103022f70c32Sdrh               pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
103122f70c32Sdrh               if( pExpr==0 ) break;
10324b59ab5eSdrh               pLeft->token.z = zTabName;
10334b59ab5eSdrh               pLeft->token.n = strlen(zTabName);
10344b59ab5eSdrh               pLeft->token.dyn = 0;
10356977fea8Sdrh               sqliteSetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
10366977fea8Sdrh               pExpr->span.n = strlen(pExpr->span.z);
10376977fea8Sdrh               pExpr->span.dyn = 1;
10386977fea8Sdrh               pExpr->token.z = 0;
10396977fea8Sdrh               pExpr->token.n = 0;
10406977fea8Sdrh               pExpr->token.dyn = 0;
104122f70c32Sdrh             }else{
104222f70c32Sdrh               pExpr = pRight;
10436977fea8Sdrh               pExpr->span = pExpr->token;
104422f70c32Sdrh             }
10457c917d19Sdrh             pNew = sqliteExprListAppend(pNew, pExpr, 0);
1046d8bc7086Sdrh           }
1047d8bc7086Sdrh         }
104854473229Sdrh         if( !tableSeen ){
1049f5db2d3eSdrh           if( pName ){
1050da93d238Sdrh             sqliteErrorMsg(pParse, "no such table: %T", pName);
1051f5db2d3eSdrh           }else{
1052da93d238Sdrh             sqliteErrorMsg(pParse, "no tables specified");
1053f5db2d3eSdrh           }
105454473229Sdrh           rc = 1;
105554473229Sdrh         }
10567c917d19Sdrh       }
10577c917d19Sdrh     }
10587c917d19Sdrh     sqliteExprListDelete(pEList);
10597c917d19Sdrh     p->pEList = pNew;
1060d8bc7086Sdrh   }
106154473229Sdrh   return rc;
1062d8bc7086Sdrh }
1063d8bc7086Sdrh 
1064d8bc7086Sdrh /*
1065ff78bd2fSdrh ** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1066ff78bd2fSdrh ** in a select structure.  It just sets the pointers to NULL.  This
1067ff78bd2fSdrh ** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1068ff78bd2fSdrh ** pointer is not NULL, this routine is called recursively on that pointer.
1069ff78bd2fSdrh **
1070ff78bd2fSdrh ** This routine is called on the Select structure that defines a
1071ff78bd2fSdrh ** VIEW in order to undo any bindings to tables.  This is necessary
1072ff78bd2fSdrh ** because those tables might be DROPed by a subsequent SQL command.
10735cf590c1Sdrh ** If the bindings are not removed, then the Select.pSrc->a[].pTab field
10745cf590c1Sdrh ** will be left pointing to a deallocated Table structure after the
10755cf590c1Sdrh ** DROP and a coredump will occur the next time the VIEW is used.
1076ff78bd2fSdrh */
1077ff78bd2fSdrh void sqliteSelectUnbind(Select *p){
1078ff78bd2fSdrh   int i;
1079ad3cab52Sdrh   SrcList *pSrc = p->pSrc;
1080ff78bd2fSdrh   Table *pTab;
1081ff78bd2fSdrh   if( p==0 ) return;
1082ad3cab52Sdrh   for(i=0; i<pSrc->nSrc; i++){
1083ff78bd2fSdrh     if( (pTab = pSrc->a[i].pTab)!=0 ){
1084ff78bd2fSdrh       if( pTab->isTransient ){
1085ff78bd2fSdrh         sqliteDeleteTable(0, pTab);
1086ff78bd2fSdrh       }
1087ff78bd2fSdrh       pSrc->a[i].pTab = 0;
1088ff78bd2fSdrh       if( pSrc->a[i].pSelect ){
1089ff78bd2fSdrh         sqliteSelectUnbind(pSrc->a[i].pSelect);
1090ff78bd2fSdrh       }
1091ff78bd2fSdrh     }
1092ff78bd2fSdrh   }
1093ff78bd2fSdrh }
1094ff78bd2fSdrh 
1095ff78bd2fSdrh /*
1096d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with
1097d8bc7086Sdrh ** columns in a result.  For each ORDER BY expression, the opcode of
1098967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of
1099d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable
1100d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter.
1101d8bc7086Sdrh **
1102d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first.  A match
1103d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT.
1104d8bc7086Sdrh **
1105d8bc7086Sdrh ** Any entry that does not match is flagged as an error.  The number
1106d8bc7086Sdrh ** of errors is returned.
1107fcb78a49Sdrh **
1108fcb78a49Sdrh ** This routine does NOT correctly initialize the Expr.dataType  field
1109fcb78a49Sdrh ** of the ORDER BY expressions.  The multiSelectSortOrder() routine
1110fcb78a49Sdrh ** must be called to do that after the individual select statements
1111fcb78a49Sdrh ** have all been analyzed.  This routine is unable to compute Expr.dataType
1112fcb78a49Sdrh ** because it must be called before the individual select statements
1113fcb78a49Sdrh ** have been analyzed.
1114d8bc7086Sdrh */
1115d8bc7086Sdrh static int matchOrderbyToColumn(
1116d8bc7086Sdrh   Parse *pParse,          /* A place to leave error messages */
1117d8bc7086Sdrh   Select *pSelect,        /* Match to result columns of this SELECT */
1118d8bc7086Sdrh   ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
1119e4de1febSdrh   int iTable,             /* Insert this value in iTable */
1120d8bc7086Sdrh   int mustComplete        /* If TRUE all ORDER BYs must match */
1121d8bc7086Sdrh ){
1122d8bc7086Sdrh   int nErr = 0;
1123d8bc7086Sdrh   int i, j;
1124d8bc7086Sdrh   ExprList *pEList;
1125d8bc7086Sdrh 
1126daffd0e5Sdrh   if( pSelect==0 || pOrderBy==0 ) return 1;
1127d8bc7086Sdrh   if( mustComplete ){
1128d8bc7086Sdrh     for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1129d8bc7086Sdrh   }
1130d8bc7086Sdrh   if( fillInColumnList(pParse, pSelect) ){
1131d8bc7086Sdrh     return 1;
1132d8bc7086Sdrh   }
1133d8bc7086Sdrh   if( pSelect->pPrior ){
113492cd52f5Sdrh     if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
113592cd52f5Sdrh       return 1;
113692cd52f5Sdrh     }
1137d8bc7086Sdrh   }
1138d8bc7086Sdrh   pEList = pSelect->pEList;
1139d8bc7086Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
1140d8bc7086Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
1141e4de1febSdrh     int iCol = -1;
1142d8bc7086Sdrh     if( pOrderBy->a[i].done ) continue;
1143e4de1febSdrh     if( sqliteExprIsInteger(pE, &iCol) ){
1144e4de1febSdrh       if( iCol<=0 || iCol>pEList->nExpr ){
1145da93d238Sdrh         sqliteErrorMsg(pParse,
1146da93d238Sdrh           "ORDER BY position %d should be between 1 and %d",
1147e4de1febSdrh           iCol, pEList->nExpr);
1148e4de1febSdrh         nErr++;
1149e4de1febSdrh         break;
1150e4de1febSdrh       }
1151fcb78a49Sdrh       if( !mustComplete ) continue;
1152e4de1febSdrh       iCol--;
1153e4de1febSdrh     }
1154e4de1febSdrh     for(j=0; iCol<0 && j<pEList->nExpr; j++){
11554cfa7934Sdrh       if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
1156a76b5dfcSdrh         char *zName, *zLabel;
1157a76b5dfcSdrh         zName = pEList->a[j].zName;
1158a76b5dfcSdrh         assert( pE->token.z );
1159a76b5dfcSdrh         zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
1160d8bc7086Sdrh         sqliteDequote(zLabel);
1161d8bc7086Sdrh         if( sqliteStrICmp(zName, zLabel)==0 ){
1162e4de1febSdrh           iCol = j;
1163d8bc7086Sdrh         }
11646e142f54Sdrh         sqliteFree(zLabel);
1165d8bc7086Sdrh       }
1166e4de1febSdrh       if( iCol<0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
1167e4de1febSdrh         iCol = j;
1168d8bc7086Sdrh       }
1169e4de1febSdrh     }
1170e4de1febSdrh     if( iCol>=0 ){
1171967e8b73Sdrh       pE->op = TK_COLUMN;
1172e4de1febSdrh       pE->iColumn = iCol;
1173d8bc7086Sdrh       pE->iTable = iTable;
1174d8bc7086Sdrh       pOrderBy->a[i].done = 1;
1175d8bc7086Sdrh     }
1176e4de1febSdrh     if( iCol<0 && mustComplete ){
1177da93d238Sdrh       sqliteErrorMsg(pParse,
1178da93d238Sdrh         "ORDER BY term number %d does not match any result column", i+1);
1179d8bc7086Sdrh       nErr++;
1180d8bc7086Sdrh       break;
1181d8bc7086Sdrh     }
1182d8bc7086Sdrh   }
1183d8bc7086Sdrh   return nErr;
1184d8bc7086Sdrh }
1185d8bc7086Sdrh 
1186d8bc7086Sdrh /*
1187d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1188d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1189d8bc7086Sdrh */
1190d8bc7086Sdrh Vdbe *sqliteGetVdbe(Parse *pParse){
1191d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1192d8bc7086Sdrh   if( v==0 ){
11934c504391Sdrh     v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
1194d8bc7086Sdrh   }
1195d8bc7086Sdrh   return v;
1196d8bc7086Sdrh }
1197d8bc7086Sdrh 
1198fcb78a49Sdrh /*
1199fcb78a49Sdrh ** This routine sets the Expr.dataType field on all elements of
1200fcb78a49Sdrh ** the pOrderBy expression list.  The pOrderBy list will have been
1201fcb78a49Sdrh ** set up by matchOrderbyToColumn().  Hence each expression has
1202fcb78a49Sdrh ** a TK_COLUMN as its root node.  The Expr.iColumn refers to a
1203fcb78a49Sdrh ** column in the result set.   The datatype is set to SQLITE_SO_TEXT
1204fcb78a49Sdrh ** if the corresponding column in p and every SELECT to the left of
1205fcb78a49Sdrh ** p has a datatype of SQLITE_SO_TEXT.  If the cooressponding column
1206fcb78a49Sdrh ** in p or any of the left SELECTs is SQLITE_SO_NUM, then the datatype
1207fcb78a49Sdrh ** of the order-by expression is set to SQLITE_SO_NUM.
1208fcb78a49Sdrh **
1209fcb78a49Sdrh ** Examples:
1210fcb78a49Sdrh **
1211e78e8284Sdrh **     CREATE TABLE one(a INTEGER, b TEXT);
1212e78e8284Sdrh **     CREATE TABLE two(c VARCHAR(5), d FLOAT);
1213e78e8284Sdrh **
1214e78e8284Sdrh **     SELECT b, b FROM one UNION SELECT d, c FROM two ORDER BY 1, 2;
1215e78e8284Sdrh **
1216e78e8284Sdrh ** The primary sort key will use SQLITE_SO_NUM because the "d" in
1217e78e8284Sdrh ** the second SELECT is numeric.  The 1st column of the first SELECT
1218e78e8284Sdrh ** is text but that does not matter because a numeric always overrides
1219e78e8284Sdrh ** a text.
1220e78e8284Sdrh **
1221e78e8284Sdrh ** The secondary key will use the SQLITE_SO_TEXT sort order because
1222e78e8284Sdrh ** both the (second) "b" in the first SELECT and the "c" in the second
1223e78e8284Sdrh ** SELECT have a datatype of text.
1224fcb78a49Sdrh */
1225fcb78a49Sdrh static void multiSelectSortOrder(Select *p, ExprList *pOrderBy){
1226fcb78a49Sdrh   int i;
1227fcb78a49Sdrh   ExprList *pEList;
1228fcb78a49Sdrh   if( pOrderBy==0 ) return;
1229fcb78a49Sdrh   if( p==0 ){
1230fcb78a49Sdrh     for(i=0; i<pOrderBy->nExpr; i++){
1231fcb78a49Sdrh       pOrderBy->a[i].pExpr->dataType = SQLITE_SO_TEXT;
1232fcb78a49Sdrh     }
1233fcb78a49Sdrh     return;
1234fcb78a49Sdrh   }
1235fcb78a49Sdrh   multiSelectSortOrder(p->pPrior, pOrderBy);
1236fcb78a49Sdrh   pEList = p->pEList;
1237fcb78a49Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
1238fcb78a49Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
1239fcb78a49Sdrh     if( pE->dataType==SQLITE_SO_NUM ) continue;
1240fcb78a49Sdrh     assert( pE->iColumn>=0 );
1241fcb78a49Sdrh     if( pEList->nExpr>pE->iColumn ){
1242fcb78a49Sdrh       pE->dataType = sqliteExprType(pEList->a[pE->iColumn].pExpr);
1243fcb78a49Sdrh     }
1244fcb78a49Sdrh   }
1245fcb78a49Sdrh }
1246d8bc7086Sdrh 
1247d8bc7086Sdrh /*
124882c3d636Sdrh ** This routine is called to process a query that is really the union
124982c3d636Sdrh ** or intersection of two or more separate queries.
1250c926afbcSdrh **
1251e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1252e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1253e78e8284Sdrh ** in which case this routine will be called recursively.
1254e78e8284Sdrh **
1255e78e8284Sdrh ** The results of the total query are to be written into a destination
1256e78e8284Sdrh ** of type eDest with parameter iParm.
1257e78e8284Sdrh **
1258e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1259e78e8284Sdrh **
1260e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1261e78e8284Sdrh **
1262e78e8284Sdrh ** This statement is parsed up as follows:
1263e78e8284Sdrh **
1264e78e8284Sdrh **     SELECT c FROM t3
1265e78e8284Sdrh **      |
1266e78e8284Sdrh **      `----->  SELECT b FROM t2
1267e78e8284Sdrh **                |
1268e78e8284Sdrh **                `------>  SELECT c FROM t1
1269e78e8284Sdrh **
1270e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1271e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1272e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1273e78e8284Sdrh **
1274e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1275e78e8284Sdrh ** individual selects always group from left to right.
127682c3d636Sdrh */
127782c3d636Sdrh static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
127810e5e3cfSdrh   int rc;             /* Success code from a subroutine */
127910e5e3cfSdrh   Select *pPrior;     /* Another SELECT immediately to our left */
128010e5e3cfSdrh   Vdbe *v;            /* Generate code to this VDBE */
128182c3d636Sdrh 
1282d8bc7086Sdrh   /* Make sure there is no ORDER BY clause on prior SELECTs.  Only the
1283d8bc7086Sdrh   ** last SELECT in the series may have an ORDER BY.
128482c3d636Sdrh   */
1285daffd0e5Sdrh   if( p==0 || p->pPrior==0 ) return 1;
1286d8bc7086Sdrh   pPrior = p->pPrior;
1287d8bc7086Sdrh   if( pPrior->pOrderBy ){
1288da93d238Sdrh     sqliteErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1289da93d238Sdrh       selectOpName(p->op));
129082c3d636Sdrh     return 1;
129182c3d636Sdrh   }
129282c3d636Sdrh 
1293d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
1294d8bc7086Sdrh   */
1295d8bc7086Sdrh   v = sqliteGetVdbe(pParse);
1296d8bc7086Sdrh   if( v==0 ) return 1;
1297d8bc7086Sdrh 
12981cc3d75fSdrh   /* Create the destination temporary table if necessary
12991cc3d75fSdrh   */
13001cc3d75fSdrh   if( eDest==SRT_TempTable ){
13011cc3d75fSdrh     sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
13021cc3d75fSdrh     eDest = SRT_Table;
13031cc3d75fSdrh   }
13041cc3d75fSdrh 
1305f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1306d8bc7086Sdrh   */
130782c3d636Sdrh   switch( p->op ){
1308f46f905aSdrh     case TK_ALL: {
1309f46f905aSdrh       if( p->pOrderBy==0 ){
1310f46f905aSdrh         rc = sqliteSelect(pParse, pPrior, eDest, iParm, 0, 0, 0);
1311f46f905aSdrh         if( rc ) return rc;
1312f46f905aSdrh         p->pPrior = 0;
1313f46f905aSdrh         rc = sqliteSelect(pParse, p, eDest, iParm, 0, 0, 0);
1314f46f905aSdrh         p->pPrior = pPrior;
1315f46f905aSdrh         if( rc ) return rc;
1316f46f905aSdrh         break;
1317f46f905aSdrh       }
1318f46f905aSdrh       /* For UNION ALL ... ORDER BY fall through to the next case */
1319f46f905aSdrh     }
132082c3d636Sdrh     case TK_EXCEPT:
132182c3d636Sdrh     case TK_UNION: {
1322d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1323d8bc7086Sdrh       int op;          /* One of the SRT_ operations to apply to self */
1324d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
1325c926afbcSdrh       ExprList *pOrderBy;  /* The ORDER BY clause for the right SELECT */
132682c3d636Sdrh 
1327d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
1328c926afbcSdrh       if( eDest==priorOp && p->pOrderBy==0 ){
1329d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1330c926afbcSdrh         ** right.
1331d8bc7086Sdrh         */
133282c3d636Sdrh         unionTab = iParm;
133382c3d636Sdrh       }else{
1334d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1335d8bc7086Sdrh         ** intermediate results.
1336d8bc7086Sdrh         */
133782c3d636Sdrh         unionTab = pParse->nTab++;
1338d8bc7086Sdrh         if( p->pOrderBy
1339d8bc7086Sdrh         && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
1340d8bc7086Sdrh           return 1;
1341d8bc7086Sdrh         }
1342d8bc7086Sdrh         if( p->op!=TK_ALL ){
1343c6b52df3Sdrh           sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
134499fcd718Sdrh           sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
1345345fda3eSdrh         }else{
134699fcd718Sdrh           sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
134782c3d636Sdrh         }
1348d8bc7086Sdrh       }
1349d8bc7086Sdrh 
1350d8bc7086Sdrh       /* Code the SELECT statements to our left
1351d8bc7086Sdrh       */
1352832508b7Sdrh       rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
135382c3d636Sdrh       if( rc ) return rc;
1354d8bc7086Sdrh 
1355d8bc7086Sdrh       /* Code the current SELECT statement
1356d8bc7086Sdrh       */
1357d8bc7086Sdrh       switch( p->op ){
1358d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
1359d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
1360d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
1361d8bc7086Sdrh       }
136282c3d636Sdrh       p->pPrior = 0;
1363c926afbcSdrh       pOrderBy = p->pOrderBy;
1364c926afbcSdrh       p->pOrderBy = 0;
1365832508b7Sdrh       rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0);
136682c3d636Sdrh       p->pPrior = pPrior;
1367c926afbcSdrh       p->pOrderBy = pOrderBy;
136882c3d636Sdrh       if( rc ) return rc;
1369d8bc7086Sdrh 
1370d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1371d8bc7086Sdrh       ** it is that we currently need.
1372d8bc7086Sdrh       */
1373c926afbcSdrh       if( eDest!=priorOp || unionTab!=iParm ){
13746b56344dSdrh         int iCont, iBreak, iStart;
137582c3d636Sdrh         assert( p->pEList );
137641202ccaSdrh         if( eDest==SRT_Callback ){
13776a3ea0e6Sdrh           generateColumnNames(pParse, 0, p->pEList);
13786a3ea0e6Sdrh           generateColumnTypes(pParse, p->pSrc, p->pEList);
137941202ccaSdrh         }
138082c3d636Sdrh         iBreak = sqliteVdbeMakeLabel(v);
13816b56344dSdrh         iCont = sqliteVdbeMakeLabel(v);
13826b56344dSdrh         sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
13836b56344dSdrh         iStart = sqliteVdbeCurrentAddr(v);
1384fcb78a49Sdrh         multiSelectSortOrder(p, p->pOrderBy);
138538640e15Sdrh         rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
1386d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
138782c3d636Sdrh                              iCont, iBreak);
138882c3d636Sdrh         if( rc ) return 1;
13896b56344dSdrh         sqliteVdbeResolveLabel(v, iCont);
13906b56344dSdrh         sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
139199fcd718Sdrh         sqliteVdbeResolveLabel(v, iBreak);
139299fcd718Sdrh         sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
1393d8bc7086Sdrh         if( p->pOrderBy ){
1394c926afbcSdrh           generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
1395d8bc7086Sdrh         }
139682c3d636Sdrh       }
139782c3d636Sdrh       break;
139882c3d636Sdrh     }
139982c3d636Sdrh     case TK_INTERSECT: {
140082c3d636Sdrh       int tab1, tab2;
14016b56344dSdrh       int iCont, iBreak, iStart;
140282c3d636Sdrh 
1403d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
14046206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
1405d8bc7086Sdrh       ** by allocating the tables we will need.
1406d8bc7086Sdrh       */
140782c3d636Sdrh       tab1 = pParse->nTab++;
140882c3d636Sdrh       tab2 = pParse->nTab++;
1409d8bc7086Sdrh       if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
1410d8bc7086Sdrh         return 1;
1411d8bc7086Sdrh       }
1412c6b52df3Sdrh       sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
141399fcd718Sdrh       sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
1414d8bc7086Sdrh 
1415d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1416d8bc7086Sdrh       */
1417832508b7Sdrh       rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
141882c3d636Sdrh       if( rc ) return rc;
1419d8bc7086Sdrh 
1420d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1421d8bc7086Sdrh       */
1422c6b52df3Sdrh       sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
142399fcd718Sdrh       sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
142482c3d636Sdrh       p->pPrior = 0;
1425832508b7Sdrh       rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0);
142682c3d636Sdrh       p->pPrior = pPrior;
142782c3d636Sdrh       if( rc ) return rc;
1428d8bc7086Sdrh 
1429d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1430d8bc7086Sdrh       ** tables.
1431d8bc7086Sdrh       */
143282c3d636Sdrh       assert( p->pEList );
143341202ccaSdrh       if( eDest==SRT_Callback ){
14346a3ea0e6Sdrh         generateColumnNames(pParse, 0, p->pEList);
14356a3ea0e6Sdrh         generateColumnTypes(pParse, p->pSrc, p->pEList);
143641202ccaSdrh       }
143782c3d636Sdrh       iBreak = sqliteVdbeMakeLabel(v);
14386b56344dSdrh       iCont = sqliteVdbeMakeLabel(v);
14396b56344dSdrh       sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
14406b56344dSdrh       iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
144199fcd718Sdrh       sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
1442fcb78a49Sdrh       multiSelectSortOrder(p, p->pOrderBy);
144338640e15Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
1444d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
144582c3d636Sdrh                              iCont, iBreak);
144682c3d636Sdrh       if( rc ) return 1;
14476b56344dSdrh       sqliteVdbeResolveLabel(v, iCont);
14486b56344dSdrh       sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
144999fcd718Sdrh       sqliteVdbeResolveLabel(v, iBreak);
145099fcd718Sdrh       sqliteVdbeAddOp(v, OP_Close, tab2, 0);
145199fcd718Sdrh       sqliteVdbeAddOp(v, OP_Close, tab1, 0);
1452d8bc7086Sdrh       if( p->pOrderBy ){
1453c926afbcSdrh         generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
1454d8bc7086Sdrh       }
145582c3d636Sdrh       break;
145682c3d636Sdrh     }
145782c3d636Sdrh   }
145882c3d636Sdrh   assert( p->pEList && pPrior->pEList );
145982c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
1460da93d238Sdrh     sqliteErrorMsg(pParse, "SELECTs to the left and right of %s"
1461da93d238Sdrh       " do not have the same number of result columns", selectOpName(p->op));
146282c3d636Sdrh     return 1;
14632282792aSdrh   }
1464fcb78a49Sdrh 
1465fcb78a49Sdrh   /* Issue a null callback if that is what the user wants.
1466fcb78a49Sdrh   */
1467326dce74Sdrh   if( eDest==SRT_Callback &&
1468326dce74Sdrh     (pParse->useCallback==0 || (pParse->db->flags & SQLITE_NullCallback)!=0)
1469326dce74Sdrh   ){
1470fcb78a49Sdrh     sqliteVdbeAddOp(v, OP_NullCallback, p->pEList->nExpr, 0);
1471fcb78a49Sdrh   }
14722282792aSdrh   return 0;
14732282792aSdrh }
14742282792aSdrh 
14752282792aSdrh /*
1476832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
14776a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
147884e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
14796a3ea0e6Sdrh ** unchanged.)
1480832508b7Sdrh **
1481832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
1482832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
1483832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
1484832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
1485832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
1486832508b7Sdrh ** of the subquery rather the result set of the subquery.
1487832508b7Sdrh */
14886a3ea0e6Sdrh static void substExprList(ExprList*,int,ExprList*);  /* Forward Decl */
14896a3ea0e6Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
1490832508b7Sdrh   if( pExpr==0 ) return;
149184e59207Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable && pExpr->iColumn>=0 ){
1492832508b7Sdrh     Expr *pNew;
149384e59207Sdrh     assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1494832508b7Sdrh     assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1495832508b7Sdrh     pNew = pEList->a[pExpr->iColumn].pExpr;
1496832508b7Sdrh     assert( pNew!=0 );
1497832508b7Sdrh     pExpr->op = pNew->op;
1498fcb78a49Sdrh     pExpr->dataType = pNew->dataType;
1499d94a6698Sdrh     assert( pExpr->pLeft==0 );
1500832508b7Sdrh     pExpr->pLeft = sqliteExprDup(pNew->pLeft);
1501d94a6698Sdrh     assert( pExpr->pRight==0 );
1502832508b7Sdrh     pExpr->pRight = sqliteExprDup(pNew->pRight);
1503d94a6698Sdrh     assert( pExpr->pList==0 );
1504832508b7Sdrh     pExpr->pList = sqliteExprListDup(pNew->pList);
1505832508b7Sdrh     pExpr->iTable = pNew->iTable;
1506832508b7Sdrh     pExpr->iColumn = pNew->iColumn;
1507832508b7Sdrh     pExpr->iAgg = pNew->iAgg;
15084b59ab5eSdrh     sqliteTokenCopy(&pExpr->token, &pNew->token);
15096977fea8Sdrh     sqliteTokenCopy(&pExpr->span, &pNew->span);
1510832508b7Sdrh   }else{
15116a3ea0e6Sdrh     substExpr(pExpr->pLeft, iTable, pEList);
15126a3ea0e6Sdrh     substExpr(pExpr->pRight, iTable, pEList);
15136a3ea0e6Sdrh     substExprList(pExpr->pList, iTable, pEList);
1514832508b7Sdrh   }
1515832508b7Sdrh }
1516832508b7Sdrh static void
15176a3ea0e6Sdrh substExprList(ExprList *pList, int iTable, ExprList *pEList){
1518832508b7Sdrh   int i;
1519832508b7Sdrh   if( pList==0 ) return;
1520832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
15216a3ea0e6Sdrh     substExpr(pList->a[i].pExpr, iTable, pEList);
1522832508b7Sdrh   }
1523832508b7Sdrh }
1524832508b7Sdrh 
1525832508b7Sdrh /*
15261350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
15271350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
15281350b030Sdrh ** occurs.
15291350b030Sdrh **
15301350b030Sdrh ** To understand the concept of flattening, consider the following
15311350b030Sdrh ** query:
15321350b030Sdrh **
15331350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
15341350b030Sdrh **
15351350b030Sdrh ** The default way of implementing this query is to execute the
15361350b030Sdrh ** subquery first and store the results in a temporary table, then
15371350b030Sdrh ** run the outer query on that temporary table.  This requires two
15381350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
15391350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
1540832508b7Sdrh ** optimized.
15411350b030Sdrh **
1542832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
15431350b030Sdrh ** a single flat select, like this:
15441350b030Sdrh **
15451350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
15461350b030Sdrh **
15471350b030Sdrh ** The code generated for this simpification gives the same result
1548832508b7Sdrh ** but only has to scan the data once.  And because indices might
1549832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
1550832508b7Sdrh ** avoided.
15511350b030Sdrh **
1552832508b7Sdrh ** Flattening is only attempted if all of the following are true:
15531350b030Sdrh **
1554832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
15551350b030Sdrh **
1556832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
1557832508b7Sdrh **
15588af4d3acSdrh **   (3)  The subquery is not the right operand of a left outer join, or
15598af4d3acSdrh **        the subquery is not itself a join.  (Ticket #306)
1560832508b7Sdrh **
1561832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
1562832508b7Sdrh **
1563832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
1564832508b7Sdrh **        aggregates.
1565832508b7Sdrh **
1566832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
1567832508b7Sdrh **        DISTINCT.
1568832508b7Sdrh **
156908192d5fSdrh **   (7)  The subquery has a FROM clause.
157008192d5fSdrh **
1571df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
1572df199a25Sdrh **
1573df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
1574df199a25Sdrh **        aggregates.
1575df199a25Sdrh **
1576df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
1577df199a25Sdrh **        use LIMIT.
1578df199a25Sdrh **
1579174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
1580174b6195Sdrh **
15813fc673e6Sdrh **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
15823fc673e6Sdrh **        subquery has no WHERE clause.  (added by ticket #350)
15833fc673e6Sdrh **
1584832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
1585832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
1586832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1587832508b7Sdrh **
1588665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
1589832508b7Sdrh ** If flattening is attempted this routine returns 1.
1590832508b7Sdrh **
1591832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
1592832508b7Sdrh ** the subquery before this routine runs.
15931350b030Sdrh */
15948c74a8caSdrh static int flattenSubquery(
15958c74a8caSdrh   Parse *pParse,       /* The parsing context */
15968c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
15978c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
15988c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
15998c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
16008c74a8caSdrh ){
16010bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
1602ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
1603ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
16040bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
16056a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
1606832508b7Sdrh   int i;
1607832508b7Sdrh   Expr *pWhere;
16081350b030Sdrh 
1609832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
1610832508b7Sdrh   */
1611832508b7Sdrh   if( p==0 ) return 0;
1612832508b7Sdrh   pSrc = p->pSrc;
1613ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
1614832508b7Sdrh   pSub = pSrc->a[iFrom].pSelect;
1615832508b7Sdrh   assert( pSub!=0 );
1616832508b7Sdrh   if( isAgg && subqueryIsAgg ) return 0;
1617ad3cab52Sdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
1618832508b7Sdrh   pSubSrc = pSub->pSrc;
1619832508b7Sdrh   assert( pSubSrc );
1620c31c2eb8Sdrh   if( pSubSrc->nSrc==0 ) return 0;
1621df199a25Sdrh   if( (pSub->isDistinct || pSub->nLimit>=0) &&  (pSrc->nSrc>1 || isAgg) ){
1622df199a25Sdrh      return 0;
1623df199a25Sdrh   }
1624d11d382cSdrh   if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
1625174b6195Sdrh   if( p->pOrderBy && pSub->pOrderBy ) return 0;
1626832508b7Sdrh 
16278af4d3acSdrh   /* Restriction 3:  If the subquery is a join, make sure the subquery is
16288af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
16298af4d3acSdrh   ** is not allowed:
16308af4d3acSdrh   **
16318af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
16328af4d3acSdrh   **
16338af4d3acSdrh   ** If we flatten the above, we would get
16348af4d3acSdrh   **
16358af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
16368af4d3acSdrh   **
16378af4d3acSdrh   ** which is not at all the same thing.
16388af4d3acSdrh   */
16398af4d3acSdrh   if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
16408af4d3acSdrh     return 0;
16418af4d3acSdrh   }
16428af4d3acSdrh 
16433fc673e6Sdrh   /* Restriction 12:  If the subquery is the right operand of a left outer
16443fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
16453fc673e6Sdrh   ** An examples of why this is not allowed:
16463fc673e6Sdrh   **
16473fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
16483fc673e6Sdrh   **
16493fc673e6Sdrh   ** If we flatten the above, we would get
16503fc673e6Sdrh   **
16513fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
16523fc673e6Sdrh   **
16533fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
16543fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
16553fc673e6Sdrh   */
16563fc673e6Sdrh   if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
16573fc673e6Sdrh       && pSub->pWhere!=0 ){
16583fc673e6Sdrh     return 0;
16593fc673e6Sdrh   }
16603fc673e6Sdrh 
16610bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
166263eb5f29Sdrh   ** iFrom-th entry of the FROM clause in the outer query.
1663832508b7Sdrh   */
1664c31c2eb8Sdrh 
1665c31c2eb8Sdrh   /* Move all of the FROM elements of the subquery into the
1666c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
1667c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
1668c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
1669c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
1670c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
1671c31c2eb8Sdrh   ** elements we are now copying in.
1672c31c2eb8Sdrh   */
16736a3ea0e6Sdrh   iParent = pSrc->a[iFrom].iCursor;
1674c31c2eb8Sdrh   {
1675c31c2eb8Sdrh     int nSubSrc = pSubSrc->nSrc;
16768af4d3acSdrh     int jointype = pSrc->a[iFrom].jointype;
1677c31c2eb8Sdrh 
1678c31c2eb8Sdrh     if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
1679c31c2eb8Sdrh       sqliteDeleteTable(0, pSrc->a[iFrom].pTab);
1680c31c2eb8Sdrh     }
1681f26e09c8Sdrh     sqliteFree(pSrc->a[iFrom].zDatabase);
1682c31c2eb8Sdrh     sqliteFree(pSrc->a[iFrom].zName);
1683c31c2eb8Sdrh     sqliteFree(pSrc->a[iFrom].zAlias);
1684c31c2eb8Sdrh     if( nSubSrc>1 ){
1685c31c2eb8Sdrh       int extra = nSubSrc - 1;
1686c31c2eb8Sdrh       for(i=1; i<nSubSrc; i++){
1687c31c2eb8Sdrh         pSrc = sqliteSrcListAppend(pSrc, 0, 0);
1688c31c2eb8Sdrh       }
1689c31c2eb8Sdrh       p->pSrc = pSrc;
1690c31c2eb8Sdrh       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1691c31c2eb8Sdrh         pSrc->a[i] = pSrc->a[i-extra];
1692c31c2eb8Sdrh       }
1693c31c2eb8Sdrh     }
1694c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
1695c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
1696c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1697c31c2eb8Sdrh     }
16988af4d3acSdrh     pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
1699c31c2eb8Sdrh   }
1700c31c2eb8Sdrh 
1701c31c2eb8Sdrh   /* Now begin substituting subquery result set expressions for
1702c31c2eb8Sdrh   ** references to the iParent in the outer query.
1703c31c2eb8Sdrh   **
1704c31c2eb8Sdrh   ** Example:
1705c31c2eb8Sdrh   **
1706c31c2eb8Sdrh   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1707c31c2eb8Sdrh   **   \                     \_____________ subquery __________/          /
1708c31c2eb8Sdrh   **    \_____________________ outer query ______________________________/
1709c31c2eb8Sdrh   **
1710c31c2eb8Sdrh   ** We look at every expression in the outer query and every place we see
1711c31c2eb8Sdrh   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1712c31c2eb8Sdrh   */
17136a3ea0e6Sdrh   substExprList(p->pEList, iParent, pSub->pEList);
1714832508b7Sdrh   pList = p->pEList;
1715832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
17166977fea8Sdrh     Expr *pExpr;
17176977fea8Sdrh     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
17186977fea8Sdrh       pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
1719832508b7Sdrh     }
1720832508b7Sdrh   }
17211b2e0329Sdrh   if( isAgg ){
17226a3ea0e6Sdrh     substExprList(p->pGroupBy, iParent, pSub->pEList);
17236a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
17241b2e0329Sdrh   }
1725174b6195Sdrh   if( pSub->pOrderBy ){
1726174b6195Sdrh     assert( p->pOrderBy==0 );
1727174b6195Sdrh     p->pOrderBy = pSub->pOrderBy;
1728174b6195Sdrh     pSub->pOrderBy = 0;
1729174b6195Sdrh   }else if( p->pOrderBy ){
17306a3ea0e6Sdrh     substExprList(p->pOrderBy, iParent, pSub->pEList);
1731174b6195Sdrh   }
1732832508b7Sdrh   if( pSub->pWhere ){
1733832508b7Sdrh     pWhere = sqliteExprDup(pSub->pWhere);
1734832508b7Sdrh   }else{
1735832508b7Sdrh     pWhere = 0;
1736832508b7Sdrh   }
1737832508b7Sdrh   if( subqueryIsAgg ){
1738832508b7Sdrh     assert( p->pHaving==0 );
17391b2e0329Sdrh     p->pHaving = p->pWhere;
17401b2e0329Sdrh     p->pWhere = pWhere;
17416a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
17421b2e0329Sdrh     if( pSub->pHaving ){
17431b2e0329Sdrh       Expr *pHaving = sqliteExprDup(pSub->pHaving);
17441b2e0329Sdrh       if( p->pHaving ){
17451b2e0329Sdrh         p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0);
17461b2e0329Sdrh       }else{
17471b2e0329Sdrh         p->pHaving = pHaving;
17481b2e0329Sdrh       }
17491b2e0329Sdrh     }
17501b2e0329Sdrh     assert( p->pGroupBy==0 );
17511b2e0329Sdrh     p->pGroupBy = sqliteExprListDup(pSub->pGroupBy);
1752832508b7Sdrh   }else if( p->pWhere==0 ){
1753832508b7Sdrh     p->pWhere = pWhere;
1754832508b7Sdrh   }else{
17556a3ea0e6Sdrh     substExpr(p->pWhere, iParent, pSub->pEList);
1756832508b7Sdrh     if( pWhere ){
1757832508b7Sdrh       p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0);
1758832508b7Sdrh     }
1759832508b7Sdrh   }
1760c31c2eb8Sdrh 
1761c31c2eb8Sdrh   /* The flattened query is distinct if either the inner or the
1762c31c2eb8Sdrh   ** outer query is distinct.
1763c31c2eb8Sdrh   */
1764832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
17658c74a8caSdrh 
1766c31c2eb8Sdrh   /* Transfer the limit expression from the subquery to the outer
1767c31c2eb8Sdrh   ** query.
1768c31c2eb8Sdrh   */
1769df199a25Sdrh   if( pSub->nLimit>=0 ){
1770df199a25Sdrh     if( p->nLimit<0 ){
1771df199a25Sdrh       p->nLimit = pSub->nLimit;
1772df199a25Sdrh     }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1773df199a25Sdrh       p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1774df199a25Sdrh     }
1775df199a25Sdrh   }
1776df199a25Sdrh   p->nOffset += pSub->nOffset;
17778c74a8caSdrh 
1778c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
1779c31c2eb8Sdrh   ** success.
1780c31c2eb8Sdrh   */
1781832508b7Sdrh   sqliteSelectDelete(pSub);
1782832508b7Sdrh   return 1;
17831350b030Sdrh }
17841350b030Sdrh 
17851350b030Sdrh /*
17869562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it
17879562b551Sdrh ** is a simple min() or max() query.  If it is and this query can be
17889562b551Sdrh ** satisfied using a single seek to the beginning or end of an index,
1789e78e8284Sdrh ** then generate the code for this SELECT and return 1.  If this is not a
17909562b551Sdrh ** simple min() or max() query, then return 0;
17919562b551Sdrh **
17929562b551Sdrh ** A simply min() or max() query looks like this:
17939562b551Sdrh **
17949562b551Sdrh **    SELECT min(a) FROM table;
17959562b551Sdrh **    SELECT max(a) FROM table;
17969562b551Sdrh **
17979562b551Sdrh ** The query may have only a single table in its FROM argument.  There
17989562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
17999562b551Sdrh ** be the min() or max() of a single column of the table.  The column
18009562b551Sdrh ** in the min() or max() function must be indexed.
18019562b551Sdrh **
18029562b551Sdrh ** The parameters to this routine are the same as for sqliteSelect().
18039562b551Sdrh ** See the header comment on that routine for additional information.
18049562b551Sdrh */
18059562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
18069562b551Sdrh   Expr *pExpr;
18079562b551Sdrh   int iCol;
18089562b551Sdrh   Table *pTab;
18099562b551Sdrh   Index *pIdx;
18109562b551Sdrh   int base;
18119562b551Sdrh   Vdbe *v;
18129562b551Sdrh   int seekOp;
18139562b551Sdrh   int cont;
18149562b551Sdrh   ExprList eList;
18159562b551Sdrh   struct ExprList_item eListItem;
18169562b551Sdrh 
18179562b551Sdrh   /* Check to see if this query is a simple min() or max() query.  Return
18189562b551Sdrh   ** zero if it is  not.
18199562b551Sdrh   */
18209562b551Sdrh   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
1821ad3cab52Sdrh   if( p->pSrc->nSrc!=1 ) return 0;
18229562b551Sdrh   if( p->pEList->nExpr!=1 ) return 0;
18239562b551Sdrh   pExpr = p->pEList->a[0].pExpr;
18249562b551Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
18259562b551Sdrh   if( pExpr->pList==0 || pExpr->pList->nExpr!=1 ) return 0;
18266977fea8Sdrh   if( pExpr->token.n!=3 ) return 0;
18270bce8354Sdrh   if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){
18280bce8354Sdrh     seekOp = OP_Rewind;
18290bce8354Sdrh   }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){
18300bce8354Sdrh     seekOp = OP_Last;
18310bce8354Sdrh   }else{
18320bce8354Sdrh     return 0;
18330bce8354Sdrh   }
18349562b551Sdrh   pExpr = pExpr->pList->a[0].pExpr;
18359562b551Sdrh   if( pExpr->op!=TK_COLUMN ) return 0;
18369562b551Sdrh   iCol = pExpr->iColumn;
18379562b551Sdrh   pTab = p->pSrc->a[0].pTab;
18389562b551Sdrh 
18399562b551Sdrh   /* If we get to here, it means the query is of the correct form.
184017f71934Sdrh   ** Check to make sure we have an index and make pIdx point to the
184117f71934Sdrh   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
184217f71934Sdrh   ** key column, no index is necessary so set pIdx to NULL.  If no
184317f71934Sdrh   ** usable index is found, return 0.
18449562b551Sdrh   */
18459562b551Sdrh   if( iCol<0 ){
18469562b551Sdrh     pIdx = 0;
18479562b551Sdrh   }else{
18489562b551Sdrh     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
18499562b551Sdrh       assert( pIdx->nColumn>=1 );
18509562b551Sdrh       if( pIdx->aiColumn[0]==iCol ) break;
18519562b551Sdrh     }
18529562b551Sdrh     if( pIdx==0 ) return 0;
18539562b551Sdrh   }
18549562b551Sdrh 
185517f71934Sdrh   /* Identify column names if we will be using the callback.  This
18569562b551Sdrh   ** step is skipped if the output is going to a table or a memory cell.
18579562b551Sdrh   */
18589562b551Sdrh   v = sqliteGetVdbe(pParse);
18599562b551Sdrh   if( v==0 ) return 0;
18609562b551Sdrh   if( eDest==SRT_Callback ){
18616a3ea0e6Sdrh     generateColumnNames(pParse, p->pSrc, p->pEList);
18626a3ea0e6Sdrh     generateColumnTypes(pParse, p->pSrc, p->pEList);
18639562b551Sdrh   }
18649562b551Sdrh 
186517f71934Sdrh   /* Generating code to find the min or the max.  Basically all we have
186617f71934Sdrh   ** to do is find the first or the last entry in the chosen index.  If
186717f71934Sdrh   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
186817f71934Sdrh   ** or last entry in the main table.
18699562b551Sdrh   */
18708bf8dc92Sdrh   sqliteCodeVerifySchema(pParse, pTab->iDb);
18716a3ea0e6Sdrh   base = p->pSrc->a[0].iCursor;
1872d24cc427Sdrh   sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
1873001bbcbbSdrh   sqliteVdbeAddOp(v, OP_OpenRead, base, pTab->tnum);
18745cf8e8c7Sdrh   sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
1875d4d595f9Sdrh   cont = sqliteVdbeMakeLabel(v);
18769562b551Sdrh   if( pIdx==0 ){
18779562b551Sdrh     sqliteVdbeAddOp(v, seekOp, base, 0);
18789562b551Sdrh   }else{
1879d24cc427Sdrh     sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
1880001bbcbbSdrh     sqliteVdbeAddOp(v, OP_OpenRead, base+1, pIdx->tnum);
18815cf8e8c7Sdrh     sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
18829562b551Sdrh     sqliteVdbeAddOp(v, seekOp, base+1, 0);
18839562b551Sdrh     sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
18849562b551Sdrh     sqliteVdbeAddOp(v, OP_Close, base+1, 0);
18859562b551Sdrh     sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
18869562b551Sdrh   }
18875cf8e8c7Sdrh   eList.nExpr = 1;
18885cf8e8c7Sdrh   memset(&eListItem, 0, sizeof(eListItem));
18895cf8e8c7Sdrh   eList.a = &eListItem;
18905cf8e8c7Sdrh   eList.a[0].pExpr = pExpr;
189138640e15Sdrh   selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont);
18929562b551Sdrh   sqliteVdbeResolveLabel(v, cont);
18939562b551Sdrh   sqliteVdbeAddOp(v, OP_Close, base, 0);
18949562b551Sdrh   return 1;
18959562b551Sdrh }
18969562b551Sdrh 
18979562b551Sdrh /*
18989bb61fe7Sdrh ** Generate code for the given SELECT statement.
18999bb61fe7Sdrh **
1900fef5208cSdrh ** The results are distributed in various ways depending on the
1901fef5208cSdrh ** value of eDest and iParm.
1902fef5208cSdrh **
1903fef5208cSdrh **     eDest Value       Result
1904fef5208cSdrh **     ------------    -------------------------------------------
1905fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
1906fef5208cSdrh **
1907fef5208cSdrh **     SRT_Mem         Store first result in memory cell iParm
1908fef5208cSdrh **
1909fef5208cSdrh **     SRT_Set         Store results as keys of a table with cursor iParm
1910fef5208cSdrh **
191182c3d636Sdrh **     SRT_Union       Store results as a key in a temporary table iParm
191282c3d636Sdrh **
1913c4a3c779Sdrh **     SRT_Except      Remove results form the temporary table iParm.
1914c4a3c779Sdrh **
1915c4a3c779Sdrh **     SRT_Table       Store results in temporary table iParm
19169bb61fe7Sdrh **
1917e78e8284Sdrh ** The table above is incomplete.  Additional eDist value have be added
1918e78e8284Sdrh ** since this comment was written.  See the selectInnerLoop() function for
1919e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings.
1920e78e8284Sdrh **
19219bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
19229bb61fe7Sdrh ** encountered, then an appropriate error message is left in
19239bb61fe7Sdrh ** pParse->zErrMsg.
19249bb61fe7Sdrh **
19259bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
19269bb61fe7Sdrh ** calling function needs to do that.
19271b2e0329Sdrh **
19281b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
19291b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
19301b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
19311b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
19321b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
19331b2e0329Sdrh ** can be changed.
1934e78e8284Sdrh **
1935e78e8284Sdrh ** Example 1:   The meaning of the pParent parameter.
1936e78e8284Sdrh **
1937e78e8284Sdrh **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
1938e78e8284Sdrh **    \                      \_______ subquery _______/        /
1939e78e8284Sdrh **     \                                                      /
1940e78e8284Sdrh **      \____________________ outer query ___________________/
1941e78e8284Sdrh **
1942e78e8284Sdrh ** This routine is called for the outer query first.   For that call,
1943e78e8284Sdrh ** pParent will be NULL.  During the processing of the outer query, this
1944e78e8284Sdrh ** routine is called recursively to handle the subquery.  For the recursive
1945e78e8284Sdrh ** call, pParent will point to the outer query.  Because the subquery is
1946e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will
1947e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.)
19489bb61fe7Sdrh */
19499bb61fe7Sdrh int sqliteSelect(
1950cce7d176Sdrh   Parse *pParse,         /* The parser context */
19519bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
1952e78e8284Sdrh   int eDest,             /* How to dispose of the results */
1953e78e8284Sdrh   int iParm,             /* A parameter used by the eDest disposal method */
1954832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
1955832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
19561b2e0329Sdrh   int *pParentAgg        /* True if pParent uses aggregate functions */
1957cce7d176Sdrh ){
1958d8bc7086Sdrh   int i;
1959cce7d176Sdrh   WhereInfo *pWInfo;
1960cce7d176Sdrh   Vdbe *v;
1961cce7d176Sdrh   int isAgg = 0;         /* True for select lists like "count(*)" */
1962a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
1963ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
19649bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
19659bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
19662282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
19672282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
196819a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
196919a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
19701d83f052Sdrh   int rc = 1;            /* Value to return from this function */
19719bb61fe7Sdrh 
1972daffd0e5Sdrh   if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
1973e22a334bSdrh   if( sqliteAuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
1974daffd0e5Sdrh 
197582c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
197682c3d636Sdrh   */
197782c3d636Sdrh   if( p->pPrior ){
197882c3d636Sdrh     return multiSelect(pParse, p, eDest, iParm);
197982c3d636Sdrh   }
198082c3d636Sdrh 
198182c3d636Sdrh   /* Make local copies of the parameters for this query.
198282c3d636Sdrh   */
19839bb61fe7Sdrh   pTabList = p->pSrc;
19849bb61fe7Sdrh   pWhere = p->pWhere;
19859bb61fe7Sdrh   pOrderBy = p->pOrderBy;
19862282792aSdrh   pGroupBy = p->pGroupBy;
19872282792aSdrh   pHaving = p->pHaving;
198819a775c2Sdrh   isDistinct = p->isDistinct;
19899bb61fe7Sdrh 
19906a3ea0e6Sdrh   /* Allocate VDBE cursors for each table in the FROM clause
199110e5e3cfSdrh   */
19926a3ea0e6Sdrh   sqliteSrcListAssignCursors(pParse, pTabList);
199310e5e3cfSdrh 
19949bb61fe7Sdrh   /*
19959bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
19969bb61fe7Sdrh   ** errors before this routine starts.
19979bb61fe7Sdrh   */
19981d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
1999cce7d176Sdrh 
2000e78e8284Sdrh   /* Expand any "*" terms in the result set.  (For example the "*" in
2001e78e8284Sdrh   ** "SELECT * FROM t1")  The fillInColumnlist() routine also does some
2002e78e8284Sdrh   ** other housekeeping - see the header comment for details.
2003cce7d176Sdrh   */
2004d8bc7086Sdrh   if( fillInColumnList(pParse, p) ){
20051d83f052Sdrh     goto select_end;
2006cce7d176Sdrh   }
2007ad2d8307Sdrh   pWhere = p->pWhere;
2008d8bc7086Sdrh   pEList = p->pEList;
20091d83f052Sdrh   if( pEList==0 ) goto select_end;
2010cce7d176Sdrh 
20112282792aSdrh   /* If writing to memory or generating a set
20122282792aSdrh   ** only a single column may be output.
201319a775c2Sdrh   */
2014fef5208cSdrh   if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
2015da93d238Sdrh     sqliteErrorMsg(pParse, "only a single result allowed for "
2016da93d238Sdrh        "a SELECT that is part of an expression");
20171d83f052Sdrh     goto select_end;
201819a775c2Sdrh   }
201919a775c2Sdrh 
2020c926afbcSdrh   /* ORDER BY is ignored for some destinations.
20212282792aSdrh   */
2022c926afbcSdrh   switch( eDest ){
2023c926afbcSdrh     case SRT_Union:
2024c926afbcSdrh     case SRT_Except:
2025c926afbcSdrh     case SRT_Discard:
2026acd4c695Sdrh       pOrderBy = 0;
2027c926afbcSdrh       break;
2028c926afbcSdrh     default:
2029c926afbcSdrh       break;
20302282792aSdrh   }
20312282792aSdrh 
203210e5e3cfSdrh   /* At this point, we should have allocated all the cursors that we
2033832508b7Sdrh   ** need to handle subquerys and temporary tables.
203410e5e3cfSdrh   **
2035967e8b73Sdrh   ** Resolve the column names and do a semantics check on all the expressions.
20362282792aSdrh   */
20374794b980Sdrh   for(i=0; i<pEList->nExpr; i++){
20386a3ea0e6Sdrh     if( sqliteExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
20391d83f052Sdrh       goto select_end;
2040cce7d176Sdrh     }
20412282792aSdrh     if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
20421d83f052Sdrh       goto select_end;
2043cce7d176Sdrh     }
2044cce7d176Sdrh   }
2045cce7d176Sdrh   if( pWhere ){
20466a3ea0e6Sdrh     if( sqliteExprResolveIds(pParse, pTabList, pEList, pWhere) ){
20471d83f052Sdrh       goto select_end;
2048cce7d176Sdrh     }
2049cce7d176Sdrh     if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
20501d83f052Sdrh       goto select_end;
2051cce7d176Sdrh     }
20526a3ea0e6Sdrh     sqliteOracle8JoinFixup(pTabList, pWhere);
2053cce7d176Sdrh   }
2054c66c5a26Sdrh   if( pHaving ){
2055c66c5a26Sdrh     if( pGroupBy==0 ){
2056da93d238Sdrh       sqliteErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2057c66c5a26Sdrh       goto select_end;
2058c66c5a26Sdrh     }
20596a3ea0e6Sdrh     if( sqliteExprResolveIds(pParse, pTabList, pEList, pHaving) ){
2060c66c5a26Sdrh       goto select_end;
2061c66c5a26Sdrh     }
2062c66c5a26Sdrh     if( sqliteExprCheck(pParse, pHaving, 1, &isAgg) ){
2063c66c5a26Sdrh       goto select_end;
2064c66c5a26Sdrh     }
2065c66c5a26Sdrh   }
2066cce7d176Sdrh   if( pOrderBy ){
2067cce7d176Sdrh     for(i=0; i<pOrderBy->nExpr; i++){
2068e4de1febSdrh       int iCol;
206988eee38aSdrh       Expr *pE = pOrderBy->a[i].pExpr;
207088eee38aSdrh       if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
207188eee38aSdrh         sqliteExprDelete(pE);
207288eee38aSdrh         pE = pOrderBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
207388eee38aSdrh       }
20746a3ea0e6Sdrh       if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){
207588eee38aSdrh         goto select_end;
207688eee38aSdrh       }
207788eee38aSdrh       if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
207888eee38aSdrh         goto select_end;
207988eee38aSdrh       }
208088eee38aSdrh       if( sqliteExprIsConstant(pE) ){
2081e4de1febSdrh         if( sqliteExprIsInteger(pE, &iCol)==0 ){
2082da93d238Sdrh           sqliteErrorMsg(pParse,
2083da93d238Sdrh              "ORDER BY terms must not be non-integer constants");
20841d83f052Sdrh           goto select_end;
2085e4de1febSdrh         }else if( iCol<=0 || iCol>pEList->nExpr ){
2086da93d238Sdrh           sqliteErrorMsg(pParse,
2087da93d238Sdrh              "ORDER BY column number %d out of range - should be "
2088e4de1febSdrh              "between 1 and %d", iCol, pEList->nExpr);
2089e4de1febSdrh           goto select_end;
2090e4de1febSdrh         }
2091cce7d176Sdrh       }
2092cce7d176Sdrh     }
2093cce7d176Sdrh   }
20942282792aSdrh   if( pGroupBy ){
20952282792aSdrh     for(i=0; i<pGroupBy->nExpr; i++){
209688eee38aSdrh       int iCol;
20972282792aSdrh       Expr *pE = pGroupBy->a[i].pExpr;
209888eee38aSdrh       if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
209988eee38aSdrh         sqliteExprDelete(pE);
210088eee38aSdrh         pE = pGroupBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
21019208643dSdrh       }
21026a3ea0e6Sdrh       if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){
21031d83f052Sdrh         goto select_end;
21042282792aSdrh       }
21052282792aSdrh       if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
21061d83f052Sdrh         goto select_end;
21072282792aSdrh       }
210888eee38aSdrh       if( sqliteExprIsConstant(pE) ){
210988eee38aSdrh         if( sqliteExprIsInteger(pE, &iCol)==0 ){
2110da93d238Sdrh           sqliteErrorMsg(pParse,
2111da93d238Sdrh             "GROUP BY terms must not be non-integer constants");
211288eee38aSdrh           goto select_end;
211388eee38aSdrh         }else if( iCol<=0 || iCol>pEList->nExpr ){
2114da93d238Sdrh           sqliteErrorMsg(pParse,
2115da93d238Sdrh              "GROUP BY column number %d out of range - should be "
211688eee38aSdrh              "between 1 and %d", iCol, pEList->nExpr);
211788eee38aSdrh           goto select_end;
211888eee38aSdrh         }
211988eee38aSdrh       }
21202282792aSdrh     }
21212282792aSdrh   }
2122cce7d176Sdrh 
21239562b551Sdrh   /* Check for the special case of a min() or max() function by itself
21249562b551Sdrh   ** in the result set.
21259562b551Sdrh   */
21269562b551Sdrh   if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
21275cf8e8c7Sdrh     rc = 0;
21289562b551Sdrh     goto select_end;
21299562b551Sdrh   }
21309562b551Sdrh 
2131d820cb1bSdrh   /* Begin generating code.
2132d820cb1bSdrh   */
2133d820cb1bSdrh   v = sqliteGetVdbe(pParse);
2134d820cb1bSdrh   if( v==0 ) goto select_end;
2135d820cb1bSdrh 
2136e78e8284Sdrh   /* Identify column names if we will be using them in a callback.  This
2137e78e8284Sdrh   ** step is skipped if the output is going to some other destination.
21380bb28106Sdrh   */
21390bb28106Sdrh   if( eDest==SRT_Callback ){
21406a3ea0e6Sdrh     generateColumnNames(pParse, pTabList, pEList);
21410bb28106Sdrh   }
21420bb28106Sdrh 
2143*ef0cae50Sdrh   /* Set the limiter.
2144*ef0cae50Sdrh   **
2145*ef0cae50Sdrh   ** The phrase "LIMIT 0" means all rows are shown, not zero rows.
2146*ef0cae50Sdrh   ** If the comparison is p->nLimit<=0 then "LIMIT 0" shows
2147*ef0cae50Sdrh   ** all rows.  It is the same as no limit. If the comparision is
2148*ef0cae50Sdrh   ** p->nLimit<0 then "LIMIT 0" show no rows at all.
2149*ef0cae50Sdrh   ** "LIMIT -1" always shows all rows.  There is some
2150*ef0cae50Sdrh   ** contraversy about what the correct behavior should be.
21510bb28106Sdrh   */
21520bb28106Sdrh   if( p->nLimit<=0 ){
2153d11d382cSdrh     p->nLimit = -1;
21540bb28106Sdrh   }else{
2155d11d382cSdrh     int iMem = pParse->nMem++;
2156d11d382cSdrh     sqliteVdbeAddOp(v, OP_Integer, -p->nLimit, 0);
2157bf5cd97eSdrh     sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
2158d11d382cSdrh     p->nLimit = iMem;
2159*ef0cae50Sdrh   }
2160d11d382cSdrh   if( p->nOffset<=0 ){
2161d11d382cSdrh     p->nOffset = 0;
2162d11d382cSdrh   }else{
2163*ef0cae50Sdrh     int iMem = pParse->nMem++;
2164*ef0cae50Sdrh     if( iMem==0 ) iMem = pParse->nMem++;
2165d11d382cSdrh     sqliteVdbeAddOp(v, OP_Integer, -p->nOffset, 0);
2166bf5cd97eSdrh     sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
2167d11d382cSdrh     p->nOffset = iMem;
2168d11d382cSdrh   }
21690bb28106Sdrh 
2170d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
2171d820cb1bSdrh   */
2172ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
21735cf590c1Sdrh     const char *zSavedAuthContext;
2174c31c2eb8Sdrh     int needRestoreContext;
2175c31c2eb8Sdrh 
2176a76b5dfcSdrh     if( pTabList->a[i].pSelect==0 ) continue;
21775cf590c1Sdrh     if( pTabList->a[i].zName!=0 ){
21785cf590c1Sdrh       zSavedAuthContext = pParse->zAuthContext;
21795cf590c1Sdrh       pParse->zAuthContext = pTabList->a[i].zName;
2180c31c2eb8Sdrh       needRestoreContext = 1;
2181c31c2eb8Sdrh     }else{
2182c31c2eb8Sdrh       needRestoreContext = 0;
21835cf590c1Sdrh     }
21846a3ea0e6Sdrh     sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable,
21856a3ea0e6Sdrh                  pTabList->a[i].iCursor, p, i, &isAgg);
2186c31c2eb8Sdrh     if( needRestoreContext ){
21875cf590c1Sdrh       pParse->zAuthContext = zSavedAuthContext;
21885cf590c1Sdrh     }
2189832508b7Sdrh     pTabList = p->pSrc;
2190832508b7Sdrh     pWhere = p->pWhere;
2191c31c2eb8Sdrh     if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
2192832508b7Sdrh       pOrderBy = p->pOrderBy;
2193acd4c695Sdrh     }
2194832508b7Sdrh     pGroupBy = p->pGroupBy;
2195832508b7Sdrh     pHaving = p->pHaving;
2196832508b7Sdrh     isDistinct = p->isDistinct;
21971b2e0329Sdrh   }
21981b2e0329Sdrh 
21991b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
22001b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
22011b2e0329Sdrh   */
22021b2e0329Sdrh   if( pParent && pParentAgg &&
22038c74a8caSdrh       flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
22041b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
22051b2e0329Sdrh     return rc;
22061b2e0329Sdrh   }
2207832508b7Sdrh 
2208e78e8284Sdrh   /* Identify column types if we will be using a callback.  This
2209e78e8284Sdrh   ** step is skipped if the output is going to a destination other
2210e78e8284Sdrh   ** than a callback.
2211fcb78a49Sdrh   */
2212fcb78a49Sdrh   if( eDest==SRT_Callback ){
22136a3ea0e6Sdrh     generateColumnTypes(pParse, pTabList, pEList);
2214fcb78a49Sdrh   }
2215fcb78a49Sdrh 
22162d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
22172d0794e3Sdrh   */
22182d0794e3Sdrh   if( eDest==SRT_TempTable ){
22192d0794e3Sdrh     sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
22202d0794e3Sdrh   }
22212d0794e3Sdrh 
22222282792aSdrh   /* Do an analysis of aggregate expressions.
2223efb7251dSdrh   */
2224d820cb1bSdrh   sqliteAggregateInfoReset(pParse);
2225bb999ef6Sdrh   if( isAgg || pGroupBy ){
22260bce8354Sdrh     assert( pParse->nAgg==0 );
2227bb999ef6Sdrh     isAgg = 1;
22282282792aSdrh     for(i=0; i<pEList->nExpr; i++){
22292282792aSdrh       if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
22301d83f052Sdrh         goto select_end;
22312282792aSdrh       }
22322282792aSdrh     }
22332282792aSdrh     if( pGroupBy ){
22342282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
22352282792aSdrh         if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
22361d83f052Sdrh           goto select_end;
22372282792aSdrh         }
22382282792aSdrh       }
22392282792aSdrh     }
22402282792aSdrh     if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
22411d83f052Sdrh       goto select_end;
22422282792aSdrh     }
2243191b690eSdrh     if( pOrderBy ){
2244191b690eSdrh       for(i=0; i<pOrderBy->nExpr; i++){
2245191b690eSdrh         if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
22461d83f052Sdrh           goto select_end;
2247191b690eSdrh         }
2248191b690eSdrh       }
2249191b690eSdrh     }
2250efb7251dSdrh   }
2251efb7251dSdrh 
22522282792aSdrh   /* Reset the aggregator
2253cce7d176Sdrh   */
2254cce7d176Sdrh   if( isAgg ){
225599fcd718Sdrh     sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
2256e5095355Sdrh     for(i=0; i<pParse->nAgg; i++){
22570bce8354Sdrh       FuncDef *pFunc;
22580bce8354Sdrh       if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
22591350b030Sdrh         sqliteVdbeAddOp(v, OP_AggInit, 0, i);
22600bce8354Sdrh         sqliteVdbeChangeP3(v, -1, (char*)pFunc, P3_POINTER);
2261e5095355Sdrh       }
2262e5095355Sdrh     }
22631bee3d7bSdrh     if( pGroupBy==0 ){
22641bee3d7bSdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
22651bee3d7bSdrh       sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
22661bee3d7bSdrh     }
2267cce7d176Sdrh   }
2268cce7d176Sdrh 
226919a775c2Sdrh   /* Initialize the memory cell to NULL
227019a775c2Sdrh   */
2271fef5208cSdrh   if( eDest==SRT_Mem ){
227299fcd718Sdrh     sqliteVdbeAddOp(v, OP_String, 0, 0);
22738721ce4aSdrh     sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
227419a775c2Sdrh   }
227519a775c2Sdrh 
2276832508b7Sdrh   /* Open a temporary table to use for the distinct set.
2277cce7d176Sdrh   */
227819a775c2Sdrh   if( isDistinct ){
2279832508b7Sdrh     distinct = pParse->nTab++;
2280c6b52df3Sdrh     sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
2281832508b7Sdrh   }else{
2282832508b7Sdrh     distinct = -1;
2283efb7251dSdrh   }
2284832508b7Sdrh 
2285832508b7Sdrh   /* Begin the database scan
2286832508b7Sdrh   */
22876a3ea0e6Sdrh   pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 0,
228868d2e591Sdrh                             pGroupBy ? 0 : &pOrderBy);
22891d83f052Sdrh   if( pWInfo==0 ) goto select_end;
2290cce7d176Sdrh 
22912282792aSdrh   /* Use the standard inner loop if we are not dealing with
22922282792aSdrh   ** aggregates
2293cce7d176Sdrh   */
2294da9d6c45Sdrh   if( !isAgg ){
2295df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2296df199a25Sdrh                     iParm, pWInfo->iContinue, pWInfo->iBreak) ){
22971d83f052Sdrh        goto select_end;
2298cce7d176Sdrh     }
2299da9d6c45Sdrh   }
2300cce7d176Sdrh 
2301e3184744Sdrh   /* If we are dealing with aggregates, then do the special aggregate
23022282792aSdrh   ** processing.
2303efb7251dSdrh   */
23042282792aSdrh   else{
23052282792aSdrh     if( pGroupBy ){
23061bee3d7bSdrh       int lbl1;
23072282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
23082282792aSdrh         sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
2309efb7251dSdrh       }
231099fcd718Sdrh       sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
2311491791a8Sdrh       if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pGroupBy);
23121bee3d7bSdrh       lbl1 = sqliteVdbeMakeLabel(v);
231399fcd718Sdrh       sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
23142282792aSdrh       for(i=0; i<pParse->nAgg; i++){
23152282792aSdrh         if( pParse->aAgg[i].isAgg ) continue;
23162282792aSdrh         sqliteExprCode(pParse, pParse->aAgg[i].pExpr);
231799fcd718Sdrh         sqliteVdbeAddOp(v, OP_AggSet, 0, i);
23182282792aSdrh       }
23192282792aSdrh       sqliteVdbeResolveLabel(v, lbl1);
23202282792aSdrh     }
23212282792aSdrh     for(i=0; i<pParse->nAgg; i++){
23222282792aSdrh       Expr *pE;
23230bce8354Sdrh       int j;
23242282792aSdrh       if( !pParse->aAgg[i].isAgg ) continue;
23252282792aSdrh       pE = pParse->aAgg[i].pExpr;
23262282792aSdrh       assert( pE->op==TK_AGG_FUNCTION );
23270bce8354Sdrh       if( pE->pList ){
2328e5095355Sdrh         for(j=0; j<pE->pList->nExpr; j++){
2329e5095355Sdrh           sqliteExprCode(pParse, pE->pList->a[j].pExpr);
2330e5095355Sdrh         }
23312282792aSdrh       }
23321350b030Sdrh       sqliteVdbeAddOp(v, OP_Integer, i, 0);
2333f55f25f0Sdrh       sqliteVdbeAddOp(v, OP_AggFunc, 0, pE->pList ? pE->pList->nExpr : 0);
23340bce8354Sdrh       assert( pParse->aAgg[i].pFunc!=0 );
23350bce8354Sdrh       assert( pParse->aAgg[i].pFunc->xStep!=0 );
23360bce8354Sdrh       sqliteVdbeChangeP3(v, -1, (char*)pParse->aAgg[i].pFunc, P3_POINTER);
23372282792aSdrh     }
23382282792aSdrh   }
23392282792aSdrh 
2340cce7d176Sdrh   /* End the database scan loop.
2341cce7d176Sdrh   */
2342cce7d176Sdrh   sqliteWhereEnd(pWInfo);
2343cce7d176Sdrh 
23442282792aSdrh   /* If we are processing aggregates, we need to set up a second loop
23452282792aSdrh   ** over all of the aggregate values and process them.
23462282792aSdrh   */
23472282792aSdrh   if( isAgg ){
23482282792aSdrh     int endagg = sqliteVdbeMakeLabel(v);
23492282792aSdrh     int startagg;
235099fcd718Sdrh     startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
23512282792aSdrh     pParse->useAgg = 1;
23522282792aSdrh     if( pHaving ){
2353f5905aa7Sdrh       sqliteExprIfFalse(pParse, pHaving, startagg, 1);
23542282792aSdrh     }
2355df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2356df199a25Sdrh                     iParm, startagg, endagg) ){
23571d83f052Sdrh       goto select_end;
23582282792aSdrh     }
235999fcd718Sdrh     sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
236099fcd718Sdrh     sqliteVdbeResolveLabel(v, endagg);
236199fcd718Sdrh     sqliteVdbeAddOp(v, OP_Noop, 0, 0);
23622282792aSdrh     pParse->useAgg = 0;
23632282792aSdrh   }
23642282792aSdrh 
2365cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
2366cce7d176Sdrh   ** and send them to the callback one by one.
2367cce7d176Sdrh   */
2368cce7d176Sdrh   if( pOrderBy ){
2369c926afbcSdrh     generateSortTail(p, v, pEList->nExpr, eDest, iParm);
2370cce7d176Sdrh   }
23716a535340Sdrh 
23726a535340Sdrh 
23736a535340Sdrh   /* Issue a null callback if that is what the user wants.
23746a535340Sdrh   */
2375326dce74Sdrh   if( eDest==SRT_Callback &&
2376326dce74Sdrh     (pParse->useCallback==0 || (pParse->db->flags & SQLITE_NullCallback)!=0)
2377326dce74Sdrh   ){
23786a535340Sdrh     sqliteVdbeAddOp(v, OP_NullCallback, pEList->nExpr, 0);
23796a535340Sdrh   }
23806a535340Sdrh 
23811d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
23821d83f052Sdrh   ** to indicate no errors.
23831d83f052Sdrh   */
23841d83f052Sdrh   rc = 0;
23851d83f052Sdrh 
23861d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
23871d83f052Sdrh   ** successful coding of the SELECT.
23881d83f052Sdrh   */
23891d83f052Sdrh select_end:
23901d83f052Sdrh   sqliteAggregateInfoReset(pParse);
23911d83f052Sdrh   return rc;
2392cce7d176Sdrh }
2393