xref: /sqlite-3.40.0/src/select.c (revision f620b4e2)
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*f620b4e2Sdrh ** $Id: select.c,v 1.151 2004/02/09 14:37:50 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 */
33ef0cae50Sdrh   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{
45b733d037Sdrh     if( pEList==0 ){
46b733d037Sdrh       pEList = sqliteExprListAppend(0, sqliteExpr(TK_ALL,0,0,0), 0);
47b733d037Sdrh     }
489bb61fe7Sdrh     pNew->pEList = pEList;
499bb61fe7Sdrh     pNew->pSrc = pSrc;
509bb61fe7Sdrh     pNew->pWhere = pWhere;
519bb61fe7Sdrh     pNew->pGroupBy = pGroupBy;
529bb61fe7Sdrh     pNew->pHaving = pHaving;
539bb61fe7Sdrh     pNew->pOrderBy = pOrderBy;
549bb61fe7Sdrh     pNew->isDistinct = isDistinct;
5582c3d636Sdrh     pNew->op = TK_SELECT;
569bbca4c1Sdrh     pNew->nLimit = nLimit;
579bbca4c1Sdrh     pNew->nOffset = nOffset;
587b58daeaSdrh     pNew->iLimit = -1;
597b58daeaSdrh     pNew->iOffset = -1;
60daffd0e5Sdrh   }
619bb61fe7Sdrh   return pNew;
629bb61fe7Sdrh }
639bb61fe7Sdrh 
649bb61fe7Sdrh /*
6501f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
6601f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
6701f3f253Sdrh ** in terms of the following bit values:
6801f3f253Sdrh **
6901f3f253Sdrh **     JT_INNER
7001f3f253Sdrh **     JT_OUTER
7101f3f253Sdrh **     JT_NATURAL
7201f3f253Sdrh **     JT_LEFT
7301f3f253Sdrh **     JT_RIGHT
7401f3f253Sdrh **
7501f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
7601f3f253Sdrh **
7701f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
7801f3f253Sdrh ** a join type, but put an error in the pParse structure.
7901f3f253Sdrh */
8001f3f253Sdrh int sqliteJoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
8101f3f253Sdrh   int jointype = 0;
8201f3f253Sdrh   Token *apAll[3];
8301f3f253Sdrh   Token *p;
8401f3f253Sdrh   static struct {
8501f3f253Sdrh     const char *zKeyword;
8601f3f253Sdrh     int nChar;
8701f3f253Sdrh     int code;
8801f3f253Sdrh   } keywords[] = {
8901f3f253Sdrh     { "natural", 7, JT_NATURAL },
90195e6967Sdrh     { "left",    4, JT_LEFT|JT_OUTER },
91195e6967Sdrh     { "right",   5, JT_RIGHT|JT_OUTER },
92195e6967Sdrh     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
9301f3f253Sdrh     { "outer",   5, JT_OUTER },
9401f3f253Sdrh     { "inner",   5, JT_INNER },
9501f3f253Sdrh     { "cross",   5, JT_INNER },
9601f3f253Sdrh   };
9701f3f253Sdrh   int i, j;
9801f3f253Sdrh   apAll[0] = pA;
9901f3f253Sdrh   apAll[1] = pB;
10001f3f253Sdrh   apAll[2] = pC;
101195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
10201f3f253Sdrh     p = apAll[i];
10301f3f253Sdrh     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
10401f3f253Sdrh       if( p->n==keywords[j].nChar
10501f3f253Sdrh           && sqliteStrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
10601f3f253Sdrh         jointype |= keywords[j].code;
10701f3f253Sdrh         break;
10801f3f253Sdrh       }
10901f3f253Sdrh     }
11001f3f253Sdrh     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
11101f3f253Sdrh       jointype |= JT_ERROR;
11201f3f253Sdrh       break;
11301f3f253Sdrh     }
11401f3f253Sdrh   }
115ad2d8307Sdrh   if(
116ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
117195e6967Sdrh      (jointype & JT_ERROR)!=0
118ad2d8307Sdrh   ){
11901f3f253Sdrh     static Token dummy = { 0, 0 };
12001f3f253Sdrh     char *zSp1 = " ", *zSp2 = " ";
12101f3f253Sdrh     if( pB==0 ){ pB = &dummy; zSp1 = 0; }
12201f3f253Sdrh     if( pC==0 ){ pC = &dummy; zSp2 = 0; }
12301f3f253Sdrh     sqliteSetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
12401f3f253Sdrh        pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0);
12501f3f253Sdrh     pParse->nErr++;
12601f3f253Sdrh     jointype = JT_INNER;
127195e6967Sdrh   }else if( jointype & JT_RIGHT ){
128da93d238Sdrh     sqliteErrorMsg(pParse,
129da93d238Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported");
130195e6967Sdrh     jointype = JT_INNER;
13101f3f253Sdrh   }
13201f3f253Sdrh   return jointype;
13301f3f253Sdrh }
13401f3f253Sdrh 
13501f3f253Sdrh /*
136ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
137ad2d8307Sdrh ** is not contained in the table.
138ad2d8307Sdrh */
139ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
140ad2d8307Sdrh   int i;
141ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
142ad2d8307Sdrh     if( sqliteStrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
143ad2d8307Sdrh   }
144ad2d8307Sdrh   return -1;
145ad2d8307Sdrh }
146ad2d8307Sdrh 
147ad2d8307Sdrh /*
148ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the
149ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2.
150ad2d8307Sdrh */
151ad2d8307Sdrh static void addWhereTerm(
152ad2d8307Sdrh   const char *zCol,        /* Name of the column */
153ad2d8307Sdrh   const Table *pTab1,      /* First table */
154ad2d8307Sdrh   const Table *pTab2,      /* Second table */
155ad2d8307Sdrh   Expr **ppExpr            /* Add the equality term to this expression */
156ad2d8307Sdrh ){
157ad2d8307Sdrh   Token dummy;
158ad2d8307Sdrh   Expr *pE1a, *pE1b, *pE1c;
159ad2d8307Sdrh   Expr *pE2a, *pE2b, *pE2c;
160ad2d8307Sdrh   Expr *pE;
161ad2d8307Sdrh 
162ad2d8307Sdrh   dummy.z = zCol;
163ad2d8307Sdrh   dummy.n = strlen(zCol);
1644b59ab5eSdrh   dummy.dyn = 0;
165ad2d8307Sdrh   pE1a = sqliteExpr(TK_ID, 0, 0, &dummy);
166ad2d8307Sdrh   pE2a = sqliteExpr(TK_ID, 0, 0, &dummy);
167ad2d8307Sdrh   dummy.z = pTab1->zName;
168ad2d8307Sdrh   dummy.n = strlen(dummy.z);
169ad2d8307Sdrh   pE1b = sqliteExpr(TK_ID, 0, 0, &dummy);
170ad2d8307Sdrh   dummy.z = pTab2->zName;
171ad2d8307Sdrh   dummy.n = strlen(dummy.z);
172ad2d8307Sdrh   pE2b = sqliteExpr(TK_ID, 0, 0, &dummy);
173ad2d8307Sdrh   pE1c = sqliteExpr(TK_DOT, pE1b, pE1a, 0);
174ad2d8307Sdrh   pE2c = sqliteExpr(TK_DOT, pE2b, pE2a, 0);
175ad2d8307Sdrh   pE = sqliteExpr(TK_EQ, pE1c, pE2c, 0);
1761f16230bSdrh   ExprSetProperty(pE, EP_FromJoin);
177ad2d8307Sdrh   if( *ppExpr ){
178ad2d8307Sdrh     *ppExpr = sqliteExpr(TK_AND, *ppExpr, pE, 0);
179ad2d8307Sdrh   }else{
180ad2d8307Sdrh     *ppExpr = pE;
181ad2d8307Sdrh   }
182ad2d8307Sdrh }
183ad2d8307Sdrh 
184ad2d8307Sdrh /*
1851f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
1861cc093c2Sdrh **
187e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
1881cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
1891f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
1901f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
1911f16230bSdrh ** WHERE clause during join processing but we need to remember that they
1921f16230bSdrh ** originated in the ON or USING clause.
1931cc093c2Sdrh */
1941cc093c2Sdrh static void setJoinExpr(Expr *p){
1951cc093c2Sdrh   while( p ){
1961f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
1971cc093c2Sdrh     setJoinExpr(p->pLeft);
1981cc093c2Sdrh     p = p->pRight;
1991cc093c2Sdrh   }
2001cc093c2Sdrh }
2011cc093c2Sdrh 
2021cc093c2Sdrh /*
203ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
204ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
205ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
206ad2d8307Sdrh **
207ad2d8307Sdrh ** This routine returns the number of errors encountered.
208ad2d8307Sdrh */
209ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
210ad2d8307Sdrh   SrcList *pSrc;
211ad2d8307Sdrh   int i, j;
212ad2d8307Sdrh   pSrc = p->pSrc;
213ad2d8307Sdrh   for(i=0; i<pSrc->nSrc-1; i++){
214ad2d8307Sdrh     struct SrcList_item *pTerm = &pSrc->a[i];
215ad2d8307Sdrh     struct SrcList_item *pOther = &pSrc->a[i+1];
216ad2d8307Sdrh 
217ad2d8307Sdrh     if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
218ad2d8307Sdrh 
219ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
220ad2d8307Sdrh     ** every column that the two tables have in common.
221ad2d8307Sdrh     */
222ad2d8307Sdrh     if( pTerm->jointype & JT_NATURAL ){
223ad2d8307Sdrh       Table *pTab;
224ad2d8307Sdrh       if( pTerm->pOn || pTerm->pUsing ){
225da93d238Sdrh         sqliteErrorMsg(pParse, "a NATURAL join may not have "
226ad2d8307Sdrh            "an ON or USING clause", 0);
227ad2d8307Sdrh         return 1;
228ad2d8307Sdrh       }
229ad2d8307Sdrh       pTab = pTerm->pTab;
230ad2d8307Sdrh       for(j=0; j<pTab->nCol; j++){
231ad2d8307Sdrh         if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
232ad2d8307Sdrh           addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
233ad2d8307Sdrh         }
234ad2d8307Sdrh       }
235ad2d8307Sdrh     }
236ad2d8307Sdrh 
237ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
238ad2d8307Sdrh     */
239ad2d8307Sdrh     if( pTerm->pOn && pTerm->pUsing ){
240da93d238Sdrh       sqliteErrorMsg(pParse, "cannot have both ON and USING "
241da93d238Sdrh         "clauses in the same join");
242ad2d8307Sdrh       return 1;
243ad2d8307Sdrh     }
244ad2d8307Sdrh 
245ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
246ad2d8307Sdrh     ** and AND operator.
247ad2d8307Sdrh     */
248ad2d8307Sdrh     if( pTerm->pOn ){
2491cc093c2Sdrh       setJoinExpr(pTerm->pOn);
250ad2d8307Sdrh       if( p->pWhere==0 ){
251ad2d8307Sdrh         p->pWhere = pTerm->pOn;
252ad2d8307Sdrh       }else{
253ad2d8307Sdrh         p->pWhere = sqliteExpr(TK_AND, p->pWhere, pTerm->pOn, 0);
254ad2d8307Sdrh       }
255ad2d8307Sdrh       pTerm->pOn = 0;
256ad2d8307Sdrh     }
257ad2d8307Sdrh 
258ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
259ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
260ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
261ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
262ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
263ad2d8307Sdrh     ** not contained in both tables to be joined.
264ad2d8307Sdrh     */
265ad2d8307Sdrh     if( pTerm->pUsing ){
266ad2d8307Sdrh       IdList *pList;
267ad2d8307Sdrh       int j;
268ad2d8307Sdrh       assert( i<pSrc->nSrc-1 );
269ad2d8307Sdrh       pList = pTerm->pUsing;
270ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
271bf5cd97eSdrh         if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
272bf5cd97eSdrh             columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
273da93d238Sdrh           sqliteErrorMsg(pParse, "cannot join using column %s - column "
274da93d238Sdrh             "not present in both tables", pList->a[j].zName);
275ad2d8307Sdrh           return 1;
276ad2d8307Sdrh         }
277bf5cd97eSdrh         addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
278ad2d8307Sdrh       }
279ad2d8307Sdrh     }
280ad2d8307Sdrh   }
281ad2d8307Sdrh   return 0;
282ad2d8307Sdrh }
283ad2d8307Sdrh 
284ad2d8307Sdrh /*
2859bb61fe7Sdrh ** Delete the given Select structure and all of its substructures.
2869bb61fe7Sdrh */
2879bb61fe7Sdrh void sqliteSelectDelete(Select *p){
28882c3d636Sdrh   if( p==0 ) return;
2899bb61fe7Sdrh   sqliteExprListDelete(p->pEList);
290ad3cab52Sdrh   sqliteSrcListDelete(p->pSrc);
2919bb61fe7Sdrh   sqliteExprDelete(p->pWhere);
2929bb61fe7Sdrh   sqliteExprListDelete(p->pGroupBy);
2939bb61fe7Sdrh   sqliteExprDelete(p->pHaving);
2949bb61fe7Sdrh   sqliteExprListDelete(p->pOrderBy);
29582c3d636Sdrh   sqliteSelectDelete(p->pPrior);
296a76b5dfcSdrh   sqliteFree(p->zSelect);
2979bb61fe7Sdrh   sqliteFree(p);
2989bb61fe7Sdrh }
2999bb61fe7Sdrh 
3009bb61fe7Sdrh /*
3012282792aSdrh ** Delete the aggregate information from the parse structure.
3022282792aSdrh */
3031d83f052Sdrh static void sqliteAggregateInfoReset(Parse *pParse){
3042282792aSdrh   sqliteFree(pParse->aAgg);
3052282792aSdrh   pParse->aAgg = 0;
3062282792aSdrh   pParse->nAgg = 0;
3072282792aSdrh   pParse->useAgg = 0;
3082282792aSdrh }
3092282792aSdrh 
3102282792aSdrh /*
311c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
312c926afbcSdrh ** stack into the sorter.
313c926afbcSdrh */
314c926afbcSdrh static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
315c926afbcSdrh   char *zSortOrder;
316c926afbcSdrh   int i;
317c926afbcSdrh   zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
318c926afbcSdrh   if( zSortOrder==0 ) return;
319c926afbcSdrh   for(i=0; i<pOrderBy->nExpr; i++){
32038640e15Sdrh     int order = pOrderBy->a[i].sortOrder;
32138640e15Sdrh     int type;
32238640e15Sdrh     int c;
32338640e15Sdrh     if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
32438640e15Sdrh       type = SQLITE_SO_TEXT;
32538640e15Sdrh     }else if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_NUM ){
32638640e15Sdrh       type = SQLITE_SO_NUM;
327491791a8Sdrh     }else if( pParse->db->file_format>=4 ){
32838640e15Sdrh       type = sqliteExprType(pOrderBy->a[i].pExpr);
32938640e15Sdrh     }else{
33038640e15Sdrh       type = SQLITE_SO_NUM;
33138640e15Sdrh     }
33238640e15Sdrh     if( (order & SQLITE_SO_DIRMASK)==SQLITE_SO_ASC ){
33338640e15Sdrh       c = type==SQLITE_SO_TEXT ? 'A' : '+';
33438640e15Sdrh     }else{
33538640e15Sdrh       c = type==SQLITE_SO_TEXT ? 'D' : '-';
33638640e15Sdrh     }
33738640e15Sdrh     zSortOrder[i] = c;
338c926afbcSdrh     sqliteExprCode(pParse, pOrderBy->a[i].pExpr);
339c926afbcSdrh   }
340c926afbcSdrh   zSortOrder[pOrderBy->nExpr] = 0;
341c926afbcSdrh   sqliteVdbeAddOp(v, OP_SortMakeKey, pOrderBy->nExpr, 0);
342c926afbcSdrh   sqliteVdbeChangeP3(v, -1, zSortOrder, strlen(zSortOrder));
343c926afbcSdrh   sqliteFree(zSortOrder);
344c926afbcSdrh   sqliteVdbeAddOp(v, OP_SortPut, 0, 0);
345c926afbcSdrh }
346c926afbcSdrh 
347c926afbcSdrh /*
34838640e15Sdrh ** This routine adds a P3 argument to the last VDBE opcode that was
34938640e15Sdrh ** inserted. The P3 argument added is a string suitable for the
35038640e15Sdrh ** OP_MakeKey or OP_MakeIdxKey opcodes.  The string consists of
35138640e15Sdrh ** characters 't' or 'n' depending on whether or not the various
35238640e15Sdrh ** fields of the key to be generated should be treated as numeric
35338640e15Sdrh ** or as text.  See the OP_MakeKey and OP_MakeIdxKey opcode
35438640e15Sdrh ** documentation for additional information about the P3 string.
35538640e15Sdrh ** See also the sqliteAddIdxKeyType() routine.
35638640e15Sdrh */
35738640e15Sdrh void sqliteAddKeyType(Vdbe *v, ExprList *pEList){
35838640e15Sdrh   int nColumn = pEList->nExpr;
35938640e15Sdrh   char *zType = sqliteMalloc( nColumn+1 );
36038640e15Sdrh   int i;
36138640e15Sdrh   if( zType==0 ) return;
36238640e15Sdrh   for(i=0; i<nColumn; i++){
36338640e15Sdrh     zType[i] = sqliteExprType(pEList->a[i].pExpr)==SQLITE_SO_NUM ? 'n' : 't';
36438640e15Sdrh   }
36538640e15Sdrh   zType[i] = 0;
36638640e15Sdrh   sqliteVdbeChangeP3(v, -1, zType, nColumn);
36738640e15Sdrh   sqliteFree(zType);
36838640e15Sdrh }
36938640e15Sdrh 
37038640e15Sdrh /*
3712282792aSdrh ** This routine generates the code for the inside of the inner loop
3722282792aSdrh ** of a SELECT.
37382c3d636Sdrh **
37438640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
37538640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
37638640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
37738640e15Sdrh ** datatypes for each column.
3782282792aSdrh */
3792282792aSdrh static int selectInnerLoop(
3802282792aSdrh   Parse *pParse,          /* The parser context */
381df199a25Sdrh   Select *p,              /* The complete select statement being coded */
3822282792aSdrh   ExprList *pEList,       /* List of values being extracted */
38382c3d636Sdrh   int srcTab,             /* Pull data from this table */
384967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
3852282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
3862282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
3872282792aSdrh   int eDest,              /* How to dispose of the results */
3882282792aSdrh   int iParm,              /* An argument to the disposal method */
3892282792aSdrh   int iContinue,          /* Jump here to continue with next row */
3902282792aSdrh   int iBreak              /* Jump here to break out of the inner loop */
3912282792aSdrh ){
3922282792aSdrh   Vdbe *v = pParse->pVdbe;
3932282792aSdrh   int i;
39438640e15Sdrh 
395daffd0e5Sdrh   if( v==0 ) return 0;
39638640e15Sdrh   assert( pEList!=0 );
3972282792aSdrh 
398df199a25Sdrh   /* If there was a LIMIT clause on the SELECT statement, then do the check
399df199a25Sdrh   ** to see if this row should be output.
400df199a25Sdrh   */
401df199a25Sdrh   if( pOrderBy==0 ){
4027b58daeaSdrh     if( p->iOffset>=0 ){
403d11d382cSdrh       int addr = sqliteVdbeCurrentAddr(v);
4047b58daeaSdrh       sqliteVdbeAddOp(v, OP_MemIncr, p->iOffset, addr+2);
405d11d382cSdrh       sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
406df199a25Sdrh     }
4077b58daeaSdrh     if( p->iLimit>=0 ){
4087b58daeaSdrh       sqliteVdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
409df199a25Sdrh     }
410df199a25Sdrh   }
411df199a25Sdrh 
412967e8b73Sdrh   /* Pull the requested columns.
4132282792aSdrh   */
41438640e15Sdrh   if( nColumn>0 ){
415967e8b73Sdrh     for(i=0; i<nColumn; i++){
41699fcd718Sdrh       sqliteVdbeAddOp(v, OP_Column, srcTab, i);
41782c3d636Sdrh     }
41838640e15Sdrh   }else{
41938640e15Sdrh     nColumn = pEList->nExpr;
42038640e15Sdrh     for(i=0; i<pEList->nExpr; i++){
42138640e15Sdrh       sqliteExprCode(pParse, pEList->a[i].pExpr);
42238640e15Sdrh     }
42382c3d636Sdrh   }
4242282792aSdrh 
425daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
426daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
427daffd0e5Sdrh   ** part of the result.
4282282792aSdrh   */
429f5905aa7Sdrh   if( distinct>=0 && pEList && pEList->nExpr>0 ){
4300bd1f4eaSdrh #if NULL_ALWAYS_DISTINCT
4310bd1f4eaSdrh     sqliteVdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqliteVdbeCurrentAddr(v)+7);
4320bd1f4eaSdrh #endif
43399fcd718Sdrh     sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
434491791a8Sdrh     if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pEList);
435f5905aa7Sdrh     sqliteVdbeAddOp(v, OP_Distinct, distinct, sqliteVdbeCurrentAddr(v)+3);
43699fcd718Sdrh     sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
43799fcd718Sdrh     sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
43899fcd718Sdrh     sqliteVdbeAddOp(v, OP_String, 0, 0);
4396b12545fSdrh     sqliteVdbeAddOp(v, OP_PutStrKey, distinct, 0);
4402282792aSdrh   }
44182c3d636Sdrh 
442c926afbcSdrh   switch( eDest ){
44382c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
44482c3d636Sdrh     ** table iParm.
4452282792aSdrh     */
446c926afbcSdrh     case SRT_Union: {
4470bd1f4eaSdrh       sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
448f5905aa7Sdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
4496b12545fSdrh       sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
450c926afbcSdrh       break;
451c926afbcSdrh     }
45282c3d636Sdrh 
4535974a30fSdrh     /* Store the result as data using a unique key.
4545974a30fSdrh     */
455c926afbcSdrh     case SRT_Table:
456c926afbcSdrh     case SRT_TempTable: {
45799fcd718Sdrh       sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
458c926afbcSdrh       if( pOrderBy ){
459c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
460c926afbcSdrh       }else{
46199fcd718Sdrh         sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
46299fcd718Sdrh         sqliteVdbeAddOp(v, OP_Pull, 1, 0);
4636b12545fSdrh         sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
464c926afbcSdrh       }
465c926afbcSdrh       break;
466c926afbcSdrh     }
4675974a30fSdrh 
46882c3d636Sdrh     /* Construct a record from the query result, but instead of
46982c3d636Sdrh     ** saving that record, use it as a key to delete elements from
47082c3d636Sdrh     ** the temporary table iParm.
47182c3d636Sdrh     */
472c926afbcSdrh     case SRT_Except: {
4730bd1f4eaSdrh       int addr;
4740bd1f4eaSdrh       addr = sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
47599fcd718Sdrh       sqliteVdbeAddOp(v, OP_NotFound, iParm, addr+3);
47699fcd718Sdrh       sqliteVdbeAddOp(v, OP_Delete, iParm, 0);
477c926afbcSdrh       break;
478c926afbcSdrh     }
4792282792aSdrh 
4802282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
4812282792aSdrh     ** then there should be a single item on the stack.  Write this
4822282792aSdrh     ** item into the set table with bogus data.
4832282792aSdrh     */
484c926afbcSdrh     case SRT_Set: {
48552b36cabSdrh       int addr1 = sqliteVdbeCurrentAddr(v);
48652b36cabSdrh       int addr2;
487967e8b73Sdrh       assert( nColumn==1 );
48852b36cabSdrh       sqliteVdbeAddOp(v, OP_NotNull, -1, addr1+3);
48952b36cabSdrh       sqliteVdbeAddOp(v, OP_Pop, 1, 0);
49052b36cabSdrh       addr2 = sqliteVdbeAddOp(v, OP_Goto, 0, 0);
491c926afbcSdrh       if( pOrderBy ){
492c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
493c926afbcSdrh       }else{
494a9f9d1c0Sdrh         sqliteVdbeAddOp(v, OP_String, 0, 0);
4956b12545fSdrh         sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
496c926afbcSdrh       }
49752b36cabSdrh       sqliteVdbeChangeP2(v, addr2, sqliteVdbeCurrentAddr(v));
498c926afbcSdrh       break;
499c926afbcSdrh     }
50082c3d636Sdrh 
5012282792aSdrh     /* If this is a scalar select that is part of an expression, then
5022282792aSdrh     ** store the results in the appropriate memory cell and break out
5032282792aSdrh     ** of the scan loop.
5042282792aSdrh     */
505c926afbcSdrh     case SRT_Mem: {
506967e8b73Sdrh       assert( nColumn==1 );
507c926afbcSdrh       if( pOrderBy ){
508c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
509c926afbcSdrh       }else{
5108721ce4aSdrh         sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
51199fcd718Sdrh         sqliteVdbeAddOp(v, OP_Goto, 0, iBreak);
512c926afbcSdrh       }
513c926afbcSdrh       break;
514c926afbcSdrh     }
5152282792aSdrh 
516f46f905aSdrh     /* Send the data to the callback function.
517f46f905aSdrh     */
518f46f905aSdrh     case SRT_Callback:
519f46f905aSdrh     case SRT_Sorter: {
520f46f905aSdrh       if( pOrderBy ){
521f46f905aSdrh         sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
522f46f905aSdrh         pushOntoSorter(pParse, v, pOrderBy);
523f46f905aSdrh       }else{
524f46f905aSdrh         assert( eDest==SRT_Callback );
525f46f905aSdrh         sqliteVdbeAddOp(v, OP_Callback, nColumn, 0);
526f46f905aSdrh       }
527f46f905aSdrh       break;
528f46f905aSdrh     }
529f46f905aSdrh 
530142e30dfSdrh     /* Invoke a subroutine to handle the results.  The subroutine itself
531142e30dfSdrh     ** is responsible for popping the results off of the stack.
532142e30dfSdrh     */
533142e30dfSdrh     case SRT_Subroutine: {
534ac82fcf5Sdrh       if( pOrderBy ){
535ac82fcf5Sdrh         sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
536ac82fcf5Sdrh         pushOntoSorter(pParse, v, pOrderBy);
537ac82fcf5Sdrh       }else{
538142e30dfSdrh         sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
539ac82fcf5Sdrh       }
540142e30dfSdrh       break;
541142e30dfSdrh     }
542142e30dfSdrh 
543d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
544d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
545d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
546d7489c39Sdrh     ** about the actual results of the select.
547d7489c39Sdrh     */
548c926afbcSdrh     default: {
549f46f905aSdrh       assert( eDest==SRT_Discard );
550f46f905aSdrh       sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
551c926afbcSdrh       break;
552c926afbcSdrh     }
553c926afbcSdrh   }
55482c3d636Sdrh   return 0;
55582c3d636Sdrh }
55682c3d636Sdrh 
55782c3d636Sdrh /*
558d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
559d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
560d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
561d8bc7086Sdrh ** routine generates the code needed to do that.
562d8bc7086Sdrh */
563c926afbcSdrh static void generateSortTail(
564c926afbcSdrh   Select *p,       /* The SELECT statement */
565c926afbcSdrh   Vdbe *v,         /* Generate code into this VDBE */
566c926afbcSdrh   int nColumn,     /* Number of columns of data */
567c926afbcSdrh   int eDest,       /* Write the sorted results here */
568c926afbcSdrh   int iParm        /* Optional parameter associated with eDest */
569c926afbcSdrh ){
570d8bc7086Sdrh   int end = sqliteVdbeMakeLabel(v);
571d8bc7086Sdrh   int addr;
572f46f905aSdrh   if( eDest==SRT_Sorter ) return;
57399fcd718Sdrh   sqliteVdbeAddOp(v, OP_Sort, 0, 0);
57499fcd718Sdrh   addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end);
5757b58daeaSdrh   if( p->iOffset>=0 ){
5767b58daeaSdrh     sqliteVdbeAddOp(v, OP_MemIncr, p->iOffset, addr+4);
577d11d382cSdrh     sqliteVdbeAddOp(v, OP_Pop, 1, 0);
578d11d382cSdrh     sqliteVdbeAddOp(v, OP_Goto, 0, addr);
579df199a25Sdrh   }
5807b58daeaSdrh   if( p->iLimit>=0 ){
5817b58daeaSdrh     sqliteVdbeAddOp(v, OP_MemIncr, p->iLimit, end);
582df199a25Sdrh   }
583c926afbcSdrh   switch( eDest ){
584c926afbcSdrh     case SRT_Callback: {
585df199a25Sdrh       sqliteVdbeAddOp(v, OP_SortCallback, nColumn, 0);
586c926afbcSdrh       break;
587c926afbcSdrh     }
588c926afbcSdrh     case SRT_Table:
589c926afbcSdrh     case SRT_TempTable: {
590c926afbcSdrh       sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
591c926afbcSdrh       sqliteVdbeAddOp(v, OP_Pull, 1, 0);
592c926afbcSdrh       sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
593c926afbcSdrh       break;
594c926afbcSdrh     }
595c926afbcSdrh     case SRT_Set: {
596c926afbcSdrh       assert( nColumn==1 );
59752b36cabSdrh       sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
59852b36cabSdrh       sqliteVdbeAddOp(v, OP_Pop, 1, 0);
59952b36cabSdrh       sqliteVdbeAddOp(v, OP_Goto, 0, sqliteVdbeCurrentAddr(v)+3);
600c926afbcSdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
601c926afbcSdrh       sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
602c926afbcSdrh       break;
603c926afbcSdrh     }
604c926afbcSdrh     case SRT_Mem: {
605c926afbcSdrh       assert( nColumn==1 );
606c926afbcSdrh       sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
607c926afbcSdrh       sqliteVdbeAddOp(v, OP_Goto, 0, end);
608c926afbcSdrh       break;
609c926afbcSdrh     }
610ac82fcf5Sdrh     case SRT_Subroutine: {
611ac82fcf5Sdrh       int i;
612ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
613ac82fcf5Sdrh         sqliteVdbeAddOp(v, OP_Column, -1-i, i);
614ac82fcf5Sdrh       }
615ac82fcf5Sdrh       sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
616ac82fcf5Sdrh       sqliteVdbeAddOp(v, OP_Pop, 1, 0);
617ac82fcf5Sdrh       break;
618ac82fcf5Sdrh     }
619c926afbcSdrh     default: {
620f46f905aSdrh       /* Do nothing */
621c926afbcSdrh       break;
622c926afbcSdrh     }
623c926afbcSdrh   }
62499fcd718Sdrh   sqliteVdbeAddOp(v, OP_Goto, 0, addr);
62599fcd718Sdrh   sqliteVdbeResolveLabel(v, end);
626a8b38d28Sdrh   sqliteVdbeAddOp(v, OP_SortReset, 0, 0);
627d8bc7086Sdrh }
628d8bc7086Sdrh 
629d8bc7086Sdrh /*
630fcb78a49Sdrh ** Generate code that will tell the VDBE the datatypes of
631fcb78a49Sdrh ** columns in the result set.
632e78e8284Sdrh **
633e78e8284Sdrh ** This routine only generates code if the "PRAGMA show_datatypes=on"
634e78e8284Sdrh ** has been executed.  The datatypes are reported out in the azCol
635e78e8284Sdrh ** parameter to the callback function.  The first N azCol[] entries
636e78e8284Sdrh ** are the names of the columns, and the second N entries are the
637e78e8284Sdrh ** datatypes for the columns.
638e78e8284Sdrh **
639e78e8284Sdrh ** The "datatype" for a result that is a column of a type is the
640e78e8284Sdrh ** datatype definition extracted from the CREATE TABLE statement.
641e78e8284Sdrh ** The datatype for an expression is either TEXT or NUMERIC.  The
642e78e8284Sdrh ** datatype for a ROWID field is INTEGER.
643fcb78a49Sdrh */
644fcb78a49Sdrh static void generateColumnTypes(
645fcb78a49Sdrh   Parse *pParse,      /* Parser context */
646fcb78a49Sdrh   SrcList *pTabList,  /* List of tables */
647fcb78a49Sdrh   ExprList *pEList    /* Expressions defining the result set */
648fcb78a49Sdrh ){
649fcb78a49Sdrh   Vdbe *v = pParse->pVdbe;
6506a3ea0e6Sdrh   int i, j;
651326dce74Sdrh   if( pParse->useCallback && (pParse->db->flags & SQLITE_ReportTypes)==0 ){
652326dce74Sdrh     return;
653326dce74Sdrh   }
654fcb78a49Sdrh   for(i=0; i<pEList->nExpr; i++){
655fcb78a49Sdrh     Expr *p = pEList->a[i].pExpr;
656fcb78a49Sdrh     char *zType = 0;
657fcb78a49Sdrh     if( p==0 ) continue;
658fcb78a49Sdrh     if( p->op==TK_COLUMN && pTabList ){
6596a3ea0e6Sdrh       Table *pTab;
660fcb78a49Sdrh       int iCol = p->iColumn;
6616a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
6626a3ea0e6Sdrh       assert( j<pTabList->nSrc );
6636a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
664fcb78a49Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
665fcb78a49Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
666fcb78a49Sdrh       if( iCol<0 ){
667fcb78a49Sdrh         zType = "INTEGER";
668fcb78a49Sdrh       }else{
669fcb78a49Sdrh         zType = pTab->aCol[iCol].zType;
670fcb78a49Sdrh       }
671fcb78a49Sdrh     }else{
672fcb78a49Sdrh       if( sqliteExprType(p)==SQLITE_SO_TEXT ){
673fcb78a49Sdrh         zType = "TEXT";
674fcb78a49Sdrh       }else{
675fcb78a49Sdrh         zType = "NUMERIC";
676fcb78a49Sdrh       }
677fcb78a49Sdrh     }
678fcb78a49Sdrh     sqliteVdbeAddOp(v, OP_ColumnName, i + pEList->nExpr, 0);
679fcb78a49Sdrh     sqliteVdbeChangeP3(v, -1, zType, P3_STATIC);
680fcb78a49Sdrh   }
681fcb78a49Sdrh }
682fcb78a49Sdrh 
683fcb78a49Sdrh /*
684fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
685fcb78a49Sdrh ** in the result set.  This information is used to provide the
686fcb78a49Sdrh ** azCol[] vaolues in the callback.
68782c3d636Sdrh */
688832508b7Sdrh static void generateColumnNames(
689832508b7Sdrh   Parse *pParse,      /* Parser context */
690ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
691832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
692832508b7Sdrh ){
693d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
6946a3ea0e6Sdrh   int i, j;
695daffd0e5Sdrh   if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return;
696d8bc7086Sdrh   pParse->colNamesSet = 1;
69782c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
69882c3d636Sdrh     Expr *p;
699b1363206Sdrh     char *zType = 0;
7001bee3d7bSdrh     int showFullNames;
7015a38705eSdrh     p = pEList->a[i].pExpr;
7025a38705eSdrh     if( p==0 ) continue;
70382c3d636Sdrh     if( pEList->a[i].zName ){
70482c3d636Sdrh       char *zName = pEList->a[i].zName;
70599fcd718Sdrh       sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
70699fcd718Sdrh       sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
70782c3d636Sdrh       continue;
70882c3d636Sdrh     }
7091bee3d7bSdrh     showFullNames = (pParse->db->flags & SQLITE_FullColNames)!=0;
710fa173a76Sdrh     if( p->op==TK_COLUMN && pTabList ){
7116a3ea0e6Sdrh       Table *pTab;
71297665873Sdrh       char *zCol;
7138aff1015Sdrh       int iCol = p->iColumn;
7146a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
7156a3ea0e6Sdrh       assert( j<pTabList->nSrc );
7166a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
7178aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
71897665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
719b1363206Sdrh       if( iCol<0 ){
720b1363206Sdrh         zCol = "_ROWID_";
721b1363206Sdrh         zType = "INTEGER";
722b1363206Sdrh       }else{
723b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
724b1363206Sdrh         zType = pTab->aCol[iCol].zType;
725b1363206Sdrh       }
7266977fea8Sdrh       if( p->span.z && p->span.z[0] && !showFullNames ){
727fa173a76Sdrh         int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
7286977fea8Sdrh         sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
729fa173a76Sdrh         sqliteVdbeCompressSpace(v, addr);
730fa173a76Sdrh       }else if( pTabList->nSrc>1 || showFullNames ){
73182c3d636Sdrh         char *zName = 0;
73282c3d636Sdrh         char *zTab;
73382c3d636Sdrh 
7346a3ea0e6Sdrh         zTab = pTabList->a[j].zAlias;
73501a34661Sdrh         if( showFullNames || zTab==0 ) zTab = pTab->zName;
73697665873Sdrh         sqliteSetString(&zName, zTab, ".", zCol, 0);
73799fcd718Sdrh         sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
73899fcd718Sdrh         sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
73982c3d636Sdrh         sqliteFree(zName);
74082c3d636Sdrh       }else{
74199fcd718Sdrh         sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
74222f70c32Sdrh         sqliteVdbeChangeP3(v, -1, zCol, 0);
74382c3d636Sdrh       }
7446977fea8Sdrh     }else if( p->span.z && p->span.z[0] ){
745fa173a76Sdrh       int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
7466977fea8Sdrh       sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
7471bee3d7bSdrh       sqliteVdbeCompressSpace(v, addr);
7481bee3d7bSdrh     }else{
7491bee3d7bSdrh       char zName[30];
7501bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
7511bee3d7bSdrh       sprintf(zName, "column%d", i+1);
7521bee3d7bSdrh       sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
7531bee3d7bSdrh       sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
75482c3d636Sdrh     }
75582c3d636Sdrh   }
7565080aaa7Sdrh }
75782c3d636Sdrh 
75882c3d636Sdrh /*
759d8bc7086Sdrh ** Name of the connection operator, used for error messages.
760d8bc7086Sdrh */
761d8bc7086Sdrh static const char *selectOpName(int id){
762d8bc7086Sdrh   char *z;
763d8bc7086Sdrh   switch( id ){
764d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
765d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
766d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
767d8bc7086Sdrh     default:           z = "UNION";       break;
768d8bc7086Sdrh   }
769d8bc7086Sdrh   return z;
770d8bc7086Sdrh }
771d8bc7086Sdrh 
772d8bc7086Sdrh /*
773315555caSdrh ** Forward declaration
774315555caSdrh */
775315555caSdrh static int fillInColumnList(Parse*, Select*);
776315555caSdrh 
777315555caSdrh /*
77822f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
77922f70c32Sdrh ** the result set of that SELECT.
78022f70c32Sdrh */
78122f70c32Sdrh Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
78222f70c32Sdrh   Table *pTab;
783b733d037Sdrh   int i, j;
78422f70c32Sdrh   ExprList *pEList;
785b733d037Sdrh   Column *aCol;
78622f70c32Sdrh 
78722f70c32Sdrh   if( fillInColumnList(pParse, pSelect) ){
78822f70c32Sdrh     return 0;
78922f70c32Sdrh   }
79022f70c32Sdrh   pTab = sqliteMalloc( sizeof(Table) );
79122f70c32Sdrh   if( pTab==0 ){
79222f70c32Sdrh     return 0;
79322f70c32Sdrh   }
79422f70c32Sdrh   pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
79522f70c32Sdrh   pEList = pSelect->pEList;
79622f70c32Sdrh   pTab->nCol = pEList->nExpr;
797417be79cSdrh   assert( pTab->nCol>0 );
798b733d037Sdrh   pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
79922f70c32Sdrh   for(i=0; i<pTab->nCol; i++){
800b733d037Sdrh     Expr *p, *pR;
80122f70c32Sdrh     if( pEList->a[i].zName ){
802b733d037Sdrh       aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
803b733d037Sdrh     }else if( (p=pEList->a[i].pExpr)->op==TK_DOT
804b733d037Sdrh                && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
805b733d037Sdrh       int cnt;
806b733d037Sdrh       sqliteSetNString(&aCol[i].zName, pR->token.z, pR->token.n, 0);
807b733d037Sdrh       for(j=cnt=0; j<i; j++){
808b733d037Sdrh         if( sqliteStrICmp(aCol[j].zName, aCol[i].zName)==0 ){
809b733d037Sdrh           int n;
810b733d037Sdrh           char zBuf[30];
811b733d037Sdrh           sprintf(zBuf,"_%d",++cnt);
812b733d037Sdrh           n = strlen(zBuf);
813b733d037Sdrh           sqliteSetNString(&aCol[i].zName, pR->token.z, pR->token.n, zBuf, n,0);
814b733d037Sdrh           j = -1;
815b733d037Sdrh         }
816b733d037Sdrh       }
817b733d037Sdrh     }else if( p->span.z && p->span.z[0] ){
8186977fea8Sdrh       sqliteSetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
81922f70c32Sdrh     }else{
82022f70c32Sdrh       char zBuf[30];
82122f70c32Sdrh       sprintf(zBuf, "column%d", i+1);
82222f70c32Sdrh       pTab->aCol[i].zName = sqliteStrDup(zBuf);
82322f70c32Sdrh     }
82422f70c32Sdrh   }
82522f70c32Sdrh   pTab->iPKey = -1;
82622f70c32Sdrh   return pTab;
82722f70c32Sdrh }
82822f70c32Sdrh 
82922f70c32Sdrh /*
830ad2d8307Sdrh ** For the given SELECT statement, do three things.
831d8bc7086Sdrh **
832ad3cab52Sdrh **    (1)  Fill in the pTabList->a[].pTab fields in the SrcList that
83363eb5f29Sdrh **         defines the set of tables that should be scanned.  For views,
83463eb5f29Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
83563eb5f29Sdrh **         that implements the view.  A copy is made of the view's SELECT
83663eb5f29Sdrh **         statement so that we can freely modify or delete that statement
83763eb5f29Sdrh **         without worrying about messing up the presistent representation
83863eb5f29Sdrh **         of the view.
839d8bc7086Sdrh **
840ad2d8307Sdrh **    (2)  Add terms to the WHERE clause to accomodate the NATURAL keyword
841ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
842ad2d8307Sdrh **
843ad2d8307Sdrh **    (3)  Scan the list of columns in the result set (pEList) looking
84454473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
84554473229Sdrh **         If found, expand each "*" to be every column in every table
84654473229Sdrh **         and TABLE.* to be every column in TABLE.
847d8bc7086Sdrh **
848d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
849d8bc7086Sdrh ** in pParse and return non-zero.
850d8bc7086Sdrh */
851d8bc7086Sdrh static int fillInColumnList(Parse *pParse, Select *p){
85254473229Sdrh   int i, j, k, rc;
853ad3cab52Sdrh   SrcList *pTabList;
854daffd0e5Sdrh   ExprList *pEList;
855a76b5dfcSdrh   Table *pTab;
856daffd0e5Sdrh 
857daffd0e5Sdrh   if( p==0 || p->pSrc==0 ) return 1;
858daffd0e5Sdrh   pTabList = p->pSrc;
859daffd0e5Sdrh   pEList = p->pEList;
860d8bc7086Sdrh 
861d8bc7086Sdrh   /* Look up every table in the table list.
862d8bc7086Sdrh   */
863ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
864d8bc7086Sdrh     if( pTabList->a[i].pTab ){
865d8bc7086Sdrh       /* This routine has run before!  No need to continue */
866d8bc7086Sdrh       return 0;
867d8bc7086Sdrh     }
868daffd0e5Sdrh     if( pTabList->a[i].zName==0 ){
86922f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
87022f70c32Sdrh       assert( pTabList->a[i].pSelect!=0 );
871ad2d8307Sdrh       if( pTabList->a[i].zAlias==0 ){
872ad2d8307Sdrh         char zFakeName[60];
873ad2d8307Sdrh         sprintf(zFakeName, "sqlite_subquery_%p_",
874ad2d8307Sdrh            (void*)pTabList->a[i].pSelect);
875ad2d8307Sdrh         sqliteSetString(&pTabList->a[i].zAlias, zFakeName, 0);
876ad2d8307Sdrh       }
87722f70c32Sdrh       pTabList->a[i].pTab = pTab =
87822f70c32Sdrh         sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias,
87922f70c32Sdrh                                         pTabList->a[i].pSelect);
88022f70c32Sdrh       if( pTab==0 ){
881daffd0e5Sdrh         return 1;
882daffd0e5Sdrh       }
8835cf590c1Sdrh       /* The isTransient flag indicates that the Table structure has been
8845cf590c1Sdrh       ** dynamically allocated and may be freed at any time.  In other words,
8855cf590c1Sdrh       ** pTab is not pointing to a persistent table structure that defines
8865cf590c1Sdrh       ** part of the schema. */
88722f70c32Sdrh       pTab->isTransient = 1;
88822f70c32Sdrh     }else{
889a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
890a76b5dfcSdrh       pTabList->a[i].pTab = pTab =
891a69d9168Sdrh         sqliteLocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
892a76b5dfcSdrh       if( pTab==0 ){
893d8bc7086Sdrh         return 1;
894d8bc7086Sdrh       }
895a76b5dfcSdrh       if( pTab->pSelect ){
89663eb5f29Sdrh         /* We reach here if the named table is a really a view */
897417be79cSdrh         if( sqliteViewGetColumnNames(pParse, pTab) ){
898417be79cSdrh           return 1;
899417be79cSdrh         }
90063eb5f29Sdrh         /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
90163eb5f29Sdrh         ** view within a view.  The SELECT structure has already been
90263eb5f29Sdrh         ** copied by the outer view so we can skip the copy step here
90363eb5f29Sdrh         ** in the inner view.
90463eb5f29Sdrh         */
90563eb5f29Sdrh         if( pTabList->a[i].pSelect==0 ){
906ff78bd2fSdrh           pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect);
907a76b5dfcSdrh         }
908d8bc7086Sdrh       }
90922f70c32Sdrh     }
91063eb5f29Sdrh   }
911d8bc7086Sdrh 
912ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
913ad2d8307Sdrh   */
914ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
915ad2d8307Sdrh 
9167c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
91754473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
91854473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
9197c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
9207c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
9217c917d19Sdrh   ** each one to the list of all columns in all tables.
92254473229Sdrh   **
92354473229Sdrh   ** The first loop just checks to see if there are any "*" operators
92454473229Sdrh   ** that need expanding.
925d8bc7086Sdrh   */
9267c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
92754473229Sdrh     Expr *pE = pEList->a[k].pExpr;
92854473229Sdrh     if( pE->op==TK_ALL ) break;
92954473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
93054473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
9317c917d19Sdrh   }
93254473229Sdrh   rc = 0;
9337c917d19Sdrh   if( k<pEList->nExpr ){
93454473229Sdrh     /*
93554473229Sdrh     ** If we get here it means the result set contains one or more "*"
93654473229Sdrh     ** operators that need to be expanded.  Loop through each expression
93754473229Sdrh     ** in the result set and expand them one by one.
93854473229Sdrh     */
9397c917d19Sdrh     struct ExprList_item *a = pEList->a;
9407c917d19Sdrh     ExprList *pNew = 0;
9417c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
94254473229Sdrh       Expr *pE = a[k].pExpr;
94354473229Sdrh       if( pE->op!=TK_ALL &&
94454473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
94554473229Sdrh         /* This particular expression does not need to be expanded.
94654473229Sdrh         */
9477c917d19Sdrh         pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
9487c917d19Sdrh         pNew->a[pNew->nExpr-1].zName = a[k].zName;
9497c917d19Sdrh         a[k].pExpr = 0;
9507c917d19Sdrh         a[k].zName = 0;
9517c917d19Sdrh       }else{
95254473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
95354473229Sdrh         ** expanded. */
95454473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
95554473229Sdrh         Token *pName;           /* text of name of TABLE */
95654473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
95754473229Sdrh           pName = &pE->pLeft->token;
95854473229Sdrh         }else{
95954473229Sdrh           pName = 0;
96054473229Sdrh         }
961ad3cab52Sdrh         for(i=0; i<pTabList->nSrc; i++){
962d8bc7086Sdrh           Table *pTab = pTabList->a[i].pTab;
96354473229Sdrh           char *zTabName = pTabList->a[i].zAlias;
96454473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
96554473229Sdrh             zTabName = pTab->zName;
96654473229Sdrh           }
96754473229Sdrh           if( pName && (zTabName==0 || zTabName[0]==0 ||
968c754fa54Sdrh                  sqliteStrNICmp(pName->z, zTabName, pName->n)!=0 ||
969c754fa54Sdrh                  zTabName[pName->n]!=0) ){
97054473229Sdrh             continue;
97154473229Sdrh           }
97254473229Sdrh           tableSeen = 1;
973d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
97422f70c32Sdrh             Expr *pExpr, *pLeft, *pRight;
975ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
976ad2d8307Sdrh 
977ad2d8307Sdrh             if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
978ad2d8307Sdrh                 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
979ad2d8307Sdrh               /* In a NATURAL join, omit the join columns from the
980ad2d8307Sdrh               ** table on the right */
981ad2d8307Sdrh               continue;
982ad2d8307Sdrh             }
983ad2d8307Sdrh             if( i>0 && sqliteIdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
984ad2d8307Sdrh               /* In a join with a USING clause, omit columns in the
985ad2d8307Sdrh               ** using clause from the table on the right. */
986ad2d8307Sdrh               continue;
987ad2d8307Sdrh             }
98822f70c32Sdrh             pRight = sqliteExpr(TK_ID, 0, 0, 0);
98922f70c32Sdrh             if( pRight==0 ) break;
990ad2d8307Sdrh             pRight->token.z = zName;
991ad2d8307Sdrh             pRight->token.n = strlen(zName);
9924b59ab5eSdrh             pRight->token.dyn = 0;
9934b59ab5eSdrh             if( zTabName && pTabList->nSrc>1 ){
99422f70c32Sdrh               pLeft = sqliteExpr(TK_ID, 0, 0, 0);
99522f70c32Sdrh               pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
99622f70c32Sdrh               if( pExpr==0 ) break;
9974b59ab5eSdrh               pLeft->token.z = zTabName;
9984b59ab5eSdrh               pLeft->token.n = strlen(zTabName);
9994b59ab5eSdrh               pLeft->token.dyn = 0;
10006977fea8Sdrh               sqliteSetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
10016977fea8Sdrh               pExpr->span.n = strlen(pExpr->span.z);
10026977fea8Sdrh               pExpr->span.dyn = 1;
10036977fea8Sdrh               pExpr->token.z = 0;
10046977fea8Sdrh               pExpr->token.n = 0;
10056977fea8Sdrh               pExpr->token.dyn = 0;
100622f70c32Sdrh             }else{
100722f70c32Sdrh               pExpr = pRight;
10086977fea8Sdrh               pExpr->span = pExpr->token;
100922f70c32Sdrh             }
10107c917d19Sdrh             pNew = sqliteExprListAppend(pNew, pExpr, 0);
1011d8bc7086Sdrh           }
1012d8bc7086Sdrh         }
101354473229Sdrh         if( !tableSeen ){
1014f5db2d3eSdrh           if( pName ){
1015da93d238Sdrh             sqliteErrorMsg(pParse, "no such table: %T", pName);
1016f5db2d3eSdrh           }else{
1017da93d238Sdrh             sqliteErrorMsg(pParse, "no tables specified");
1018f5db2d3eSdrh           }
101954473229Sdrh           rc = 1;
102054473229Sdrh         }
10217c917d19Sdrh       }
10227c917d19Sdrh     }
10237c917d19Sdrh     sqliteExprListDelete(pEList);
10247c917d19Sdrh     p->pEList = pNew;
1025d8bc7086Sdrh   }
102654473229Sdrh   return rc;
1027d8bc7086Sdrh }
1028d8bc7086Sdrh 
1029d8bc7086Sdrh /*
1030ff78bd2fSdrh ** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1031ff78bd2fSdrh ** in a select structure.  It just sets the pointers to NULL.  This
1032ff78bd2fSdrh ** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1033ff78bd2fSdrh ** pointer is not NULL, this routine is called recursively on that pointer.
1034ff78bd2fSdrh **
1035ff78bd2fSdrh ** This routine is called on the Select structure that defines a
1036ff78bd2fSdrh ** VIEW in order to undo any bindings to tables.  This is necessary
1037ff78bd2fSdrh ** because those tables might be DROPed by a subsequent SQL command.
10385cf590c1Sdrh ** If the bindings are not removed, then the Select.pSrc->a[].pTab field
10395cf590c1Sdrh ** will be left pointing to a deallocated Table structure after the
10405cf590c1Sdrh ** DROP and a coredump will occur the next time the VIEW is used.
1041ff78bd2fSdrh */
1042ff78bd2fSdrh void sqliteSelectUnbind(Select *p){
1043ff78bd2fSdrh   int i;
1044ad3cab52Sdrh   SrcList *pSrc = p->pSrc;
1045ff78bd2fSdrh   Table *pTab;
1046ff78bd2fSdrh   if( p==0 ) return;
1047ad3cab52Sdrh   for(i=0; i<pSrc->nSrc; i++){
1048ff78bd2fSdrh     if( (pTab = pSrc->a[i].pTab)!=0 ){
1049ff78bd2fSdrh       if( pTab->isTransient ){
1050ff78bd2fSdrh         sqliteDeleteTable(0, pTab);
1051ff78bd2fSdrh       }
1052ff78bd2fSdrh       pSrc->a[i].pTab = 0;
1053ff78bd2fSdrh       if( pSrc->a[i].pSelect ){
1054ff78bd2fSdrh         sqliteSelectUnbind(pSrc->a[i].pSelect);
1055ff78bd2fSdrh       }
1056ff78bd2fSdrh     }
1057ff78bd2fSdrh   }
1058ff78bd2fSdrh }
1059ff78bd2fSdrh 
1060ff78bd2fSdrh /*
1061d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with
1062d8bc7086Sdrh ** columns in a result.  For each ORDER BY expression, the opcode of
1063967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of
1064d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable
1065d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter.
1066d8bc7086Sdrh **
1067d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first.  A match
1068d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT.
1069d8bc7086Sdrh **
1070d8bc7086Sdrh ** Any entry that does not match is flagged as an error.  The number
1071d8bc7086Sdrh ** of errors is returned.
1072fcb78a49Sdrh **
1073fcb78a49Sdrh ** This routine does NOT correctly initialize the Expr.dataType  field
1074fcb78a49Sdrh ** of the ORDER BY expressions.  The multiSelectSortOrder() routine
1075fcb78a49Sdrh ** must be called to do that after the individual select statements
1076fcb78a49Sdrh ** have all been analyzed.  This routine is unable to compute Expr.dataType
1077fcb78a49Sdrh ** because it must be called before the individual select statements
1078fcb78a49Sdrh ** have been analyzed.
1079d8bc7086Sdrh */
1080d8bc7086Sdrh static int matchOrderbyToColumn(
1081d8bc7086Sdrh   Parse *pParse,          /* A place to leave error messages */
1082d8bc7086Sdrh   Select *pSelect,        /* Match to result columns of this SELECT */
1083d8bc7086Sdrh   ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
1084e4de1febSdrh   int iTable,             /* Insert this value in iTable */
1085d8bc7086Sdrh   int mustComplete        /* If TRUE all ORDER BYs must match */
1086d8bc7086Sdrh ){
1087d8bc7086Sdrh   int nErr = 0;
1088d8bc7086Sdrh   int i, j;
1089d8bc7086Sdrh   ExprList *pEList;
1090d8bc7086Sdrh 
1091daffd0e5Sdrh   if( pSelect==0 || pOrderBy==0 ) return 1;
1092d8bc7086Sdrh   if( mustComplete ){
1093d8bc7086Sdrh     for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1094d8bc7086Sdrh   }
1095d8bc7086Sdrh   if( fillInColumnList(pParse, pSelect) ){
1096d8bc7086Sdrh     return 1;
1097d8bc7086Sdrh   }
1098d8bc7086Sdrh   if( pSelect->pPrior ){
109992cd52f5Sdrh     if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
110092cd52f5Sdrh       return 1;
110192cd52f5Sdrh     }
1102d8bc7086Sdrh   }
1103d8bc7086Sdrh   pEList = pSelect->pEList;
1104d8bc7086Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
1105d8bc7086Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
1106e4de1febSdrh     int iCol = -1;
1107d8bc7086Sdrh     if( pOrderBy->a[i].done ) continue;
1108e4de1febSdrh     if( sqliteExprIsInteger(pE, &iCol) ){
1109e4de1febSdrh       if( iCol<=0 || iCol>pEList->nExpr ){
1110da93d238Sdrh         sqliteErrorMsg(pParse,
1111da93d238Sdrh           "ORDER BY position %d should be between 1 and %d",
1112e4de1febSdrh           iCol, pEList->nExpr);
1113e4de1febSdrh         nErr++;
1114e4de1febSdrh         break;
1115e4de1febSdrh       }
1116fcb78a49Sdrh       if( !mustComplete ) continue;
1117e4de1febSdrh       iCol--;
1118e4de1febSdrh     }
1119e4de1febSdrh     for(j=0; iCol<0 && j<pEList->nExpr; j++){
11204cfa7934Sdrh       if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
1121a76b5dfcSdrh         char *zName, *zLabel;
1122a76b5dfcSdrh         zName = pEList->a[j].zName;
1123a76b5dfcSdrh         assert( pE->token.z );
1124a76b5dfcSdrh         zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
1125d8bc7086Sdrh         sqliteDequote(zLabel);
1126d8bc7086Sdrh         if( sqliteStrICmp(zName, zLabel)==0 ){
1127e4de1febSdrh           iCol = j;
1128d8bc7086Sdrh         }
11296e142f54Sdrh         sqliteFree(zLabel);
1130d8bc7086Sdrh       }
1131e4de1febSdrh       if( iCol<0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
1132e4de1febSdrh         iCol = j;
1133d8bc7086Sdrh       }
1134e4de1febSdrh     }
1135e4de1febSdrh     if( iCol>=0 ){
1136967e8b73Sdrh       pE->op = TK_COLUMN;
1137e4de1febSdrh       pE->iColumn = iCol;
1138d8bc7086Sdrh       pE->iTable = iTable;
1139d8bc7086Sdrh       pOrderBy->a[i].done = 1;
1140d8bc7086Sdrh     }
1141e4de1febSdrh     if( iCol<0 && mustComplete ){
1142da93d238Sdrh       sqliteErrorMsg(pParse,
1143da93d238Sdrh         "ORDER BY term number %d does not match any result column", i+1);
1144d8bc7086Sdrh       nErr++;
1145d8bc7086Sdrh       break;
1146d8bc7086Sdrh     }
1147d8bc7086Sdrh   }
1148d8bc7086Sdrh   return nErr;
1149d8bc7086Sdrh }
1150d8bc7086Sdrh 
1151d8bc7086Sdrh /*
1152d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1153d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1154d8bc7086Sdrh */
1155d8bc7086Sdrh Vdbe *sqliteGetVdbe(Parse *pParse){
1156d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1157d8bc7086Sdrh   if( v==0 ){
11584c504391Sdrh     v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
1159d8bc7086Sdrh   }
1160d8bc7086Sdrh   return v;
1161d8bc7086Sdrh }
1162d8bc7086Sdrh 
1163fcb78a49Sdrh /*
1164fcb78a49Sdrh ** This routine sets the Expr.dataType field on all elements of
1165fcb78a49Sdrh ** the pOrderBy expression list.  The pOrderBy list will have been
1166fcb78a49Sdrh ** set up by matchOrderbyToColumn().  Hence each expression has
1167fcb78a49Sdrh ** a TK_COLUMN as its root node.  The Expr.iColumn refers to a
1168fcb78a49Sdrh ** column in the result set.   The datatype is set to SQLITE_SO_TEXT
1169fcb78a49Sdrh ** if the corresponding column in p and every SELECT to the left of
1170fcb78a49Sdrh ** p has a datatype of SQLITE_SO_TEXT.  If the cooressponding column
1171fcb78a49Sdrh ** in p or any of the left SELECTs is SQLITE_SO_NUM, then the datatype
1172fcb78a49Sdrh ** of the order-by expression is set to SQLITE_SO_NUM.
1173fcb78a49Sdrh **
1174fcb78a49Sdrh ** Examples:
1175fcb78a49Sdrh **
1176e78e8284Sdrh **     CREATE TABLE one(a INTEGER, b TEXT);
1177e78e8284Sdrh **     CREATE TABLE two(c VARCHAR(5), d FLOAT);
1178e78e8284Sdrh **
1179e78e8284Sdrh **     SELECT b, b FROM one UNION SELECT d, c FROM two ORDER BY 1, 2;
1180e78e8284Sdrh **
1181e78e8284Sdrh ** The primary sort key will use SQLITE_SO_NUM because the "d" in
1182e78e8284Sdrh ** the second SELECT is numeric.  The 1st column of the first SELECT
1183e78e8284Sdrh ** is text but that does not matter because a numeric always overrides
1184e78e8284Sdrh ** a text.
1185e78e8284Sdrh **
1186e78e8284Sdrh ** The secondary key will use the SQLITE_SO_TEXT sort order because
1187e78e8284Sdrh ** both the (second) "b" in the first SELECT and the "c" in the second
1188e78e8284Sdrh ** SELECT have a datatype of text.
1189fcb78a49Sdrh */
1190fcb78a49Sdrh static void multiSelectSortOrder(Select *p, ExprList *pOrderBy){
1191fcb78a49Sdrh   int i;
1192fcb78a49Sdrh   ExprList *pEList;
1193fcb78a49Sdrh   if( pOrderBy==0 ) return;
1194fcb78a49Sdrh   if( p==0 ){
1195fcb78a49Sdrh     for(i=0; i<pOrderBy->nExpr; i++){
1196fcb78a49Sdrh       pOrderBy->a[i].pExpr->dataType = SQLITE_SO_TEXT;
1197fcb78a49Sdrh     }
1198fcb78a49Sdrh     return;
1199fcb78a49Sdrh   }
1200fcb78a49Sdrh   multiSelectSortOrder(p->pPrior, pOrderBy);
1201fcb78a49Sdrh   pEList = p->pEList;
1202fcb78a49Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
1203fcb78a49Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
1204fcb78a49Sdrh     if( pE->dataType==SQLITE_SO_NUM ) continue;
1205fcb78a49Sdrh     assert( pE->iColumn>=0 );
1206fcb78a49Sdrh     if( pEList->nExpr>pE->iColumn ){
1207fcb78a49Sdrh       pE->dataType = sqliteExprType(pEList->a[pE->iColumn].pExpr);
1208fcb78a49Sdrh     }
1209fcb78a49Sdrh   }
1210fcb78a49Sdrh }
1211d8bc7086Sdrh 
1212d8bc7086Sdrh /*
12137b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
12147b58daeaSdrh ** nLimit and nOffset fields.  nLimit and nOffset hold the integers
12157b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
12167b58daeaSdrh ** keywords.  Or that hold -1 and 0 if those keywords are omitted.
12177b58daeaSdrh ** iLimit and iOffset are the integer memory register numbers for
12187b58daeaSdrh ** counters used to compute the limit and offset.  If there is no
12197b58daeaSdrh ** limit and/or offset, then iLimit and iOffset are negative.
12207b58daeaSdrh **
12217b58daeaSdrh ** This routine changes the values if iLimit and iOffset only if
12227b58daeaSdrh ** a limit or offset is defined by nLimit and nOffset.  iLimit and
12237b58daeaSdrh ** iOffset should have been preset to appropriate default values
12247b58daeaSdrh ** (usually but not always -1) prior to calling this routine.
12257b58daeaSdrh ** Only if nLimit>=0 or nOffset>0 do the limit registers get
12267b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
12277b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
12287b58daeaSdrh ** SELECT statements.
12297b58daeaSdrh */
12307b58daeaSdrh static void computeLimitRegisters(Parse *pParse, Select *p){
12317b58daeaSdrh   /*
12327b58daeaSdrh   ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
12337b58daeaSdrh   ** all rows.  It is the same as no limit. If the comparision is
12347b58daeaSdrh   ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
12357b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
12367b58daeaSdrh   ** contraversy about what the correct behavior should be.
12377b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
12387b58daeaSdrh   ** no rows.
12397b58daeaSdrh   */
12407b58daeaSdrh   if( p->nLimit>=0 ){
12417b58daeaSdrh     int iMem = pParse->nMem++;
12427b58daeaSdrh     Vdbe *v = sqliteGetVdbe(pParse);
12437b58daeaSdrh     if( v==0 ) return;
12447b58daeaSdrh     sqliteVdbeAddOp(v, OP_Integer, -p->nLimit, 0);
12457b58daeaSdrh     sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
12467b58daeaSdrh     p->iLimit = iMem;
12477b58daeaSdrh   }
12487b58daeaSdrh   if( p->nOffset>0 ){
12497b58daeaSdrh     int iMem = pParse->nMem++;
12507b58daeaSdrh     Vdbe *v = sqliteGetVdbe(pParse);
12517b58daeaSdrh     if( v==0 ) return;
12527b58daeaSdrh     sqliteVdbeAddOp(v, OP_Integer, -p->nOffset, 0);
12537b58daeaSdrh     sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
12547b58daeaSdrh     p->iOffset = iMem;
12557b58daeaSdrh   }
12567b58daeaSdrh }
12577b58daeaSdrh 
12587b58daeaSdrh /*
125982c3d636Sdrh ** This routine is called to process a query that is really the union
126082c3d636Sdrh ** or intersection of two or more separate queries.
1261c926afbcSdrh **
1262e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1263e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1264e78e8284Sdrh ** in which case this routine will be called recursively.
1265e78e8284Sdrh **
1266e78e8284Sdrh ** The results of the total query are to be written into a destination
1267e78e8284Sdrh ** of type eDest with parameter iParm.
1268e78e8284Sdrh **
1269e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1270e78e8284Sdrh **
1271e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1272e78e8284Sdrh **
1273e78e8284Sdrh ** This statement is parsed up as follows:
1274e78e8284Sdrh **
1275e78e8284Sdrh **     SELECT c FROM t3
1276e78e8284Sdrh **      |
1277e78e8284Sdrh **      `----->  SELECT b FROM t2
1278e78e8284Sdrh **                |
12794b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1280e78e8284Sdrh **
1281e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1282e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1283e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1284e78e8284Sdrh **
1285e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1286e78e8284Sdrh ** individual selects always group from left to right.
128782c3d636Sdrh */
128882c3d636Sdrh static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
128910e5e3cfSdrh   int rc;             /* Success code from a subroutine */
129010e5e3cfSdrh   Select *pPrior;     /* Another SELECT immediately to our left */
129110e5e3cfSdrh   Vdbe *v;            /* Generate code to this VDBE */
129282c3d636Sdrh 
12937b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
12947b58daeaSdrh   ** the last SELECT in the series may have an ORDER BY or LIMIT.
129582c3d636Sdrh   */
1296daffd0e5Sdrh   if( p==0 || p->pPrior==0 ) return 1;
1297d8bc7086Sdrh   pPrior = p->pPrior;
1298d8bc7086Sdrh   if( pPrior->pOrderBy ){
1299da93d238Sdrh     sqliteErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1300da93d238Sdrh       selectOpName(p->op));
130182c3d636Sdrh     return 1;
130282c3d636Sdrh   }
13037b58daeaSdrh   if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
13047b58daeaSdrh     sqliteErrorMsg(pParse,"LIMIT clause should come after %s not before",
13057b58daeaSdrh       selectOpName(p->op));
13067b58daeaSdrh     return 1;
13077b58daeaSdrh   }
130882c3d636Sdrh 
1309d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
1310d8bc7086Sdrh   */
1311d8bc7086Sdrh   v = sqliteGetVdbe(pParse);
1312d8bc7086Sdrh   if( v==0 ) return 1;
1313d8bc7086Sdrh 
13141cc3d75fSdrh   /* Create the destination temporary table if necessary
13151cc3d75fSdrh   */
13161cc3d75fSdrh   if( eDest==SRT_TempTable ){
13171cc3d75fSdrh     sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
13181cc3d75fSdrh     eDest = SRT_Table;
13191cc3d75fSdrh   }
13201cc3d75fSdrh 
1321f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1322d8bc7086Sdrh   */
132382c3d636Sdrh   switch( p->op ){
1324f46f905aSdrh     case TK_ALL: {
1325f46f905aSdrh       if( p->pOrderBy==0 ){
13267b58daeaSdrh         pPrior->nLimit = p->nLimit;
13277b58daeaSdrh         pPrior->nOffset = p->nOffset;
1328f46f905aSdrh         rc = sqliteSelect(pParse, pPrior, eDest, iParm, 0, 0, 0);
1329f46f905aSdrh         if( rc ) return rc;
1330f46f905aSdrh         p->pPrior = 0;
13317b58daeaSdrh         p->iLimit = pPrior->iLimit;
13327b58daeaSdrh         p->iOffset = pPrior->iOffset;
13337b58daeaSdrh         p->nLimit = -1;
13347b58daeaSdrh         p->nOffset = 0;
1335f46f905aSdrh         rc = sqliteSelect(pParse, p, eDest, iParm, 0, 0, 0);
1336f46f905aSdrh         p->pPrior = pPrior;
1337f46f905aSdrh         if( rc ) return rc;
1338f46f905aSdrh         break;
1339f46f905aSdrh       }
1340f46f905aSdrh       /* For UNION ALL ... ORDER BY fall through to the next case */
1341f46f905aSdrh     }
134282c3d636Sdrh     case TK_EXCEPT:
134382c3d636Sdrh     case TK_UNION: {
1344d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1345d8bc7086Sdrh       int op;          /* One of the SRT_ operations to apply to self */
1346d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
13477b58daeaSdrh       int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
1348c926afbcSdrh       ExprList *pOrderBy;  /* The ORDER BY clause for the right SELECT */
134982c3d636Sdrh 
1350d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
13517b58daeaSdrh       if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
1352d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1353c926afbcSdrh         ** right.
1354d8bc7086Sdrh         */
135582c3d636Sdrh         unionTab = iParm;
135682c3d636Sdrh       }else{
1357d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1358d8bc7086Sdrh         ** intermediate results.
1359d8bc7086Sdrh         */
136082c3d636Sdrh         unionTab = pParse->nTab++;
1361d8bc7086Sdrh         if( p->pOrderBy
1362d8bc7086Sdrh         && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
1363d8bc7086Sdrh           return 1;
1364d8bc7086Sdrh         }
1365d8bc7086Sdrh         if( p->op!=TK_ALL ){
1366c6b52df3Sdrh           sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
136799fcd718Sdrh           sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
1368345fda3eSdrh         }else{
136999fcd718Sdrh           sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
137082c3d636Sdrh         }
1371d8bc7086Sdrh       }
1372d8bc7086Sdrh 
1373d8bc7086Sdrh       /* Code the SELECT statements to our left
1374d8bc7086Sdrh       */
1375832508b7Sdrh       rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
137682c3d636Sdrh       if( rc ) return rc;
1377d8bc7086Sdrh 
1378d8bc7086Sdrh       /* Code the current SELECT statement
1379d8bc7086Sdrh       */
1380d8bc7086Sdrh       switch( p->op ){
1381d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
1382d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
1383d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
1384d8bc7086Sdrh       }
138582c3d636Sdrh       p->pPrior = 0;
1386c926afbcSdrh       pOrderBy = p->pOrderBy;
1387c926afbcSdrh       p->pOrderBy = 0;
13887b58daeaSdrh       nLimit = p->nLimit;
13897b58daeaSdrh       p->nLimit = -1;
13907b58daeaSdrh       nOffset = p->nOffset;
13917b58daeaSdrh       p->nOffset = 0;
1392832508b7Sdrh       rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0);
139382c3d636Sdrh       p->pPrior = pPrior;
1394c926afbcSdrh       p->pOrderBy = pOrderBy;
13957b58daeaSdrh       p->nLimit = nLimit;
13967b58daeaSdrh       p->nOffset = nOffset;
139782c3d636Sdrh       if( rc ) return rc;
1398d8bc7086Sdrh 
1399d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1400d8bc7086Sdrh       ** it is that we currently need.
1401d8bc7086Sdrh       */
1402c926afbcSdrh       if( eDest!=priorOp || unionTab!=iParm ){
14036b56344dSdrh         int iCont, iBreak, iStart;
140482c3d636Sdrh         assert( p->pEList );
140541202ccaSdrh         if( eDest==SRT_Callback ){
14066a3ea0e6Sdrh           generateColumnNames(pParse, 0, p->pEList);
14076a3ea0e6Sdrh           generateColumnTypes(pParse, p->pSrc, p->pEList);
140841202ccaSdrh         }
140982c3d636Sdrh         iBreak = sqliteVdbeMakeLabel(v);
14106b56344dSdrh         iCont = sqliteVdbeMakeLabel(v);
14116b56344dSdrh         sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
14127b58daeaSdrh         computeLimitRegisters(pParse, p);
14136b56344dSdrh         iStart = sqliteVdbeCurrentAddr(v);
1414fcb78a49Sdrh         multiSelectSortOrder(p, p->pOrderBy);
141538640e15Sdrh         rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
1416d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
141782c3d636Sdrh                              iCont, iBreak);
141882c3d636Sdrh         if( rc ) return 1;
14196b56344dSdrh         sqliteVdbeResolveLabel(v, iCont);
14206b56344dSdrh         sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
142199fcd718Sdrh         sqliteVdbeResolveLabel(v, iBreak);
142299fcd718Sdrh         sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
1423d8bc7086Sdrh         if( p->pOrderBy ){
1424c926afbcSdrh           generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
1425d8bc7086Sdrh         }
142682c3d636Sdrh       }
142782c3d636Sdrh       break;
142882c3d636Sdrh     }
142982c3d636Sdrh     case TK_INTERSECT: {
143082c3d636Sdrh       int tab1, tab2;
14316b56344dSdrh       int iCont, iBreak, iStart;
14327b58daeaSdrh       int nLimit, nOffset;
143382c3d636Sdrh 
1434d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
14356206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
1436d8bc7086Sdrh       ** by allocating the tables we will need.
1437d8bc7086Sdrh       */
143882c3d636Sdrh       tab1 = pParse->nTab++;
143982c3d636Sdrh       tab2 = pParse->nTab++;
1440d8bc7086Sdrh       if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
1441d8bc7086Sdrh         return 1;
1442d8bc7086Sdrh       }
1443c6b52df3Sdrh       sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
144499fcd718Sdrh       sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
1445d8bc7086Sdrh 
1446d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1447d8bc7086Sdrh       */
1448832508b7Sdrh       rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
144982c3d636Sdrh       if( rc ) return rc;
1450d8bc7086Sdrh 
1451d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1452d8bc7086Sdrh       */
1453c6b52df3Sdrh       sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
145499fcd718Sdrh       sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
145582c3d636Sdrh       p->pPrior = 0;
14567b58daeaSdrh       nLimit = p->nLimit;
14577b58daeaSdrh       p->nLimit = -1;
14587b58daeaSdrh       nOffset = p->nOffset;
14597b58daeaSdrh       p->nOffset = 0;
1460832508b7Sdrh       rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0);
146182c3d636Sdrh       p->pPrior = pPrior;
14627b58daeaSdrh       p->nLimit = nLimit;
14637b58daeaSdrh       p->nOffset = nOffset;
146482c3d636Sdrh       if( rc ) return rc;
1465d8bc7086Sdrh 
1466d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1467d8bc7086Sdrh       ** tables.
1468d8bc7086Sdrh       */
146982c3d636Sdrh       assert( p->pEList );
147041202ccaSdrh       if( eDest==SRT_Callback ){
14716a3ea0e6Sdrh         generateColumnNames(pParse, 0, p->pEList);
14726a3ea0e6Sdrh         generateColumnTypes(pParse, p->pSrc, p->pEList);
147341202ccaSdrh       }
147482c3d636Sdrh       iBreak = sqliteVdbeMakeLabel(v);
14756b56344dSdrh       iCont = sqliteVdbeMakeLabel(v);
14766b56344dSdrh       sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
14777b58daeaSdrh       computeLimitRegisters(pParse, p);
14786b56344dSdrh       iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
147999fcd718Sdrh       sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
1480fcb78a49Sdrh       multiSelectSortOrder(p, p->pOrderBy);
148138640e15Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
1482d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
148382c3d636Sdrh                              iCont, iBreak);
148482c3d636Sdrh       if( rc ) return 1;
14856b56344dSdrh       sqliteVdbeResolveLabel(v, iCont);
14866b56344dSdrh       sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
148799fcd718Sdrh       sqliteVdbeResolveLabel(v, iBreak);
148899fcd718Sdrh       sqliteVdbeAddOp(v, OP_Close, tab2, 0);
148999fcd718Sdrh       sqliteVdbeAddOp(v, OP_Close, tab1, 0);
1490d8bc7086Sdrh       if( p->pOrderBy ){
1491c926afbcSdrh         generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
1492d8bc7086Sdrh       }
149382c3d636Sdrh       break;
149482c3d636Sdrh     }
149582c3d636Sdrh   }
149682c3d636Sdrh   assert( p->pEList && pPrior->pEList );
149782c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
1498da93d238Sdrh     sqliteErrorMsg(pParse, "SELECTs to the left and right of %s"
1499da93d238Sdrh       " do not have the same number of result columns", selectOpName(p->op));
150082c3d636Sdrh     return 1;
15012282792aSdrh   }
1502fcb78a49Sdrh 
1503fcb78a49Sdrh   /* Issue a null callback if that is what the user wants.
1504fcb78a49Sdrh   */
1505326dce74Sdrh   if( eDest==SRT_Callback &&
1506326dce74Sdrh     (pParse->useCallback==0 || (pParse->db->flags & SQLITE_NullCallback)!=0)
1507326dce74Sdrh   ){
1508fcb78a49Sdrh     sqliteVdbeAddOp(v, OP_NullCallback, p->pEList->nExpr, 0);
1509fcb78a49Sdrh   }
15102282792aSdrh   return 0;
15112282792aSdrh }
15122282792aSdrh 
15132282792aSdrh /*
1514832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
15156a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
151684e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
15176a3ea0e6Sdrh ** unchanged.)
1518832508b7Sdrh **
1519832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
1520832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
1521832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
1522832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
1523832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
1524832508b7Sdrh ** of the subquery rather the result set of the subquery.
1525832508b7Sdrh */
15266a3ea0e6Sdrh static void substExprList(ExprList*,int,ExprList*);  /* Forward Decl */
15276a3ea0e6Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
1528832508b7Sdrh   if( pExpr==0 ) return;
152984e59207Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable && pExpr->iColumn>=0 ){
1530832508b7Sdrh     Expr *pNew;
153184e59207Sdrh     assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1532832508b7Sdrh     assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1533832508b7Sdrh     pNew = pEList->a[pExpr->iColumn].pExpr;
1534832508b7Sdrh     assert( pNew!=0 );
1535832508b7Sdrh     pExpr->op = pNew->op;
1536fcb78a49Sdrh     pExpr->dataType = pNew->dataType;
1537d94a6698Sdrh     assert( pExpr->pLeft==0 );
1538832508b7Sdrh     pExpr->pLeft = sqliteExprDup(pNew->pLeft);
1539d94a6698Sdrh     assert( pExpr->pRight==0 );
1540832508b7Sdrh     pExpr->pRight = sqliteExprDup(pNew->pRight);
1541d94a6698Sdrh     assert( pExpr->pList==0 );
1542832508b7Sdrh     pExpr->pList = sqliteExprListDup(pNew->pList);
1543832508b7Sdrh     pExpr->iTable = pNew->iTable;
1544832508b7Sdrh     pExpr->iColumn = pNew->iColumn;
1545832508b7Sdrh     pExpr->iAgg = pNew->iAgg;
15464b59ab5eSdrh     sqliteTokenCopy(&pExpr->token, &pNew->token);
15476977fea8Sdrh     sqliteTokenCopy(&pExpr->span, &pNew->span);
1548832508b7Sdrh   }else{
15496a3ea0e6Sdrh     substExpr(pExpr->pLeft, iTable, pEList);
15506a3ea0e6Sdrh     substExpr(pExpr->pRight, iTable, pEList);
15516a3ea0e6Sdrh     substExprList(pExpr->pList, iTable, pEList);
1552832508b7Sdrh   }
1553832508b7Sdrh }
1554832508b7Sdrh static void
15556a3ea0e6Sdrh substExprList(ExprList *pList, int iTable, ExprList *pEList){
1556832508b7Sdrh   int i;
1557832508b7Sdrh   if( pList==0 ) return;
1558832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
15596a3ea0e6Sdrh     substExpr(pList->a[i].pExpr, iTable, pEList);
1560832508b7Sdrh   }
1561832508b7Sdrh }
1562832508b7Sdrh 
1563832508b7Sdrh /*
15641350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
15651350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
15661350b030Sdrh ** occurs.
15671350b030Sdrh **
15681350b030Sdrh ** To understand the concept of flattening, consider the following
15691350b030Sdrh ** query:
15701350b030Sdrh **
15711350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
15721350b030Sdrh **
15731350b030Sdrh ** The default way of implementing this query is to execute the
15741350b030Sdrh ** subquery first and store the results in a temporary table, then
15751350b030Sdrh ** run the outer query on that temporary table.  This requires two
15761350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
15771350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
1578832508b7Sdrh ** optimized.
15791350b030Sdrh **
1580832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
15811350b030Sdrh ** a single flat select, like this:
15821350b030Sdrh **
15831350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
15841350b030Sdrh **
15851350b030Sdrh ** The code generated for this simpification gives the same result
1586832508b7Sdrh ** but only has to scan the data once.  And because indices might
1587832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
1588832508b7Sdrh ** avoided.
15891350b030Sdrh **
1590832508b7Sdrh ** Flattening is only attempted if all of the following are true:
15911350b030Sdrh **
1592832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
15931350b030Sdrh **
1594832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
1595832508b7Sdrh **
15968af4d3acSdrh **   (3)  The subquery is not the right operand of a left outer join, or
15978af4d3acSdrh **        the subquery is not itself a join.  (Ticket #306)
1598832508b7Sdrh **
1599832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
1600832508b7Sdrh **
1601832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
1602832508b7Sdrh **        aggregates.
1603832508b7Sdrh **
1604832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
1605832508b7Sdrh **        DISTINCT.
1606832508b7Sdrh **
160708192d5fSdrh **   (7)  The subquery has a FROM clause.
160808192d5fSdrh **
1609df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
1610df199a25Sdrh **
1611df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
1612df199a25Sdrh **        aggregates.
1613df199a25Sdrh **
1614df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
1615df199a25Sdrh **        use LIMIT.
1616df199a25Sdrh **
1617174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
1618174b6195Sdrh **
16193fc673e6Sdrh **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
16203fc673e6Sdrh **        subquery has no WHERE clause.  (added by ticket #350)
16213fc673e6Sdrh **
1622832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
1623832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
1624832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1625832508b7Sdrh **
1626665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
1627832508b7Sdrh ** If flattening is attempted this routine returns 1.
1628832508b7Sdrh **
1629832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
1630832508b7Sdrh ** the subquery before this routine runs.
16311350b030Sdrh */
16328c74a8caSdrh static int flattenSubquery(
16338c74a8caSdrh   Parse *pParse,       /* The parsing context */
16348c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
16358c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
16368c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
16378c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
16388c74a8caSdrh ){
16390bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
1640ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
1641ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
16420bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
16436a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
1644832508b7Sdrh   int i;
1645832508b7Sdrh   Expr *pWhere;
16461350b030Sdrh 
1647832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
1648832508b7Sdrh   */
1649832508b7Sdrh   if( p==0 ) return 0;
1650832508b7Sdrh   pSrc = p->pSrc;
1651ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
1652832508b7Sdrh   pSub = pSrc->a[iFrom].pSelect;
1653832508b7Sdrh   assert( pSub!=0 );
1654832508b7Sdrh   if( isAgg && subqueryIsAgg ) return 0;
1655ad3cab52Sdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
1656832508b7Sdrh   pSubSrc = pSub->pSrc;
1657832508b7Sdrh   assert( pSubSrc );
1658c31c2eb8Sdrh   if( pSubSrc->nSrc==0 ) return 0;
1659df199a25Sdrh   if( (pSub->isDistinct || pSub->nLimit>=0) &&  (pSrc->nSrc>1 || isAgg) ){
1660df199a25Sdrh      return 0;
1661df199a25Sdrh   }
1662d11d382cSdrh   if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
1663174b6195Sdrh   if( p->pOrderBy && pSub->pOrderBy ) return 0;
1664832508b7Sdrh 
16658af4d3acSdrh   /* Restriction 3:  If the subquery is a join, make sure the subquery is
16668af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
16678af4d3acSdrh   ** is not allowed:
16688af4d3acSdrh   **
16698af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
16708af4d3acSdrh   **
16718af4d3acSdrh   ** If we flatten the above, we would get
16728af4d3acSdrh   **
16738af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
16748af4d3acSdrh   **
16758af4d3acSdrh   ** which is not at all the same thing.
16768af4d3acSdrh   */
16778af4d3acSdrh   if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
16788af4d3acSdrh     return 0;
16798af4d3acSdrh   }
16808af4d3acSdrh 
16813fc673e6Sdrh   /* Restriction 12:  If the subquery is the right operand of a left outer
16823fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
16833fc673e6Sdrh   ** An examples of why this is not allowed:
16843fc673e6Sdrh   **
16853fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
16863fc673e6Sdrh   **
16873fc673e6Sdrh   ** If we flatten the above, we would get
16883fc673e6Sdrh   **
16893fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
16903fc673e6Sdrh   **
16913fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
16923fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
16933fc673e6Sdrh   */
16943fc673e6Sdrh   if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
16953fc673e6Sdrh       && pSub->pWhere!=0 ){
16963fc673e6Sdrh     return 0;
16973fc673e6Sdrh   }
16983fc673e6Sdrh 
16990bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
170063eb5f29Sdrh   ** iFrom-th entry of the FROM clause in the outer query.
1701832508b7Sdrh   */
1702c31c2eb8Sdrh 
1703c31c2eb8Sdrh   /* Move all of the FROM elements of the subquery into the
1704c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
1705c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
1706c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
1707c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
1708c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
1709c31c2eb8Sdrh   ** elements we are now copying in.
1710c31c2eb8Sdrh   */
17116a3ea0e6Sdrh   iParent = pSrc->a[iFrom].iCursor;
1712c31c2eb8Sdrh   {
1713c31c2eb8Sdrh     int nSubSrc = pSubSrc->nSrc;
17148af4d3acSdrh     int jointype = pSrc->a[iFrom].jointype;
1715c31c2eb8Sdrh 
1716c31c2eb8Sdrh     if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
1717c31c2eb8Sdrh       sqliteDeleteTable(0, pSrc->a[iFrom].pTab);
1718c31c2eb8Sdrh     }
1719f26e09c8Sdrh     sqliteFree(pSrc->a[iFrom].zDatabase);
1720c31c2eb8Sdrh     sqliteFree(pSrc->a[iFrom].zName);
1721c31c2eb8Sdrh     sqliteFree(pSrc->a[iFrom].zAlias);
1722c31c2eb8Sdrh     if( nSubSrc>1 ){
1723c31c2eb8Sdrh       int extra = nSubSrc - 1;
1724c31c2eb8Sdrh       for(i=1; i<nSubSrc; i++){
1725c31c2eb8Sdrh         pSrc = sqliteSrcListAppend(pSrc, 0, 0);
1726c31c2eb8Sdrh       }
1727c31c2eb8Sdrh       p->pSrc = pSrc;
1728c31c2eb8Sdrh       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1729c31c2eb8Sdrh         pSrc->a[i] = pSrc->a[i-extra];
1730c31c2eb8Sdrh       }
1731c31c2eb8Sdrh     }
1732c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
1733c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
1734c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1735c31c2eb8Sdrh     }
17368af4d3acSdrh     pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
1737c31c2eb8Sdrh   }
1738c31c2eb8Sdrh 
1739c31c2eb8Sdrh   /* Now begin substituting subquery result set expressions for
1740c31c2eb8Sdrh   ** references to the iParent in the outer query.
1741c31c2eb8Sdrh   **
1742c31c2eb8Sdrh   ** Example:
1743c31c2eb8Sdrh   **
1744c31c2eb8Sdrh   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1745c31c2eb8Sdrh   **   \                     \_____________ subquery __________/          /
1746c31c2eb8Sdrh   **    \_____________________ outer query ______________________________/
1747c31c2eb8Sdrh   **
1748c31c2eb8Sdrh   ** We look at every expression in the outer query and every place we see
1749c31c2eb8Sdrh   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1750c31c2eb8Sdrh   */
17516a3ea0e6Sdrh   substExprList(p->pEList, iParent, pSub->pEList);
1752832508b7Sdrh   pList = p->pEList;
1753832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
17546977fea8Sdrh     Expr *pExpr;
17556977fea8Sdrh     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
17566977fea8Sdrh       pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
1757832508b7Sdrh     }
1758832508b7Sdrh   }
17591b2e0329Sdrh   if( isAgg ){
17606a3ea0e6Sdrh     substExprList(p->pGroupBy, iParent, pSub->pEList);
17616a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
17621b2e0329Sdrh   }
1763174b6195Sdrh   if( pSub->pOrderBy ){
1764174b6195Sdrh     assert( p->pOrderBy==0 );
1765174b6195Sdrh     p->pOrderBy = pSub->pOrderBy;
1766174b6195Sdrh     pSub->pOrderBy = 0;
1767174b6195Sdrh   }else if( p->pOrderBy ){
17686a3ea0e6Sdrh     substExprList(p->pOrderBy, iParent, pSub->pEList);
1769174b6195Sdrh   }
1770832508b7Sdrh   if( pSub->pWhere ){
1771832508b7Sdrh     pWhere = sqliteExprDup(pSub->pWhere);
1772832508b7Sdrh   }else{
1773832508b7Sdrh     pWhere = 0;
1774832508b7Sdrh   }
1775832508b7Sdrh   if( subqueryIsAgg ){
1776832508b7Sdrh     assert( p->pHaving==0 );
17771b2e0329Sdrh     p->pHaving = p->pWhere;
17781b2e0329Sdrh     p->pWhere = pWhere;
17796a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
17801b2e0329Sdrh     if( pSub->pHaving ){
17811b2e0329Sdrh       Expr *pHaving = sqliteExprDup(pSub->pHaving);
17821b2e0329Sdrh       if( p->pHaving ){
17831b2e0329Sdrh         p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0);
17841b2e0329Sdrh       }else{
17851b2e0329Sdrh         p->pHaving = pHaving;
17861b2e0329Sdrh       }
17871b2e0329Sdrh     }
17881b2e0329Sdrh     assert( p->pGroupBy==0 );
17891b2e0329Sdrh     p->pGroupBy = sqliteExprListDup(pSub->pGroupBy);
1790832508b7Sdrh   }else if( p->pWhere==0 ){
1791832508b7Sdrh     p->pWhere = pWhere;
1792832508b7Sdrh   }else{
17936a3ea0e6Sdrh     substExpr(p->pWhere, iParent, pSub->pEList);
1794832508b7Sdrh     if( pWhere ){
1795832508b7Sdrh       p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0);
1796832508b7Sdrh     }
1797832508b7Sdrh   }
1798c31c2eb8Sdrh 
1799c31c2eb8Sdrh   /* The flattened query is distinct if either the inner or the
1800c31c2eb8Sdrh   ** outer query is distinct.
1801c31c2eb8Sdrh   */
1802832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
18038c74a8caSdrh 
1804c31c2eb8Sdrh   /* Transfer the limit expression from the subquery to the outer
1805c31c2eb8Sdrh   ** query.
1806c31c2eb8Sdrh   */
1807df199a25Sdrh   if( pSub->nLimit>=0 ){
1808df199a25Sdrh     if( p->nLimit<0 ){
1809df199a25Sdrh       p->nLimit = pSub->nLimit;
1810df199a25Sdrh     }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1811df199a25Sdrh       p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1812df199a25Sdrh     }
1813df199a25Sdrh   }
1814df199a25Sdrh   p->nOffset += pSub->nOffset;
18158c74a8caSdrh 
1816c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
1817c31c2eb8Sdrh   ** success.
1818c31c2eb8Sdrh   */
1819832508b7Sdrh   sqliteSelectDelete(pSub);
1820832508b7Sdrh   return 1;
18211350b030Sdrh }
18221350b030Sdrh 
18231350b030Sdrh /*
18249562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it
18259562b551Sdrh ** is a simple min() or max() query.  If it is and this query can be
18269562b551Sdrh ** satisfied using a single seek to the beginning or end of an index,
1827e78e8284Sdrh ** then generate the code for this SELECT and return 1.  If this is not a
18289562b551Sdrh ** simple min() or max() query, then return 0;
18299562b551Sdrh **
18309562b551Sdrh ** A simply min() or max() query looks like this:
18319562b551Sdrh **
18329562b551Sdrh **    SELECT min(a) FROM table;
18339562b551Sdrh **    SELECT max(a) FROM table;
18349562b551Sdrh **
18359562b551Sdrh ** The query may have only a single table in its FROM argument.  There
18369562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
18379562b551Sdrh ** be the min() or max() of a single column of the table.  The column
18389562b551Sdrh ** in the min() or max() function must be indexed.
18399562b551Sdrh **
18409562b551Sdrh ** The parameters to this routine are the same as for sqliteSelect().
18419562b551Sdrh ** See the header comment on that routine for additional information.
18429562b551Sdrh */
18439562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
18449562b551Sdrh   Expr *pExpr;
18459562b551Sdrh   int iCol;
18469562b551Sdrh   Table *pTab;
18479562b551Sdrh   Index *pIdx;
18489562b551Sdrh   int base;
18499562b551Sdrh   Vdbe *v;
18509562b551Sdrh   int seekOp;
18519562b551Sdrh   int cont;
18529562b551Sdrh   ExprList eList;
18539562b551Sdrh   struct ExprList_item eListItem;
18549562b551Sdrh 
18559562b551Sdrh   /* Check to see if this query is a simple min() or max() query.  Return
18569562b551Sdrh   ** zero if it is  not.
18579562b551Sdrh   */
18589562b551Sdrh   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
1859ad3cab52Sdrh   if( p->pSrc->nSrc!=1 ) return 0;
18609562b551Sdrh   if( p->pEList->nExpr!=1 ) return 0;
18619562b551Sdrh   pExpr = p->pEList->a[0].pExpr;
18629562b551Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
18639562b551Sdrh   if( pExpr->pList==0 || pExpr->pList->nExpr!=1 ) return 0;
18646977fea8Sdrh   if( pExpr->token.n!=3 ) return 0;
18650bce8354Sdrh   if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){
18660bce8354Sdrh     seekOp = OP_Rewind;
18670bce8354Sdrh   }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){
18680bce8354Sdrh     seekOp = OP_Last;
18690bce8354Sdrh   }else{
18700bce8354Sdrh     return 0;
18710bce8354Sdrh   }
18729562b551Sdrh   pExpr = pExpr->pList->a[0].pExpr;
18739562b551Sdrh   if( pExpr->op!=TK_COLUMN ) return 0;
18749562b551Sdrh   iCol = pExpr->iColumn;
18759562b551Sdrh   pTab = p->pSrc->a[0].pTab;
18769562b551Sdrh 
18779562b551Sdrh   /* If we get to here, it means the query is of the correct form.
187817f71934Sdrh   ** Check to make sure we have an index and make pIdx point to the
187917f71934Sdrh   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
188017f71934Sdrh   ** key column, no index is necessary so set pIdx to NULL.  If no
188117f71934Sdrh   ** usable index is found, return 0.
18829562b551Sdrh   */
18839562b551Sdrh   if( iCol<0 ){
18849562b551Sdrh     pIdx = 0;
18859562b551Sdrh   }else{
18869562b551Sdrh     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
18879562b551Sdrh       assert( pIdx->nColumn>=1 );
18889562b551Sdrh       if( pIdx->aiColumn[0]==iCol ) break;
18899562b551Sdrh     }
18909562b551Sdrh     if( pIdx==0 ) return 0;
18919562b551Sdrh   }
18929562b551Sdrh 
1893e5f50722Sdrh   /* Identify column types if we will be using the callback.  This
18949562b551Sdrh   ** step is skipped if the output is going to a table or a memory cell.
1895e5f50722Sdrh   ** The column names have already been generated in the calling function.
18969562b551Sdrh   */
18979562b551Sdrh   v = sqliteGetVdbe(pParse);
18989562b551Sdrh   if( v==0 ) return 0;
18999562b551Sdrh   if( eDest==SRT_Callback ){
19006a3ea0e6Sdrh     generateColumnTypes(pParse, p->pSrc, p->pEList);
19019562b551Sdrh   }
19029562b551Sdrh 
19030c37e630Sdrh   /* If the output is destined for a temporary table, open that table.
19040c37e630Sdrh   */
19050c37e630Sdrh   if( eDest==SRT_TempTable ){
19060c37e630Sdrh     sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
19070c37e630Sdrh   }
19080c37e630Sdrh 
190917f71934Sdrh   /* Generating code to find the min or the max.  Basically all we have
191017f71934Sdrh   ** to do is find the first or the last entry in the chosen index.  If
191117f71934Sdrh   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
191217f71934Sdrh   ** or last entry in the main table.
19139562b551Sdrh   */
19148bf8dc92Sdrh   sqliteCodeVerifySchema(pParse, pTab->iDb);
19156a3ea0e6Sdrh   base = p->pSrc->a[0].iCursor;
19167b58daeaSdrh   computeLimitRegisters(pParse, p);
1917d24cc427Sdrh   sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
1918001bbcbbSdrh   sqliteVdbeAddOp(v, OP_OpenRead, base, pTab->tnum);
19195cf8e8c7Sdrh   sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
1920d4d595f9Sdrh   cont = sqliteVdbeMakeLabel(v);
19219562b551Sdrh   if( pIdx==0 ){
19229562b551Sdrh     sqliteVdbeAddOp(v, seekOp, base, 0);
19239562b551Sdrh   }else{
1924d24cc427Sdrh     sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
1925001bbcbbSdrh     sqliteVdbeAddOp(v, OP_OpenRead, base+1, pIdx->tnum);
19265cf8e8c7Sdrh     sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
19279562b551Sdrh     sqliteVdbeAddOp(v, seekOp, base+1, 0);
19289562b551Sdrh     sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
19299562b551Sdrh     sqliteVdbeAddOp(v, OP_Close, base+1, 0);
19309562b551Sdrh     sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
19319562b551Sdrh   }
19325cf8e8c7Sdrh   eList.nExpr = 1;
19335cf8e8c7Sdrh   memset(&eListItem, 0, sizeof(eListItem));
19345cf8e8c7Sdrh   eList.a = &eListItem;
19355cf8e8c7Sdrh   eList.a[0].pExpr = pExpr;
193638640e15Sdrh   selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont);
19379562b551Sdrh   sqliteVdbeResolveLabel(v, cont);
19389562b551Sdrh   sqliteVdbeAddOp(v, OP_Close, base, 0);
19399562b551Sdrh   return 1;
19409562b551Sdrh }
19419562b551Sdrh 
19429562b551Sdrh /*
19439bb61fe7Sdrh ** Generate code for the given SELECT statement.
19449bb61fe7Sdrh **
1945fef5208cSdrh ** The results are distributed in various ways depending on the
1946fef5208cSdrh ** value of eDest and iParm.
1947fef5208cSdrh **
1948fef5208cSdrh **     eDest Value       Result
1949fef5208cSdrh **     ------------    -------------------------------------------
1950fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
1951fef5208cSdrh **
1952fef5208cSdrh **     SRT_Mem         Store first result in memory cell iParm
1953fef5208cSdrh **
1954fef5208cSdrh **     SRT_Set         Store results as keys of a table with cursor iParm
1955fef5208cSdrh **
195682c3d636Sdrh **     SRT_Union       Store results as a key in a temporary table iParm
195782c3d636Sdrh **
19584b11c6d3Sjplyon **     SRT_Except      Remove results from the temporary table iParm.
1959c4a3c779Sdrh **
1960c4a3c779Sdrh **     SRT_Table       Store results in temporary table iParm
19619bb61fe7Sdrh **
1962e78e8284Sdrh ** The table above is incomplete.  Additional eDist value have be added
1963e78e8284Sdrh ** since this comment was written.  See the selectInnerLoop() function for
1964e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings.
1965e78e8284Sdrh **
19669bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
19679bb61fe7Sdrh ** encountered, then an appropriate error message is left in
19689bb61fe7Sdrh ** pParse->zErrMsg.
19699bb61fe7Sdrh **
19709bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
19719bb61fe7Sdrh ** calling function needs to do that.
19721b2e0329Sdrh **
19731b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
19741b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
19751b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
19761b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
19771b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
19781b2e0329Sdrh ** can be changed.
1979e78e8284Sdrh **
1980e78e8284Sdrh ** Example 1:   The meaning of the pParent parameter.
1981e78e8284Sdrh **
1982e78e8284Sdrh **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
1983e78e8284Sdrh **    \                      \_______ subquery _______/        /
1984e78e8284Sdrh **     \                                                      /
1985e78e8284Sdrh **      \____________________ outer query ___________________/
1986e78e8284Sdrh **
1987e78e8284Sdrh ** This routine is called for the outer query first.   For that call,
1988e78e8284Sdrh ** pParent will be NULL.  During the processing of the outer query, this
1989e78e8284Sdrh ** routine is called recursively to handle the subquery.  For the recursive
1990e78e8284Sdrh ** call, pParent will point to the outer query.  Because the subquery is
1991e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will
1992e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.)
19939bb61fe7Sdrh */
19949bb61fe7Sdrh int sqliteSelect(
1995cce7d176Sdrh   Parse *pParse,         /* The parser context */
19969bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
1997e78e8284Sdrh   int eDest,             /* How to dispose of the results */
1998e78e8284Sdrh   int iParm,             /* A parameter used by the eDest disposal method */
1999832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
2000832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
20011b2e0329Sdrh   int *pParentAgg        /* True if pParent uses aggregate functions */
2002cce7d176Sdrh ){
2003d8bc7086Sdrh   int i;
2004cce7d176Sdrh   WhereInfo *pWInfo;
2005cce7d176Sdrh   Vdbe *v;
2006cce7d176Sdrh   int isAgg = 0;         /* True for select lists like "count(*)" */
2007a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
2008ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
20099bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
20109bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
20112282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
20122282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
201319a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
201419a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
20151d83f052Sdrh   int rc = 1;            /* Value to return from this function */
20169bb61fe7Sdrh 
2017daffd0e5Sdrh   if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
2018e22a334bSdrh   if( sqliteAuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
2019daffd0e5Sdrh 
202082c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
202182c3d636Sdrh   */
202282c3d636Sdrh   if( p->pPrior ){
202382c3d636Sdrh     return multiSelect(pParse, p, eDest, iParm);
202482c3d636Sdrh   }
202582c3d636Sdrh 
202682c3d636Sdrh   /* Make local copies of the parameters for this query.
202782c3d636Sdrh   */
20289bb61fe7Sdrh   pTabList = p->pSrc;
20299bb61fe7Sdrh   pWhere = p->pWhere;
20309bb61fe7Sdrh   pOrderBy = p->pOrderBy;
20312282792aSdrh   pGroupBy = p->pGroupBy;
20322282792aSdrh   pHaving = p->pHaving;
203319a775c2Sdrh   isDistinct = p->isDistinct;
20349bb61fe7Sdrh 
20356a3ea0e6Sdrh   /* Allocate VDBE cursors for each table in the FROM clause
203610e5e3cfSdrh   */
20376a3ea0e6Sdrh   sqliteSrcListAssignCursors(pParse, pTabList);
203810e5e3cfSdrh 
20399bb61fe7Sdrh   /*
20409bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
20419bb61fe7Sdrh   ** errors before this routine starts.
20429bb61fe7Sdrh   */
20431d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
2044cce7d176Sdrh 
2045e78e8284Sdrh   /* Expand any "*" terms in the result set.  (For example the "*" in
2046e78e8284Sdrh   ** "SELECT * FROM t1")  The fillInColumnlist() routine also does some
2047e78e8284Sdrh   ** other housekeeping - see the header comment for details.
2048cce7d176Sdrh   */
2049d8bc7086Sdrh   if( fillInColumnList(pParse, p) ){
20501d83f052Sdrh     goto select_end;
2051cce7d176Sdrh   }
2052ad2d8307Sdrh   pWhere = p->pWhere;
2053d8bc7086Sdrh   pEList = p->pEList;
20541d83f052Sdrh   if( pEList==0 ) goto select_end;
2055cce7d176Sdrh 
20562282792aSdrh   /* If writing to memory or generating a set
20572282792aSdrh   ** only a single column may be output.
205819a775c2Sdrh   */
2059fef5208cSdrh   if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
2060da93d238Sdrh     sqliteErrorMsg(pParse, "only a single result allowed for "
2061da93d238Sdrh        "a SELECT that is part of an expression");
20621d83f052Sdrh     goto select_end;
206319a775c2Sdrh   }
206419a775c2Sdrh 
2065c926afbcSdrh   /* ORDER BY is ignored for some destinations.
20662282792aSdrh   */
2067c926afbcSdrh   switch( eDest ){
2068c926afbcSdrh     case SRT_Union:
2069c926afbcSdrh     case SRT_Except:
2070c926afbcSdrh     case SRT_Discard:
2071acd4c695Sdrh       pOrderBy = 0;
2072c926afbcSdrh       break;
2073c926afbcSdrh     default:
2074c926afbcSdrh       break;
20752282792aSdrh   }
20762282792aSdrh 
207710e5e3cfSdrh   /* At this point, we should have allocated all the cursors that we
2078832508b7Sdrh   ** need to handle subquerys and temporary tables.
207910e5e3cfSdrh   **
2080967e8b73Sdrh   ** Resolve the column names and do a semantics check on all the expressions.
20812282792aSdrh   */
20824794b980Sdrh   for(i=0; i<pEList->nExpr; i++){
20836a3ea0e6Sdrh     if( sqliteExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
20841d83f052Sdrh       goto select_end;
2085cce7d176Sdrh     }
20862282792aSdrh     if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
20871d83f052Sdrh       goto select_end;
2088cce7d176Sdrh     }
2089cce7d176Sdrh   }
2090cce7d176Sdrh   if( pWhere ){
20916a3ea0e6Sdrh     if( sqliteExprResolveIds(pParse, pTabList, pEList, pWhere) ){
20921d83f052Sdrh       goto select_end;
2093cce7d176Sdrh     }
2094cce7d176Sdrh     if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
20951d83f052Sdrh       goto select_end;
2096cce7d176Sdrh     }
2097cce7d176Sdrh   }
2098c66c5a26Sdrh   if( pHaving ){
2099c66c5a26Sdrh     if( pGroupBy==0 ){
2100da93d238Sdrh       sqliteErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2101c66c5a26Sdrh       goto select_end;
2102c66c5a26Sdrh     }
21036a3ea0e6Sdrh     if( sqliteExprResolveIds(pParse, pTabList, pEList, pHaving) ){
2104c66c5a26Sdrh       goto select_end;
2105c66c5a26Sdrh     }
2106c66c5a26Sdrh     if( sqliteExprCheck(pParse, pHaving, 1, &isAgg) ){
2107c66c5a26Sdrh       goto select_end;
2108c66c5a26Sdrh     }
2109c66c5a26Sdrh   }
2110cce7d176Sdrh   if( pOrderBy ){
2111cce7d176Sdrh     for(i=0; i<pOrderBy->nExpr; i++){
2112e4de1febSdrh       int iCol;
211388eee38aSdrh       Expr *pE = pOrderBy->a[i].pExpr;
211488eee38aSdrh       if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
211588eee38aSdrh         sqliteExprDelete(pE);
211688eee38aSdrh         pE = pOrderBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
211788eee38aSdrh       }
21186a3ea0e6Sdrh       if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){
211988eee38aSdrh         goto select_end;
212088eee38aSdrh       }
212188eee38aSdrh       if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
212288eee38aSdrh         goto select_end;
212388eee38aSdrh       }
212488eee38aSdrh       if( sqliteExprIsConstant(pE) ){
2125e4de1febSdrh         if( sqliteExprIsInteger(pE, &iCol)==0 ){
2126da93d238Sdrh           sqliteErrorMsg(pParse,
2127da93d238Sdrh              "ORDER BY terms must not be non-integer constants");
21281d83f052Sdrh           goto select_end;
2129e4de1febSdrh         }else if( iCol<=0 || iCol>pEList->nExpr ){
2130da93d238Sdrh           sqliteErrorMsg(pParse,
2131da93d238Sdrh              "ORDER BY column number %d out of range - should be "
2132e4de1febSdrh              "between 1 and %d", iCol, pEList->nExpr);
2133e4de1febSdrh           goto select_end;
2134e4de1febSdrh         }
2135cce7d176Sdrh       }
2136cce7d176Sdrh     }
2137cce7d176Sdrh   }
21382282792aSdrh   if( pGroupBy ){
21392282792aSdrh     for(i=0; i<pGroupBy->nExpr; i++){
214088eee38aSdrh       int iCol;
21412282792aSdrh       Expr *pE = pGroupBy->a[i].pExpr;
214288eee38aSdrh       if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
214388eee38aSdrh         sqliteExprDelete(pE);
214488eee38aSdrh         pE = pGroupBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
21459208643dSdrh       }
21466a3ea0e6Sdrh       if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){
21471d83f052Sdrh         goto select_end;
21482282792aSdrh       }
21492282792aSdrh       if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
21501d83f052Sdrh         goto select_end;
21512282792aSdrh       }
215288eee38aSdrh       if( sqliteExprIsConstant(pE) ){
215388eee38aSdrh         if( sqliteExprIsInteger(pE, &iCol)==0 ){
2154da93d238Sdrh           sqliteErrorMsg(pParse,
2155da93d238Sdrh             "GROUP BY terms must not be non-integer constants");
215688eee38aSdrh           goto select_end;
215788eee38aSdrh         }else if( iCol<=0 || iCol>pEList->nExpr ){
2158da93d238Sdrh           sqliteErrorMsg(pParse,
2159da93d238Sdrh              "GROUP BY column number %d out of range - should be "
216088eee38aSdrh              "between 1 and %d", iCol, pEList->nExpr);
216188eee38aSdrh           goto select_end;
216288eee38aSdrh         }
216388eee38aSdrh       }
21642282792aSdrh     }
21652282792aSdrh   }
2166cce7d176Sdrh 
2167d820cb1bSdrh   /* Begin generating code.
2168d820cb1bSdrh   */
2169d820cb1bSdrh   v = sqliteGetVdbe(pParse);
2170d820cb1bSdrh   if( v==0 ) goto select_end;
2171d820cb1bSdrh 
2172e78e8284Sdrh   /* Identify column names if we will be using them in a callback.  This
2173e78e8284Sdrh   ** step is skipped if the output is going to some other destination.
21740bb28106Sdrh   */
21750bb28106Sdrh   if( eDest==SRT_Callback ){
21766a3ea0e6Sdrh     generateColumnNames(pParse, pTabList, pEList);
21770bb28106Sdrh   }
21780bb28106Sdrh 
2179e5f50722Sdrh   /* Check for the special case of a min() or max() function by itself
2180e5f50722Sdrh   ** in the result set.
2181e5f50722Sdrh   */
2182e5f50722Sdrh   if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2183e5f50722Sdrh     rc = 0;
2184e5f50722Sdrh     goto select_end;
2185e5f50722Sdrh   }
2186e5f50722Sdrh 
2187d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
2188d820cb1bSdrh   */
2189ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
21905cf590c1Sdrh     const char *zSavedAuthContext;
2191c31c2eb8Sdrh     int needRestoreContext;
2192c31c2eb8Sdrh 
2193a76b5dfcSdrh     if( pTabList->a[i].pSelect==0 ) continue;
21945cf590c1Sdrh     if( pTabList->a[i].zName!=0 ){
21955cf590c1Sdrh       zSavedAuthContext = pParse->zAuthContext;
21965cf590c1Sdrh       pParse->zAuthContext = pTabList->a[i].zName;
2197c31c2eb8Sdrh       needRestoreContext = 1;
2198c31c2eb8Sdrh     }else{
2199c31c2eb8Sdrh       needRestoreContext = 0;
22005cf590c1Sdrh     }
22016a3ea0e6Sdrh     sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable,
22026a3ea0e6Sdrh                  pTabList->a[i].iCursor, p, i, &isAgg);
2203c31c2eb8Sdrh     if( needRestoreContext ){
22045cf590c1Sdrh       pParse->zAuthContext = zSavedAuthContext;
22055cf590c1Sdrh     }
2206832508b7Sdrh     pTabList = p->pSrc;
2207832508b7Sdrh     pWhere = p->pWhere;
2208c31c2eb8Sdrh     if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
2209832508b7Sdrh       pOrderBy = p->pOrderBy;
2210acd4c695Sdrh     }
2211832508b7Sdrh     pGroupBy = p->pGroupBy;
2212832508b7Sdrh     pHaving = p->pHaving;
2213832508b7Sdrh     isDistinct = p->isDistinct;
22141b2e0329Sdrh   }
22151b2e0329Sdrh 
22161b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
22171b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
22181b2e0329Sdrh   */
22191b2e0329Sdrh   if( pParent && pParentAgg &&
22208c74a8caSdrh       flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
22211b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
22221b2e0329Sdrh     return rc;
22231b2e0329Sdrh   }
2224832508b7Sdrh 
22257b58daeaSdrh   /* Set the limiter.
22267b58daeaSdrh   */
22277b58daeaSdrh   computeLimitRegisters(pParse, p);
22287b58daeaSdrh 
2229e78e8284Sdrh   /* Identify column types if we will be using a callback.  This
2230e78e8284Sdrh   ** step is skipped if the output is going to a destination other
2231e78e8284Sdrh   ** than a callback.
2232e5f50722Sdrh   **
2233e5f50722Sdrh   ** We have to do this separately from the creation of column names
2234e5f50722Sdrh   ** above because if the pTabList contains views then they will not
2235e5f50722Sdrh   ** have been resolved and we will not know the column types until
2236e5f50722Sdrh   ** now.
2237fcb78a49Sdrh   */
2238fcb78a49Sdrh   if( eDest==SRT_Callback ){
22396a3ea0e6Sdrh     generateColumnTypes(pParse, pTabList, pEList);
2240fcb78a49Sdrh   }
2241fcb78a49Sdrh 
22422d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
22432d0794e3Sdrh   */
22442d0794e3Sdrh   if( eDest==SRT_TempTable ){
22452d0794e3Sdrh     sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
22462d0794e3Sdrh   }
22472d0794e3Sdrh 
22482282792aSdrh   /* Do an analysis of aggregate expressions.
2249efb7251dSdrh   */
2250d820cb1bSdrh   sqliteAggregateInfoReset(pParse);
2251bb999ef6Sdrh   if( isAgg || pGroupBy ){
22520bce8354Sdrh     assert( pParse->nAgg==0 );
2253bb999ef6Sdrh     isAgg = 1;
22542282792aSdrh     for(i=0; i<pEList->nExpr; i++){
22552282792aSdrh       if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
22561d83f052Sdrh         goto select_end;
22572282792aSdrh       }
22582282792aSdrh     }
22592282792aSdrh     if( pGroupBy ){
22602282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
22612282792aSdrh         if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
22621d83f052Sdrh           goto select_end;
22632282792aSdrh         }
22642282792aSdrh       }
22652282792aSdrh     }
22662282792aSdrh     if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
22671d83f052Sdrh       goto select_end;
22682282792aSdrh     }
2269191b690eSdrh     if( pOrderBy ){
2270191b690eSdrh       for(i=0; i<pOrderBy->nExpr; i++){
2271191b690eSdrh         if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
22721d83f052Sdrh           goto select_end;
2273191b690eSdrh         }
2274191b690eSdrh       }
2275191b690eSdrh     }
2276efb7251dSdrh   }
2277efb7251dSdrh 
22782282792aSdrh   /* Reset the aggregator
2279cce7d176Sdrh   */
2280cce7d176Sdrh   if( isAgg ){
228199fcd718Sdrh     sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
2282e5095355Sdrh     for(i=0; i<pParse->nAgg; i++){
22830bce8354Sdrh       FuncDef *pFunc;
22840bce8354Sdrh       if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
22851350b030Sdrh         sqliteVdbeAddOp(v, OP_AggInit, 0, i);
22860bce8354Sdrh         sqliteVdbeChangeP3(v, -1, (char*)pFunc, P3_POINTER);
2287e5095355Sdrh       }
2288e5095355Sdrh     }
22891bee3d7bSdrh     if( pGroupBy==0 ){
22901bee3d7bSdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
22911bee3d7bSdrh       sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
22921bee3d7bSdrh     }
2293cce7d176Sdrh   }
2294cce7d176Sdrh 
229519a775c2Sdrh   /* Initialize the memory cell to NULL
229619a775c2Sdrh   */
2297fef5208cSdrh   if( eDest==SRT_Mem ){
229899fcd718Sdrh     sqliteVdbeAddOp(v, OP_String, 0, 0);
22998721ce4aSdrh     sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
230019a775c2Sdrh   }
230119a775c2Sdrh 
2302832508b7Sdrh   /* Open a temporary table to use for the distinct set.
2303cce7d176Sdrh   */
230419a775c2Sdrh   if( isDistinct ){
2305832508b7Sdrh     distinct = pParse->nTab++;
2306c6b52df3Sdrh     sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
2307832508b7Sdrh   }else{
2308832508b7Sdrh     distinct = -1;
2309efb7251dSdrh   }
2310832508b7Sdrh 
2311832508b7Sdrh   /* Begin the database scan
2312832508b7Sdrh   */
23136a3ea0e6Sdrh   pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 0,
231468d2e591Sdrh                             pGroupBy ? 0 : &pOrderBy);
23151d83f052Sdrh   if( pWInfo==0 ) goto select_end;
2316cce7d176Sdrh 
23172282792aSdrh   /* Use the standard inner loop if we are not dealing with
23182282792aSdrh   ** aggregates
2319cce7d176Sdrh   */
2320da9d6c45Sdrh   if( !isAgg ){
2321df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2322df199a25Sdrh                     iParm, pWInfo->iContinue, pWInfo->iBreak) ){
23231d83f052Sdrh        goto select_end;
2324cce7d176Sdrh     }
2325da9d6c45Sdrh   }
2326cce7d176Sdrh 
2327e3184744Sdrh   /* If we are dealing with aggregates, then do the special aggregate
23282282792aSdrh   ** processing.
2329efb7251dSdrh   */
23302282792aSdrh   else{
23312282792aSdrh     if( pGroupBy ){
23321bee3d7bSdrh       int lbl1;
23332282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
23342282792aSdrh         sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
2335efb7251dSdrh       }
233699fcd718Sdrh       sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
2337491791a8Sdrh       if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pGroupBy);
23381bee3d7bSdrh       lbl1 = sqliteVdbeMakeLabel(v);
233999fcd718Sdrh       sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
23402282792aSdrh       for(i=0; i<pParse->nAgg; i++){
23412282792aSdrh         if( pParse->aAgg[i].isAgg ) continue;
23422282792aSdrh         sqliteExprCode(pParse, pParse->aAgg[i].pExpr);
234399fcd718Sdrh         sqliteVdbeAddOp(v, OP_AggSet, 0, i);
23442282792aSdrh       }
23452282792aSdrh       sqliteVdbeResolveLabel(v, lbl1);
23462282792aSdrh     }
23472282792aSdrh     for(i=0; i<pParse->nAgg; i++){
23482282792aSdrh       Expr *pE;
23490bce8354Sdrh       int j;
23502282792aSdrh       if( !pParse->aAgg[i].isAgg ) continue;
23512282792aSdrh       pE = pParse->aAgg[i].pExpr;
23522282792aSdrh       assert( pE->op==TK_AGG_FUNCTION );
23530bce8354Sdrh       if( pE->pList ){
2354e5095355Sdrh         for(j=0; j<pE->pList->nExpr; j++){
2355e5095355Sdrh           sqliteExprCode(pParse, pE->pList->a[j].pExpr);
2356e5095355Sdrh         }
23572282792aSdrh       }
23581350b030Sdrh       sqliteVdbeAddOp(v, OP_Integer, i, 0);
2359f55f25f0Sdrh       sqliteVdbeAddOp(v, OP_AggFunc, 0, pE->pList ? pE->pList->nExpr : 0);
23600bce8354Sdrh       assert( pParse->aAgg[i].pFunc!=0 );
23610bce8354Sdrh       assert( pParse->aAgg[i].pFunc->xStep!=0 );
23620bce8354Sdrh       sqliteVdbeChangeP3(v, -1, (char*)pParse->aAgg[i].pFunc, P3_POINTER);
23632282792aSdrh     }
23642282792aSdrh   }
23652282792aSdrh 
2366cce7d176Sdrh   /* End the database scan loop.
2367cce7d176Sdrh   */
2368cce7d176Sdrh   sqliteWhereEnd(pWInfo);
2369cce7d176Sdrh 
23702282792aSdrh   /* If we are processing aggregates, we need to set up a second loop
23712282792aSdrh   ** over all of the aggregate values and process them.
23722282792aSdrh   */
23732282792aSdrh   if( isAgg ){
23742282792aSdrh     int endagg = sqliteVdbeMakeLabel(v);
23752282792aSdrh     int startagg;
237699fcd718Sdrh     startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
23772282792aSdrh     pParse->useAgg = 1;
23782282792aSdrh     if( pHaving ){
2379f5905aa7Sdrh       sqliteExprIfFalse(pParse, pHaving, startagg, 1);
23802282792aSdrh     }
2381df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2382df199a25Sdrh                     iParm, startagg, endagg) ){
23831d83f052Sdrh       goto select_end;
23842282792aSdrh     }
238599fcd718Sdrh     sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
238699fcd718Sdrh     sqliteVdbeResolveLabel(v, endagg);
238799fcd718Sdrh     sqliteVdbeAddOp(v, OP_Noop, 0, 0);
23882282792aSdrh     pParse->useAgg = 0;
23892282792aSdrh   }
23902282792aSdrh 
2391cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
2392cce7d176Sdrh   ** and send them to the callback one by one.
2393cce7d176Sdrh   */
2394cce7d176Sdrh   if( pOrderBy ){
2395c926afbcSdrh     generateSortTail(p, v, pEList->nExpr, eDest, iParm);
2396cce7d176Sdrh   }
23976a535340Sdrh 
23986a535340Sdrh 
23996a535340Sdrh   /* Issue a null callback if that is what the user wants.
24006a535340Sdrh   */
2401326dce74Sdrh   if( eDest==SRT_Callback &&
2402326dce74Sdrh     (pParse->useCallback==0 || (pParse->db->flags & SQLITE_NullCallback)!=0)
2403326dce74Sdrh   ){
24046a535340Sdrh     sqliteVdbeAddOp(v, OP_NullCallback, pEList->nExpr, 0);
24056a535340Sdrh   }
24066a535340Sdrh 
2407*f620b4e2Sdrh   /* If this was a subquery, we have now converted the subquery into a
2408*f620b4e2Sdrh   ** temporary table.  So delete the subquery structure from the parent
2409*f620b4e2Sdrh   ** to prevent this subquery from being evaluated again and to force the
2410*f620b4e2Sdrh   ** the use of the temporary table.
2411*f620b4e2Sdrh   */
2412*f620b4e2Sdrh   if( pParent ){
2413*f620b4e2Sdrh     assert( pParent->pSrc->nSrc>parentTab );
2414*f620b4e2Sdrh     assert( pParent->pSrc->a[parentTab].pSelect==p );
2415*f620b4e2Sdrh     sqliteSelectDelete(p);
2416*f620b4e2Sdrh     pParent->pSrc->a[parentTab].pSelect = 0;
2417*f620b4e2Sdrh   }
2418*f620b4e2Sdrh 
24191d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
24201d83f052Sdrh   ** to indicate no errors.
24211d83f052Sdrh   */
24221d83f052Sdrh   rc = 0;
24231d83f052Sdrh 
24241d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
24251d83f052Sdrh   ** successful coding of the SELECT.
24261d83f052Sdrh   */
24271d83f052Sdrh select_end:
24281d83f052Sdrh   sqliteAggregateInfoReset(pParse);
24291d83f052Sdrh   return rc;
2430cce7d176Sdrh }
2431