xref: /sqlite-3.40.0/src/select.c (revision e4de1feb)
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*e4de1febSdrh ** $Id: select.c,v 1.90 2002/06/02 16:09:02 drh Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19cce7d176Sdrh /*
209bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that
219bb61fe7Sdrh ** structure.
22cce7d176Sdrh */
239bb61fe7Sdrh Select *sqliteSelectNew(
24daffd0e5Sdrh   ExprList *pEList,     /* which columns to include in the result */
25ad3cab52Sdrh   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
26daffd0e5Sdrh   Expr *pWhere,         /* the WHERE clause */
27daffd0e5Sdrh   ExprList *pGroupBy,   /* the GROUP BY clause */
28daffd0e5Sdrh   Expr *pHaving,        /* the HAVING clause */
29daffd0e5Sdrh   ExprList *pOrderBy,   /* the ORDER BY clause */
309bbca4c1Sdrh   int isDistinct,       /* true if the DISTINCT keyword is present */
319bbca4c1Sdrh   int nLimit,           /* LIMIT value.  -1 means not used */
329bbca4c1Sdrh   int nOffset           /* OFFSET value.  -1 means not used */
339bb61fe7Sdrh ){
349bb61fe7Sdrh   Select *pNew;
359bb61fe7Sdrh   pNew = sqliteMalloc( sizeof(*pNew) );
36daffd0e5Sdrh   if( pNew==0 ){
37daffd0e5Sdrh     sqliteExprListDelete(pEList);
38ad3cab52Sdrh     sqliteSrcListDelete(pSrc);
39daffd0e5Sdrh     sqliteExprDelete(pWhere);
40daffd0e5Sdrh     sqliteExprListDelete(pGroupBy);
41daffd0e5Sdrh     sqliteExprDelete(pHaving);
42daffd0e5Sdrh     sqliteExprListDelete(pOrderBy);
43daffd0e5Sdrh   }else{
449bb61fe7Sdrh     pNew->pEList = pEList;
459bb61fe7Sdrh     pNew->pSrc = pSrc;
469bb61fe7Sdrh     pNew->pWhere = pWhere;
479bb61fe7Sdrh     pNew->pGroupBy = pGroupBy;
489bb61fe7Sdrh     pNew->pHaving = pHaving;
499bb61fe7Sdrh     pNew->pOrderBy = pOrderBy;
509bb61fe7Sdrh     pNew->isDistinct = isDistinct;
5182c3d636Sdrh     pNew->op = TK_SELECT;
529bbca4c1Sdrh     pNew->nLimit = nLimit;
539bbca4c1Sdrh     pNew->nOffset = nOffset;
54daffd0e5Sdrh   }
559bb61fe7Sdrh   return pNew;
569bb61fe7Sdrh }
579bb61fe7Sdrh 
589bb61fe7Sdrh /*
5901f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
6001f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
6101f3f253Sdrh ** in terms of the following bit values:
6201f3f253Sdrh **
6301f3f253Sdrh **     JT_INNER
6401f3f253Sdrh **     JT_OUTER
6501f3f253Sdrh **     JT_NATURAL
6601f3f253Sdrh **     JT_LEFT
6701f3f253Sdrh **     JT_RIGHT
6801f3f253Sdrh **
6901f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
7001f3f253Sdrh **
7101f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
7201f3f253Sdrh ** a join type, but put an error in the pParse structure.
7301f3f253Sdrh */
7401f3f253Sdrh int sqliteJoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
7501f3f253Sdrh   int jointype = 0;
7601f3f253Sdrh   Token *apAll[3];
7701f3f253Sdrh   Token *p;
7801f3f253Sdrh   static struct {
7901f3f253Sdrh     const char *zKeyword;
8001f3f253Sdrh     int nChar;
8101f3f253Sdrh     int code;
8201f3f253Sdrh   } keywords[] = {
8301f3f253Sdrh     { "natural", 7, JT_NATURAL },
84195e6967Sdrh     { "left",    4, JT_LEFT|JT_OUTER },
85195e6967Sdrh     { "right",   5, JT_RIGHT|JT_OUTER },
86195e6967Sdrh     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
8701f3f253Sdrh     { "outer",   5, JT_OUTER },
8801f3f253Sdrh     { "inner",   5, JT_INNER },
8901f3f253Sdrh     { "cross",   5, JT_INNER },
9001f3f253Sdrh   };
9101f3f253Sdrh   int i, j;
9201f3f253Sdrh   apAll[0] = pA;
9301f3f253Sdrh   apAll[1] = pB;
9401f3f253Sdrh   apAll[2] = pC;
95195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
9601f3f253Sdrh     p = apAll[i];
9701f3f253Sdrh     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
9801f3f253Sdrh       if( p->n==keywords[j].nChar
9901f3f253Sdrh           && sqliteStrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
10001f3f253Sdrh         jointype |= keywords[j].code;
10101f3f253Sdrh         break;
10201f3f253Sdrh       }
10301f3f253Sdrh     }
10401f3f253Sdrh     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
10501f3f253Sdrh       jointype |= JT_ERROR;
10601f3f253Sdrh       break;
10701f3f253Sdrh     }
10801f3f253Sdrh   }
109ad2d8307Sdrh   if(
110ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
111195e6967Sdrh      (jointype & JT_ERROR)!=0
112ad2d8307Sdrh   ){
11301f3f253Sdrh     static Token dummy = { 0, 0 };
11401f3f253Sdrh     char *zSp1 = " ", *zSp2 = " ";
11501f3f253Sdrh     if( pB==0 ){ pB = &dummy; zSp1 = 0; }
11601f3f253Sdrh     if( pC==0 ){ pC = &dummy; zSp2 = 0; }
11701f3f253Sdrh     sqliteSetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
11801f3f253Sdrh        pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0);
11901f3f253Sdrh     pParse->nErr++;
12001f3f253Sdrh     jointype = JT_INNER;
121195e6967Sdrh   }else if( jointype & JT_RIGHT ){
122195e6967Sdrh     sqliteSetString(&pParse->zErrMsg,
123195e6967Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported", 0);
124195e6967Sdrh     pParse->nErr++;
125195e6967Sdrh     jointype = JT_INNER;
12601f3f253Sdrh   }
12701f3f253Sdrh   return jointype;
12801f3f253Sdrh }
12901f3f253Sdrh 
13001f3f253Sdrh /*
131ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
132ad2d8307Sdrh ** is not contained in the table.
133ad2d8307Sdrh */
134ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
135ad2d8307Sdrh   int i;
136ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
137ad2d8307Sdrh     if( sqliteStrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
138ad2d8307Sdrh   }
139ad2d8307Sdrh   return -1;
140ad2d8307Sdrh }
141ad2d8307Sdrh 
142ad2d8307Sdrh /*
143ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the
144ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2.
145ad2d8307Sdrh */
146ad2d8307Sdrh static void addWhereTerm(
147ad2d8307Sdrh   const char *zCol,        /* Name of the column */
148ad2d8307Sdrh   const Table *pTab1,      /* First table */
149ad2d8307Sdrh   const Table *pTab2,      /* Second table */
150ad2d8307Sdrh   Expr **ppExpr            /* Add the equality term to this expression */
151ad2d8307Sdrh ){
152ad2d8307Sdrh   Token dummy;
153ad2d8307Sdrh   Expr *pE1a, *pE1b, *pE1c;
154ad2d8307Sdrh   Expr *pE2a, *pE2b, *pE2c;
155ad2d8307Sdrh   Expr *pE;
156ad2d8307Sdrh 
157ad2d8307Sdrh   dummy.z = zCol;
158ad2d8307Sdrh   dummy.n = strlen(zCol);
159ad2d8307Sdrh   pE1a = sqliteExpr(TK_ID, 0, 0, &dummy);
160ad2d8307Sdrh   pE2a = sqliteExpr(TK_ID, 0, 0, &dummy);
161ad2d8307Sdrh   dummy.z = pTab1->zName;
162ad2d8307Sdrh   dummy.n = strlen(dummy.z);
163ad2d8307Sdrh   pE1b = sqliteExpr(TK_ID, 0, 0, &dummy);
164ad2d8307Sdrh   dummy.z = pTab2->zName;
165ad2d8307Sdrh   dummy.n = strlen(dummy.z);
166ad2d8307Sdrh   pE2b = sqliteExpr(TK_ID, 0, 0, &dummy);
167ad2d8307Sdrh   pE1c = sqliteExpr(TK_DOT, pE1b, pE1a, 0);
168ad2d8307Sdrh   pE2c = sqliteExpr(TK_DOT, pE2b, pE2a, 0);
169ad2d8307Sdrh   pE = sqliteExpr(TK_EQ, pE1c, pE2c, 0);
170ad2d8307Sdrh   if( *ppExpr ){
171ad2d8307Sdrh     *ppExpr = sqliteExpr(TK_AND, *ppExpr, pE, 0);
172ad2d8307Sdrh   }else{
173ad2d8307Sdrh     *ppExpr = pE;
174ad2d8307Sdrh   }
175ad2d8307Sdrh }
176ad2d8307Sdrh 
177ad2d8307Sdrh /*
178ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
179ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
180ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
181ad2d8307Sdrh **
182ad2d8307Sdrh ** This routine returns the number of errors encountered.
183ad2d8307Sdrh */
184ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
185ad2d8307Sdrh   SrcList *pSrc;
186ad2d8307Sdrh   int i, j;
187ad2d8307Sdrh   pSrc = p->pSrc;
188ad2d8307Sdrh   for(i=0; i<pSrc->nSrc-1; i++){
189ad2d8307Sdrh     struct SrcList_item *pTerm = &pSrc->a[i];
190ad2d8307Sdrh     struct SrcList_item *pOther = &pSrc->a[i+1];
191ad2d8307Sdrh 
192ad2d8307Sdrh     if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
193ad2d8307Sdrh 
194ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
195ad2d8307Sdrh     ** every column that the two tables have in common.
196ad2d8307Sdrh     */
197ad2d8307Sdrh     if( pTerm->jointype & JT_NATURAL ){
198ad2d8307Sdrh       Table *pTab;
199ad2d8307Sdrh       if( pTerm->pOn || pTerm->pUsing ){
200ad2d8307Sdrh         sqliteSetString(&pParse->zErrMsg, "a NATURAL join may not have "
201ad2d8307Sdrh            "an ON or USING clause", 0);
202ad2d8307Sdrh         pParse->nErr++;
203ad2d8307Sdrh         return 1;
204ad2d8307Sdrh       }
205ad2d8307Sdrh       pTab = pTerm->pTab;
206ad2d8307Sdrh       for(j=0; j<pTab->nCol; j++){
207ad2d8307Sdrh         if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
208ad2d8307Sdrh           addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
209ad2d8307Sdrh         }
210ad2d8307Sdrh       }
211ad2d8307Sdrh     }
212ad2d8307Sdrh 
213ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
214ad2d8307Sdrh     */
215ad2d8307Sdrh     if( pTerm->pOn && pTerm->pUsing ){
216ad2d8307Sdrh       sqliteSetString(&pParse->zErrMsg, "cannot have both ON and USING "
217ad2d8307Sdrh         "clauses in the same join", 0);
218ad2d8307Sdrh       pParse->nErr++;
219ad2d8307Sdrh       return 1;
220ad2d8307Sdrh     }
221ad2d8307Sdrh 
222ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
223ad2d8307Sdrh     ** and AND operator.
224ad2d8307Sdrh     */
225ad2d8307Sdrh     if( pTerm->pOn ){
226ad2d8307Sdrh       if( p->pWhere==0 ){
227ad2d8307Sdrh         p->pWhere = pTerm->pOn;
228ad2d8307Sdrh       }else{
229ad2d8307Sdrh         p->pWhere = sqliteExpr(TK_AND, p->pWhere, pTerm->pOn, 0);
230ad2d8307Sdrh       }
231ad2d8307Sdrh       pTerm->pOn = 0;
232ad2d8307Sdrh     }
233ad2d8307Sdrh 
234ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
235ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
236ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
237ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
238ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
239ad2d8307Sdrh     ** not contained in both tables to be joined.
240ad2d8307Sdrh     */
241ad2d8307Sdrh     if( pTerm->pUsing ){
242ad2d8307Sdrh       IdList *pList;
243ad2d8307Sdrh       int j;
244ad2d8307Sdrh       assert( i<pSrc->nSrc-1 );
245ad2d8307Sdrh       pList = pTerm->pUsing;
246ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
247ad2d8307Sdrh         if( columnIndex(pTerm->pTab, pList->a[i].zName)<0 ||
248ad2d8307Sdrh             columnIndex(pOther->pTab, pList->a[i].zName)<0 ){
249ad2d8307Sdrh           sqliteSetString(&pParse->zErrMsg, "cannot join using column ",
250ad2d8307Sdrh             pList->a[i].zName, " - column not present in both tables", 0);
251ad2d8307Sdrh           pParse->nErr++;
252ad2d8307Sdrh           return 1;
253ad2d8307Sdrh         }
254ad2d8307Sdrh         addWhereTerm(pList->a[i].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
255ad2d8307Sdrh       }
256ad2d8307Sdrh     }
257ad2d8307Sdrh   }
258ad2d8307Sdrh   return 0;
259ad2d8307Sdrh }
260ad2d8307Sdrh 
261ad2d8307Sdrh /*
2629bb61fe7Sdrh ** Delete the given Select structure and all of its substructures.
2639bb61fe7Sdrh */
2649bb61fe7Sdrh void sqliteSelectDelete(Select *p){
26582c3d636Sdrh   if( p==0 ) return;
2669bb61fe7Sdrh   sqliteExprListDelete(p->pEList);
267ad3cab52Sdrh   sqliteSrcListDelete(p->pSrc);
2689bb61fe7Sdrh   sqliteExprDelete(p->pWhere);
2699bb61fe7Sdrh   sqliteExprListDelete(p->pGroupBy);
2709bb61fe7Sdrh   sqliteExprDelete(p->pHaving);
2719bb61fe7Sdrh   sqliteExprListDelete(p->pOrderBy);
27282c3d636Sdrh   sqliteSelectDelete(p->pPrior);
273a76b5dfcSdrh   sqliteFree(p->zSelect);
2749bb61fe7Sdrh   sqliteFree(p);
2759bb61fe7Sdrh }
2769bb61fe7Sdrh 
2779bb61fe7Sdrh /*
2782282792aSdrh ** Delete the aggregate information from the parse structure.
2792282792aSdrh */
2801d83f052Sdrh static void sqliteAggregateInfoReset(Parse *pParse){
2812282792aSdrh   sqliteFree(pParse->aAgg);
2822282792aSdrh   pParse->aAgg = 0;
2832282792aSdrh   pParse->nAgg = 0;
2842282792aSdrh   pParse->useAgg = 0;
2852282792aSdrh }
2862282792aSdrh 
2872282792aSdrh /*
2882282792aSdrh ** This routine generates the code for the inside of the inner loop
2892282792aSdrh ** of a SELECT.
29082c3d636Sdrh **
29182c3d636Sdrh ** The pEList is used to determine the values for each column in the
292967e8b73Sdrh ** result row.  Except  if pEList==NULL, then we just read nColumn
29382c3d636Sdrh ** elements from the srcTab table.
2942282792aSdrh */
2952282792aSdrh static int selectInnerLoop(
2962282792aSdrh   Parse *pParse,          /* The parser context */
2972282792aSdrh   ExprList *pEList,       /* List of values being extracted */
29882c3d636Sdrh   int srcTab,             /* Pull data from this table */
299967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
3002282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
3012282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
3022282792aSdrh   int eDest,              /* How to dispose of the results */
3032282792aSdrh   int iParm,              /* An argument to the disposal method */
3042282792aSdrh   int iContinue,          /* Jump here to continue with next row */
3052282792aSdrh   int iBreak              /* Jump here to break out of the inner loop */
3062282792aSdrh ){
3072282792aSdrh   Vdbe *v = pParse->pVdbe;
3082282792aSdrh   int i;
309daffd0e5Sdrh   if( v==0 ) return 0;
3102282792aSdrh 
311967e8b73Sdrh   /* Pull the requested columns.
3122282792aSdrh   */
31382c3d636Sdrh   if( pEList ){
3142282792aSdrh     for(i=0; i<pEList->nExpr; i++){
3152282792aSdrh       sqliteExprCode(pParse, pEList->a[i].pExpr);
3162282792aSdrh     }
317967e8b73Sdrh     nColumn = pEList->nExpr;
31882c3d636Sdrh   }else{
319967e8b73Sdrh     for(i=0; i<nColumn; i++){
32099fcd718Sdrh       sqliteVdbeAddOp(v, OP_Column, srcTab, i);
32182c3d636Sdrh     }
32282c3d636Sdrh   }
3232282792aSdrh 
324daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
325daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
326daffd0e5Sdrh   ** part of the result.
3272282792aSdrh   */
328f5905aa7Sdrh   if( distinct>=0 && pEList && pEList->nExpr>0 ){
329f570f011Sdrh     /* For the purposes of the DISTINCT keyword to a SELECT, NULLs
330f570f011Sdrh     ** are indistinct.  This was confirmed by experiment in Oracle
331f570f011Sdrh     ** and PostgreSQL.  It seems contradictory, but it appears to be
332f570f011Sdrh     ** true.
333f570f011Sdrh     ** sqliteVdbeAddOp(v, OP_IsNull, -pEList->nExpr,sqliteVdbeCurrentAddr(v)+7);
334f570f011Sdrh     */
33599fcd718Sdrh     sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
336f5905aa7Sdrh     sqliteVdbeAddOp(v, OP_Distinct, distinct, sqliteVdbeCurrentAddr(v)+3);
33799fcd718Sdrh     sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
33899fcd718Sdrh     sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
33999fcd718Sdrh     sqliteVdbeAddOp(v, OP_String, 0, 0);
3406b12545fSdrh     sqliteVdbeAddOp(v, OP_PutStrKey, distinct, 0);
3412282792aSdrh   }
34282c3d636Sdrh 
3432282792aSdrh   /* If there is an ORDER BY clause, then store the results
3442282792aSdrh   ** in a sorter.
3452282792aSdrh   */
3462282792aSdrh   if( pOrderBy ){
3472282792aSdrh     char *zSortOrder;
34899fcd718Sdrh     sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
3492282792aSdrh     zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
3502282792aSdrh     if( zSortOrder==0 ) return 1;
3512282792aSdrh     for(i=0; i<pOrderBy->nExpr; i++){
352d8bc7086Sdrh       zSortOrder[i] = pOrderBy->a[i].sortOrder ? '-' : '+';
3532282792aSdrh       sqliteExprCode(pParse, pOrderBy->a[i].pExpr);
3542282792aSdrh     }
3552282792aSdrh     zSortOrder[pOrderBy->nExpr] = 0;
35699fcd718Sdrh     sqliteVdbeAddOp(v, OP_SortMakeKey, pOrderBy->nExpr, 0);
35799fcd718Sdrh     sqliteVdbeChangeP3(v, -1, zSortOrder, strlen(zSortOrder));
3586e142f54Sdrh     sqliteFree(zSortOrder);
35999fcd718Sdrh     sqliteVdbeAddOp(v, OP_SortPut, 0, 0);
3602282792aSdrh   }else
3612282792aSdrh 
36282c3d636Sdrh   /* In this mode, write each query result to the key of the temporary
36382c3d636Sdrh   ** table iParm.
3642282792aSdrh   */
36582c3d636Sdrh   if( eDest==SRT_Union ){
366f570f011Sdrh     sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
367f5905aa7Sdrh     sqliteVdbeAddOp(v, OP_String, 0, 0);
3686b12545fSdrh     sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
36982c3d636Sdrh   }else
37082c3d636Sdrh 
3715974a30fSdrh   /* Store the result as data using a unique key.
3725974a30fSdrh   */
3732d0794e3Sdrh   if( eDest==SRT_Table || eDest==SRT_TempTable ){
37499fcd718Sdrh     sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
37599fcd718Sdrh     sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
37699fcd718Sdrh     sqliteVdbeAddOp(v, OP_Pull, 1, 0);
3776b12545fSdrh     sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
3785974a30fSdrh   }else
3795974a30fSdrh 
38082c3d636Sdrh   /* Construct a record from the query result, but instead of
38182c3d636Sdrh   ** saving that record, use it as a key to delete elements from
38282c3d636Sdrh   ** the temporary table iParm.
38382c3d636Sdrh   */
38482c3d636Sdrh   if( eDest==SRT_Except ){
385f570f011Sdrh     int addr = sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
38699fcd718Sdrh     sqliteVdbeAddOp(v, OP_NotFound, iParm, addr+3);
38799fcd718Sdrh     sqliteVdbeAddOp(v, OP_Delete, iParm, 0);
3882282792aSdrh   }else
3892282792aSdrh 
3902282792aSdrh   /* If we are creating a set for an "expr IN (SELECT ...)" construct,
3912282792aSdrh   ** then there should be a single item on the stack.  Write this
3922282792aSdrh   ** item into the set table with bogus data.
3932282792aSdrh   */
3942282792aSdrh   if( eDest==SRT_Set ){
395967e8b73Sdrh     assert( nColumn==1 );
396f5905aa7Sdrh     sqliteVdbeAddOp(v, OP_IsNull, -1, sqliteVdbeCurrentAddr(v)+3);
39799fcd718Sdrh     sqliteVdbeAddOp(v, OP_String, 0, 0);
3986b12545fSdrh     sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
3992282792aSdrh   }else
4002282792aSdrh 
40182c3d636Sdrh 
4022282792aSdrh   /* If this is a scalar select that is part of an expression, then
4032282792aSdrh   ** store the results in the appropriate memory cell and break out
4042282792aSdrh   ** of the scan loop.
4052282792aSdrh   */
4062282792aSdrh   if( eDest==SRT_Mem ){
407967e8b73Sdrh     assert( nColumn==1 );
4088721ce4aSdrh     sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
40999fcd718Sdrh     sqliteVdbeAddOp(v, OP_Goto, 0, iBreak);
4102282792aSdrh   }else
4112282792aSdrh 
412d7489c39Sdrh   /* Discard the results.  This is used for SELECT statements inside
413d7489c39Sdrh   ** the body of a TRIGGER.  The purpose of such selects is to call
414d7489c39Sdrh   ** user-defined functions that have side effects.  We do not care
415d7489c39Sdrh   ** about the actual results of the select.
416d7489c39Sdrh   */
417d7489c39Sdrh   if( eDest==SRT_Discard ){
418d7489c39Sdrh     sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
419d7489c39Sdrh   }else
420d7489c39Sdrh 
4212282792aSdrh   /* If none of the above, send the data to the callback function.
4222282792aSdrh   */
4232282792aSdrh   {
4249bbca4c1Sdrh     sqliteVdbeAddOp(v, OP_Callback, nColumn, iBreak);
42582c3d636Sdrh   }
42682c3d636Sdrh   return 0;
42782c3d636Sdrh }
42882c3d636Sdrh 
42982c3d636Sdrh /*
430d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
431d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
432d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
433d8bc7086Sdrh ** routine generates the code needed to do that.
434d8bc7086Sdrh */
435967e8b73Sdrh static void generateSortTail(Vdbe *v, int nColumn){
436d8bc7086Sdrh   int end = sqliteVdbeMakeLabel(v);
437d8bc7086Sdrh   int addr;
43899fcd718Sdrh   sqliteVdbeAddOp(v, OP_Sort, 0, 0);
43999fcd718Sdrh   addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end);
4409bbca4c1Sdrh   sqliteVdbeAddOp(v, OP_SortCallback, nColumn, end);
44199fcd718Sdrh   sqliteVdbeAddOp(v, OP_Goto, 0, addr);
44299fcd718Sdrh   sqliteVdbeResolveLabel(v, end);
443a8b38d28Sdrh   sqliteVdbeAddOp(v, OP_SortReset, 0, 0);
444d8bc7086Sdrh }
445d8bc7086Sdrh 
446d8bc7086Sdrh /*
44782c3d636Sdrh ** Generate code that will tell the VDBE how many columns there
44882c3d636Sdrh ** are in the result and the name for each column.  This information
44982c3d636Sdrh ** is used to provide "argc" and "azCol[]" values in the callback.
45082c3d636Sdrh */
451832508b7Sdrh static void generateColumnNames(
452832508b7Sdrh   Parse *pParse,      /* Parser context */
453832508b7Sdrh   int base,           /* VDBE cursor corresponding to first entry in pTabList */
454ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
455832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
456832508b7Sdrh ){
457d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
45882c3d636Sdrh   int i;
459daffd0e5Sdrh   if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return;
460d8bc7086Sdrh   pParse->colNamesSet = 1;
46199fcd718Sdrh   sqliteVdbeAddOp(v, OP_ColumnCount, pEList->nExpr, 0);
46282c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
46382c3d636Sdrh     Expr *p;
4641bee3d7bSdrh     int showFullNames;
46582c3d636Sdrh     if( pEList->a[i].zName ){
46682c3d636Sdrh       char *zName = pEList->a[i].zName;
46799fcd718Sdrh       sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
46899fcd718Sdrh       sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
46982c3d636Sdrh       continue;
47082c3d636Sdrh     }
47182c3d636Sdrh     p = pEList->a[i].pExpr;
472daffd0e5Sdrh     if( p==0 ) continue;
4731bee3d7bSdrh     showFullNames = (pParse->db->flags & SQLITE_FullColNames)!=0;
4741bee3d7bSdrh     if( p->span.z && p->span.z[0] && !showFullNames ){
47599fcd718Sdrh       int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
47699fcd718Sdrh       sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
477e1b6a5b8Sdrh       sqliteVdbeCompressSpace(v, addr);
4781bee3d7bSdrh     }else if( p->op==TK_COLUMN && pTabList ){
479832508b7Sdrh       Table *pTab = pTabList->a[p->iTable - base].pTab;
48097665873Sdrh       char *zCol;
4818aff1015Sdrh       int iCol = p->iColumn;
4828aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
48397665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
48497665873Sdrh       zCol = iCol<0 ? "_ROWID_" : pTab->aCol[iCol].zName;
485ad3cab52Sdrh       if( pTabList->nSrc>1 || showFullNames ){
48682c3d636Sdrh         char *zName = 0;
48782c3d636Sdrh         char *zTab;
48882c3d636Sdrh 
489832508b7Sdrh         zTab = pTabList->a[p->iTable - base].zAlias;
49001a34661Sdrh         if( showFullNames || zTab==0 ) zTab = pTab->zName;
49197665873Sdrh         sqliteSetString(&zName, zTab, ".", zCol, 0);
49299fcd718Sdrh         sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
49399fcd718Sdrh         sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
49482c3d636Sdrh         sqliteFree(zName);
49582c3d636Sdrh       }else{
49699fcd718Sdrh         sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
49722f70c32Sdrh         sqliteVdbeChangeP3(v, -1, zCol, 0);
49882c3d636Sdrh       }
4991bee3d7bSdrh     }else if( p->span.z && p->span.z[0] ){
5001bee3d7bSdrh       int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
5011bee3d7bSdrh       sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
5021bee3d7bSdrh       sqliteVdbeCompressSpace(v, addr);
5031bee3d7bSdrh     }else{
5041bee3d7bSdrh       char zName[30];
5051bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
5061bee3d7bSdrh       sprintf(zName, "column%d", i+1);
5071bee3d7bSdrh       sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
5081bee3d7bSdrh       sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
50982c3d636Sdrh     }
51082c3d636Sdrh   }
51182c3d636Sdrh }
51282c3d636Sdrh 
51382c3d636Sdrh /*
514d8bc7086Sdrh ** Name of the connection operator, used for error messages.
515d8bc7086Sdrh */
516d8bc7086Sdrh static const char *selectOpName(int id){
517d8bc7086Sdrh   char *z;
518d8bc7086Sdrh   switch( id ){
519d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
520d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
521d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
522d8bc7086Sdrh     default:           z = "UNION";       break;
523d8bc7086Sdrh   }
524d8bc7086Sdrh   return z;
525d8bc7086Sdrh }
526d8bc7086Sdrh 
527d8bc7086Sdrh /*
52822f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
52922f70c32Sdrh ** the result set of that SELECT.
53022f70c32Sdrh */
53122f70c32Sdrh Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
53222f70c32Sdrh   Table *pTab;
53322f70c32Sdrh   int i;
53422f70c32Sdrh   ExprList *pEList;
53522f70c32Sdrh   static int fillInColumnList(Parse*, Select*);
53622f70c32Sdrh 
53722f70c32Sdrh   if( fillInColumnList(pParse, pSelect) ){
53822f70c32Sdrh     return 0;
53922f70c32Sdrh   }
54022f70c32Sdrh   pTab = sqliteMalloc( sizeof(Table) );
54122f70c32Sdrh   if( pTab==0 ){
54222f70c32Sdrh     return 0;
54322f70c32Sdrh   }
54422f70c32Sdrh   pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
54522f70c32Sdrh   pEList = pSelect->pEList;
54622f70c32Sdrh   pTab->nCol = pEList->nExpr;
547417be79cSdrh   assert( pTab->nCol>0 );
54822f70c32Sdrh   pTab->aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
54922f70c32Sdrh   for(i=0; i<pTab->nCol; i++){
55022f70c32Sdrh     Expr *p;
55122f70c32Sdrh     if( pEList->a[i].zName ){
55222f70c32Sdrh       pTab->aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
55322f70c32Sdrh     }else if( (p=pEList->a[i].pExpr)->span.z && p->span.z[0] ){
55422f70c32Sdrh       sqliteSetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
555d820cb1bSdrh     }else if( p->op==TK_DOT && p->pRight && p->pRight->token.z &&
556d820cb1bSdrh            p->pRight->token.z[0] ){
557d820cb1bSdrh       sqliteSetNString(&pTab->aCol[i].zName,
558d820cb1bSdrh            p->pRight->token.z, p->pRight->token.n, 0);
55922f70c32Sdrh     }else{
56022f70c32Sdrh       char zBuf[30];
56122f70c32Sdrh       sprintf(zBuf, "column%d", i+1);
56222f70c32Sdrh       pTab->aCol[i].zName = sqliteStrDup(zBuf);
56322f70c32Sdrh     }
56422f70c32Sdrh   }
56522f70c32Sdrh   pTab->iPKey = -1;
56622f70c32Sdrh   return pTab;
56722f70c32Sdrh }
56822f70c32Sdrh 
56922f70c32Sdrh /*
570ad2d8307Sdrh ** For the given SELECT statement, do three things.
571d8bc7086Sdrh **
572ad3cab52Sdrh **    (1)  Fill in the pTabList->a[].pTab fields in the SrcList that
573967e8b73Sdrh **         defines the set of tables that should be scanned.
574d8bc7086Sdrh **
575ad2d8307Sdrh **    (2)  Add terms to the WHERE clause to accomodate the NATURAL keyword
576ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
577ad2d8307Sdrh **
578ad2d8307Sdrh **    (3)  Scan the list of columns in the result set (pEList) looking
57954473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
58054473229Sdrh **         If found, expand each "*" to be every column in every table
58154473229Sdrh **         and TABLE.* to be every column in TABLE.
582d8bc7086Sdrh **
583d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
584d8bc7086Sdrh ** in pParse and return non-zero.
585d8bc7086Sdrh */
586d8bc7086Sdrh static int fillInColumnList(Parse *pParse, Select *p){
58754473229Sdrh   int i, j, k, rc;
588ad3cab52Sdrh   SrcList *pTabList;
589daffd0e5Sdrh   ExprList *pEList;
590a76b5dfcSdrh   Table *pTab;
591daffd0e5Sdrh 
592daffd0e5Sdrh   if( p==0 || p->pSrc==0 ) return 1;
593daffd0e5Sdrh   pTabList = p->pSrc;
594daffd0e5Sdrh   pEList = p->pEList;
595d8bc7086Sdrh 
596d8bc7086Sdrh   /* Look up every table in the table list.
597d8bc7086Sdrh   */
598ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
599d8bc7086Sdrh     if( pTabList->a[i].pTab ){
600d8bc7086Sdrh       /* This routine has run before!  No need to continue */
601d8bc7086Sdrh       return 0;
602d8bc7086Sdrh     }
603daffd0e5Sdrh     if( pTabList->a[i].zName==0 ){
60422f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
60522f70c32Sdrh       assert( pTabList->a[i].pSelect!=0 );
606ad2d8307Sdrh       if( pTabList->a[i].zAlias==0 ){
607ad2d8307Sdrh         char zFakeName[60];
608ad2d8307Sdrh         sprintf(zFakeName, "sqlite_subquery_%p_",
609ad2d8307Sdrh            (void*)pTabList->a[i].pSelect);
610ad2d8307Sdrh         sqliteSetString(&pTabList->a[i].zAlias, zFakeName, 0);
611ad2d8307Sdrh       }
61222f70c32Sdrh       pTabList->a[i].pTab = pTab =
61322f70c32Sdrh         sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias,
61422f70c32Sdrh                                         pTabList->a[i].pSelect);
61522f70c32Sdrh       if( pTab==0 ){
616daffd0e5Sdrh         return 1;
617daffd0e5Sdrh       }
61822f70c32Sdrh       pTab->isTransient = 1;
61922f70c32Sdrh     }else{
620a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
621a76b5dfcSdrh       pTabList->a[i].pTab = pTab =
622a76b5dfcSdrh         sqliteFindTable(pParse->db, pTabList->a[i].zName);
623a76b5dfcSdrh       if( pTab==0 ){
624d8bc7086Sdrh         sqliteSetString(&pParse->zErrMsg, "no such table: ",
625d8bc7086Sdrh            pTabList->a[i].zName, 0);
626d8bc7086Sdrh         pParse->nErr++;
627d8bc7086Sdrh         return 1;
628d8bc7086Sdrh       }
629a76b5dfcSdrh       if( pTab->pSelect ){
630417be79cSdrh         if( sqliteViewGetColumnNames(pParse, pTab) ){
631417be79cSdrh           return 1;
632417be79cSdrh         }
633ff78bd2fSdrh         pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect);
634a76b5dfcSdrh       }
635d8bc7086Sdrh     }
63622f70c32Sdrh   }
637d8bc7086Sdrh 
638ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
639ad2d8307Sdrh   */
640ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
641ad2d8307Sdrh 
6427c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
64354473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
64454473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
6457c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
6467c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
6477c917d19Sdrh   ** each one to the list of all columns in all tables.
64854473229Sdrh   **
64954473229Sdrh   ** The first loop just checks to see if there are any "*" operators
65054473229Sdrh   ** that need expanding.
651d8bc7086Sdrh   */
6527c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
65354473229Sdrh     Expr *pE = pEList->a[k].pExpr;
65454473229Sdrh     if( pE->op==TK_ALL ) break;
65554473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
65654473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
6577c917d19Sdrh   }
65854473229Sdrh   rc = 0;
6597c917d19Sdrh   if( k<pEList->nExpr ){
66054473229Sdrh     /*
66154473229Sdrh     ** If we get here it means the result set contains one or more "*"
66254473229Sdrh     ** operators that need to be expanded.  Loop through each expression
66354473229Sdrh     ** in the result set and expand them one by one.
66454473229Sdrh     */
6657c917d19Sdrh     struct ExprList_item *a = pEList->a;
6667c917d19Sdrh     ExprList *pNew = 0;
6677c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
66854473229Sdrh       Expr *pE = a[k].pExpr;
66954473229Sdrh       if( pE->op!=TK_ALL &&
67054473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
67154473229Sdrh         /* This particular expression does not need to be expanded.
67254473229Sdrh         */
6737c917d19Sdrh         pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
6747c917d19Sdrh         pNew->a[pNew->nExpr-1].zName = a[k].zName;
6757c917d19Sdrh         a[k].pExpr = 0;
6767c917d19Sdrh         a[k].zName = 0;
6777c917d19Sdrh       }else{
67854473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
67954473229Sdrh         ** expanded. */
68054473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
68154473229Sdrh         Token *pName;           /* text of name of TABLE */
68254473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
68354473229Sdrh           pName = &pE->pLeft->token;
68454473229Sdrh         }else{
68554473229Sdrh           pName = 0;
68654473229Sdrh         }
687ad3cab52Sdrh         for(i=0; i<pTabList->nSrc; i++){
688d8bc7086Sdrh           Table *pTab = pTabList->a[i].pTab;
68954473229Sdrh           char *zTabName = pTabList->a[i].zAlias;
69054473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
69154473229Sdrh             zTabName = pTab->zName;
69254473229Sdrh           }
69354473229Sdrh           if( pName && (zTabName==0 || zTabName[0]==0 ||
694c754fa54Sdrh                  sqliteStrNICmp(pName->z, zTabName, pName->n)!=0 ||
695c754fa54Sdrh                  zTabName[pName->n]!=0) ){
69654473229Sdrh             continue;
69754473229Sdrh           }
69854473229Sdrh           tableSeen = 1;
699d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
70022f70c32Sdrh             Expr *pExpr, *pLeft, *pRight;
701ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
702ad2d8307Sdrh 
703ad2d8307Sdrh             if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
704ad2d8307Sdrh                 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
705ad2d8307Sdrh               /* In a NATURAL join, omit the join columns from the
706ad2d8307Sdrh               ** table on the right */
707ad2d8307Sdrh               continue;
708ad2d8307Sdrh             }
709ad2d8307Sdrh             if( i>0 && sqliteIdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
710ad2d8307Sdrh               /* In a join with a USING clause, omit columns in the
711ad2d8307Sdrh               ** using clause from the table on the right. */
712ad2d8307Sdrh               continue;
713ad2d8307Sdrh             }
71422f70c32Sdrh             pRight = sqliteExpr(TK_ID, 0, 0, 0);
71522f70c32Sdrh             if( pRight==0 ) break;
716ad2d8307Sdrh             pRight->token.z = zName;
717ad2d8307Sdrh             pRight->token.n = strlen(zName);
71854473229Sdrh             if( zTabName ){
71922f70c32Sdrh               pLeft = sqliteExpr(TK_ID, 0, 0, 0);
72022f70c32Sdrh               if( pLeft==0 ) break;
72154473229Sdrh               pLeft->token.z = zTabName;
72254473229Sdrh               pLeft->token.n = strlen(zTabName);
72322f70c32Sdrh               pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
72422f70c32Sdrh               if( pExpr==0 ) break;
72522f70c32Sdrh             }else{
72622f70c32Sdrh               pExpr = pRight;
72722f70c32Sdrh               pExpr->span = pExpr->token;
72822f70c32Sdrh             }
7297c917d19Sdrh             pNew = sqliteExprListAppend(pNew, pExpr, 0);
730d8bc7086Sdrh           }
731d8bc7086Sdrh         }
73254473229Sdrh         if( !tableSeen ){
73354473229Sdrh           assert( pName!=0 );
73454473229Sdrh           sqliteSetNString(&pParse->zErrMsg, "no such table: ", -1,
73554473229Sdrh             pName->z, pName->n, 0);
73654473229Sdrh           rc = 1;
73754473229Sdrh         }
7387c917d19Sdrh       }
7397c917d19Sdrh     }
7407c917d19Sdrh     sqliteExprListDelete(pEList);
7417c917d19Sdrh     p->pEList = pNew;
742d8bc7086Sdrh   }
74354473229Sdrh   return rc;
744d8bc7086Sdrh }
745d8bc7086Sdrh 
746d8bc7086Sdrh /*
747ff78bd2fSdrh ** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
748ff78bd2fSdrh ** in a select structure.  It just sets the pointers to NULL.  This
749ff78bd2fSdrh ** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
750ff78bd2fSdrh ** pointer is not NULL, this routine is called recursively on that pointer.
751ff78bd2fSdrh **
752ff78bd2fSdrh ** This routine is called on the Select structure that defines a
753ff78bd2fSdrh ** VIEW in order to undo any bindings to tables.  This is necessary
754ff78bd2fSdrh ** because those tables might be DROPed by a subsequent SQL command.
755ff78bd2fSdrh */
756ff78bd2fSdrh void sqliteSelectUnbind(Select *p){
757ff78bd2fSdrh   int i;
758ad3cab52Sdrh   SrcList *pSrc = p->pSrc;
759ff78bd2fSdrh   Table *pTab;
760ff78bd2fSdrh   if( p==0 ) return;
761ad3cab52Sdrh   for(i=0; i<pSrc->nSrc; i++){
762ff78bd2fSdrh     if( (pTab = pSrc->a[i].pTab)!=0 ){
763ff78bd2fSdrh       if( pTab->isTransient ){
764ff78bd2fSdrh         sqliteDeleteTable(0, pTab);
765ff78bd2fSdrh         sqliteSelectDelete(pSrc->a[i].pSelect);
766ff78bd2fSdrh         pSrc->a[i].pSelect = 0;
767ff78bd2fSdrh       }
768ff78bd2fSdrh       pSrc->a[i].pTab = 0;
769ff78bd2fSdrh       if( pSrc->a[i].pSelect ){
770ff78bd2fSdrh         sqliteSelectUnbind(pSrc->a[i].pSelect);
771ff78bd2fSdrh       }
772ff78bd2fSdrh     }
773ff78bd2fSdrh   }
774ff78bd2fSdrh }
775ff78bd2fSdrh 
776ff78bd2fSdrh /*
777d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with
778d8bc7086Sdrh ** columns in a result.  For each ORDER BY expression, the opcode of
779967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of
780d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable
781d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter.
782d8bc7086Sdrh **
783d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first.  A match
784d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT.
785d8bc7086Sdrh **
786d8bc7086Sdrh ** Any entry that does not match is flagged as an error.  The number
787d8bc7086Sdrh ** of errors is returned.
788d8bc7086Sdrh */
789d8bc7086Sdrh static int matchOrderbyToColumn(
790d8bc7086Sdrh   Parse *pParse,          /* A place to leave error messages */
791d8bc7086Sdrh   Select *pSelect,        /* Match to result columns of this SELECT */
792d8bc7086Sdrh   ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
793*e4de1febSdrh   int iTable,             /* Insert this value in iTable */
794d8bc7086Sdrh   int mustComplete        /* If TRUE all ORDER BYs must match */
795d8bc7086Sdrh ){
796d8bc7086Sdrh   int nErr = 0;
797d8bc7086Sdrh   int i, j;
798d8bc7086Sdrh   ExprList *pEList;
799d8bc7086Sdrh 
800daffd0e5Sdrh   if( pSelect==0 || pOrderBy==0 ) return 1;
801d8bc7086Sdrh   if( mustComplete ){
802d8bc7086Sdrh     for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
803d8bc7086Sdrh   }
804d8bc7086Sdrh   if( fillInColumnList(pParse, pSelect) ){
805d8bc7086Sdrh     return 1;
806d8bc7086Sdrh   }
807d8bc7086Sdrh   if( pSelect->pPrior ){
80892cd52f5Sdrh     if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
80992cd52f5Sdrh       return 1;
81092cd52f5Sdrh     }
811d8bc7086Sdrh   }
812d8bc7086Sdrh   pEList = pSelect->pEList;
813d8bc7086Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
814d8bc7086Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
815*e4de1febSdrh     int iCol = -1;
816d8bc7086Sdrh     if( pOrderBy->a[i].done ) continue;
817*e4de1febSdrh     if( sqliteExprIsInteger(pE, &iCol) ){
818*e4de1febSdrh       if( iCol<=0 || iCol>pEList->nExpr ){
819*e4de1febSdrh         char zBuf[200];
820*e4de1febSdrh         sprintf(zBuf,"ORDER BY position %d should be between 1 and %d",
821*e4de1febSdrh            iCol, pEList->nExpr);
822*e4de1febSdrh         sqliteSetString(&pParse->zErrMsg, zBuf, 0);
823*e4de1febSdrh         pParse->nErr++;
824*e4de1febSdrh         nErr++;
825*e4de1febSdrh         break;
826*e4de1febSdrh       }
827*e4de1febSdrh       iCol--;
828*e4de1febSdrh     }
829*e4de1febSdrh     for(j=0; iCol<0 && j<pEList->nExpr; j++){
8304cfa7934Sdrh       if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
831a76b5dfcSdrh         char *zName, *zLabel;
832a76b5dfcSdrh         zName = pEList->a[j].zName;
833a76b5dfcSdrh         assert( pE->token.z );
834a76b5dfcSdrh         zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
835d8bc7086Sdrh         sqliteDequote(zLabel);
836d8bc7086Sdrh         if( sqliteStrICmp(zName, zLabel)==0 ){
837*e4de1febSdrh           iCol = j;
838d8bc7086Sdrh         }
8396e142f54Sdrh         sqliteFree(zLabel);
840d8bc7086Sdrh       }
841*e4de1febSdrh       if( iCol<0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
842*e4de1febSdrh         iCol = j;
843d8bc7086Sdrh       }
844*e4de1febSdrh     }
845*e4de1febSdrh     if( iCol>=0 ){
846967e8b73Sdrh       pE->op = TK_COLUMN;
847*e4de1febSdrh       pE->iColumn = iCol;
848d8bc7086Sdrh       pE->iTable = iTable;
849d8bc7086Sdrh       pOrderBy->a[i].done = 1;
850d8bc7086Sdrh     }
851*e4de1febSdrh     if( iCol<0 && mustComplete ){
852d8bc7086Sdrh       char zBuf[30];
853d8bc7086Sdrh       sprintf(zBuf,"%d",i+1);
854d8bc7086Sdrh       sqliteSetString(&pParse->zErrMsg, "ORDER BY term number ", zBuf,
855d8bc7086Sdrh         " does not match any result column", 0);
856d8bc7086Sdrh       pParse->nErr++;
857d8bc7086Sdrh       nErr++;
858d8bc7086Sdrh       break;
859d8bc7086Sdrh     }
860d8bc7086Sdrh   }
861d8bc7086Sdrh   return nErr;
862d8bc7086Sdrh }
863d8bc7086Sdrh 
864d8bc7086Sdrh /*
865d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
866d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
867d8bc7086Sdrh */
868d8bc7086Sdrh Vdbe *sqliteGetVdbe(Parse *pParse){
869d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
870d8bc7086Sdrh   if( v==0 ){
8714c504391Sdrh     v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
872d8bc7086Sdrh   }
873d8bc7086Sdrh   return v;
874d8bc7086Sdrh }
875d8bc7086Sdrh 
876d8bc7086Sdrh 
877d8bc7086Sdrh /*
87882c3d636Sdrh ** This routine is called to process a query that is really the union
87982c3d636Sdrh ** or intersection of two or more separate queries.
88082c3d636Sdrh */
88182c3d636Sdrh static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
88210e5e3cfSdrh   int rc;             /* Success code from a subroutine */
88310e5e3cfSdrh   Select *pPrior;     /* Another SELECT immediately to our left */
88410e5e3cfSdrh   Vdbe *v;            /* Generate code to this VDBE */
88510e5e3cfSdrh   int base;           /* Baseline value for pParse->nTab */
88682c3d636Sdrh 
887d8bc7086Sdrh   /* Make sure there is no ORDER BY clause on prior SELECTs.  Only the
888d8bc7086Sdrh   ** last SELECT in the series may have an ORDER BY.
88982c3d636Sdrh   */
890daffd0e5Sdrh   if( p==0 || p->pPrior==0 ) return 1;
891d8bc7086Sdrh   pPrior = p->pPrior;
892d8bc7086Sdrh   if( pPrior->pOrderBy ){
893d8bc7086Sdrh     sqliteSetString(&pParse->zErrMsg,"ORDER BY clause should come after ",
894d8bc7086Sdrh       selectOpName(p->op), " not before", 0);
89582c3d636Sdrh     pParse->nErr++;
89682c3d636Sdrh     return 1;
89782c3d636Sdrh   }
89882c3d636Sdrh 
899d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
900d8bc7086Sdrh   */
901d8bc7086Sdrh   v = sqliteGetVdbe(pParse);
902d8bc7086Sdrh   if( v==0 ) return 1;
903d8bc7086Sdrh 
9041cc3d75fSdrh   /* Create the destination temporary table if necessary
9051cc3d75fSdrh   */
9061cc3d75fSdrh   if( eDest==SRT_TempTable ){
9071cc3d75fSdrh     sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
9081cc3d75fSdrh     eDest = SRT_Table;
9091cc3d75fSdrh   }
9101cc3d75fSdrh 
911d8bc7086Sdrh   /* Process the UNION or INTERSECTION
912d8bc7086Sdrh   */
91310e5e3cfSdrh   base = pParse->nTab;
91482c3d636Sdrh   switch( p->op ){
915d8bc7086Sdrh     case TK_ALL:
91682c3d636Sdrh     case TK_EXCEPT:
91782c3d636Sdrh     case TK_UNION: {
918d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
919d8bc7086Sdrh       int op;          /* One of the SRT_ operations to apply to self */
920d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
92182c3d636Sdrh 
922d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
923d8bc7086Sdrh       if( eDest==priorOp ){
924d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
925d8bc7086Sdrh         ** right.  This also means we are not the right-most select and so
926d8bc7086Sdrh         ** we cannot have an ORDER BY clause
927d8bc7086Sdrh         */
92882c3d636Sdrh         unionTab = iParm;
929d8bc7086Sdrh         assert( p->pOrderBy==0 );
93082c3d636Sdrh       }else{
931d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
932d8bc7086Sdrh         ** intermediate results.
933d8bc7086Sdrh         */
93482c3d636Sdrh         unionTab = pParse->nTab++;
935d8bc7086Sdrh         if( p->pOrderBy
936d8bc7086Sdrh         && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
937d8bc7086Sdrh           return 1;
938d8bc7086Sdrh         }
939d8bc7086Sdrh         if( p->op!=TK_ALL ){
940c6b52df3Sdrh           sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
94199fcd718Sdrh           sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
942345fda3eSdrh         }else{
94399fcd718Sdrh           sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
94482c3d636Sdrh         }
945d8bc7086Sdrh       }
946d8bc7086Sdrh 
947d8bc7086Sdrh       /* Code the SELECT statements to our left
948d8bc7086Sdrh       */
949832508b7Sdrh       rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
95082c3d636Sdrh       if( rc ) return rc;
951d8bc7086Sdrh 
952d8bc7086Sdrh       /* Code the current SELECT statement
953d8bc7086Sdrh       */
954d8bc7086Sdrh       switch( p->op ){
955d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
956d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
957d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
958d8bc7086Sdrh       }
95982c3d636Sdrh       p->pPrior = 0;
960832508b7Sdrh       rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0);
96182c3d636Sdrh       p->pPrior = pPrior;
96282c3d636Sdrh       if( rc ) return rc;
963d8bc7086Sdrh 
964d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
965d8bc7086Sdrh       ** it is that we currently need.
966d8bc7086Sdrh       */
967d8bc7086Sdrh       if( eDest!=priorOp ){
9686b56344dSdrh         int iCont, iBreak, iStart;
96982c3d636Sdrh         assert( p->pEList );
97041202ccaSdrh         if( eDest==SRT_Callback ){
971832508b7Sdrh           generateColumnNames(pParse, p->base, 0, p->pEList);
97241202ccaSdrh         }
97382c3d636Sdrh         iBreak = sqliteVdbeMakeLabel(v);
9746b56344dSdrh         iCont = sqliteVdbeMakeLabel(v);
9756b56344dSdrh         sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
9766b56344dSdrh         iStart = sqliteVdbeCurrentAddr(v);
97782c3d636Sdrh         rc = selectInnerLoop(pParse, 0, unionTab, p->pEList->nExpr,
978d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
97982c3d636Sdrh                              iCont, iBreak);
98082c3d636Sdrh         if( rc ) return 1;
9816b56344dSdrh         sqliteVdbeResolveLabel(v, iCont);
9826b56344dSdrh         sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
98399fcd718Sdrh         sqliteVdbeResolveLabel(v, iBreak);
98499fcd718Sdrh         sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
985d8bc7086Sdrh         if( p->pOrderBy ){
986d8bc7086Sdrh           generateSortTail(v, p->pEList->nExpr);
987d8bc7086Sdrh         }
98882c3d636Sdrh       }
98982c3d636Sdrh       break;
99082c3d636Sdrh     }
99182c3d636Sdrh     case TK_INTERSECT: {
99282c3d636Sdrh       int tab1, tab2;
9936b56344dSdrh       int iCont, iBreak, iStart;
99482c3d636Sdrh 
995d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
9966206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
997d8bc7086Sdrh       ** by allocating the tables we will need.
998d8bc7086Sdrh       */
99982c3d636Sdrh       tab1 = pParse->nTab++;
100082c3d636Sdrh       tab2 = pParse->nTab++;
1001d8bc7086Sdrh       if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
1002d8bc7086Sdrh         return 1;
1003d8bc7086Sdrh       }
1004c6b52df3Sdrh       sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
100599fcd718Sdrh       sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
1006d8bc7086Sdrh 
1007d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1008d8bc7086Sdrh       */
1009832508b7Sdrh       rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
101082c3d636Sdrh       if( rc ) return rc;
1011d8bc7086Sdrh 
1012d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1013d8bc7086Sdrh       */
1014c6b52df3Sdrh       sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
101599fcd718Sdrh       sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
101682c3d636Sdrh       p->pPrior = 0;
1017832508b7Sdrh       rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0);
101882c3d636Sdrh       p->pPrior = pPrior;
101982c3d636Sdrh       if( rc ) return rc;
1020d8bc7086Sdrh 
1021d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1022d8bc7086Sdrh       ** tables.
1023d8bc7086Sdrh       */
102482c3d636Sdrh       assert( p->pEList );
102541202ccaSdrh       if( eDest==SRT_Callback ){
1026832508b7Sdrh         generateColumnNames(pParse, p->base, 0, p->pEList);
102741202ccaSdrh       }
102882c3d636Sdrh       iBreak = sqliteVdbeMakeLabel(v);
10296b56344dSdrh       iCont = sqliteVdbeMakeLabel(v);
10306b56344dSdrh       sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
10316b56344dSdrh       iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
103299fcd718Sdrh       sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
103382c3d636Sdrh       rc = selectInnerLoop(pParse, 0, tab1, p->pEList->nExpr,
1034d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
103582c3d636Sdrh                              iCont, iBreak);
103682c3d636Sdrh       if( rc ) return 1;
10376b56344dSdrh       sqliteVdbeResolveLabel(v, iCont);
10386b56344dSdrh       sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
103999fcd718Sdrh       sqliteVdbeResolveLabel(v, iBreak);
104099fcd718Sdrh       sqliteVdbeAddOp(v, OP_Close, tab2, 0);
104199fcd718Sdrh       sqliteVdbeAddOp(v, OP_Close, tab1, 0);
1042d8bc7086Sdrh       if( p->pOrderBy ){
1043d8bc7086Sdrh         generateSortTail(v, p->pEList->nExpr);
1044d8bc7086Sdrh       }
104582c3d636Sdrh       break;
104682c3d636Sdrh     }
104782c3d636Sdrh   }
104882c3d636Sdrh   assert( p->pEList && pPrior->pEList );
104982c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
1050d8bc7086Sdrh     sqliteSetString(&pParse->zErrMsg, "SELECTs to the left and right of ",
1051d8bc7086Sdrh       selectOpName(p->op), " do not have the same number of result columns", 0);
105282c3d636Sdrh     pParse->nErr++;
105382c3d636Sdrh     return 1;
10542282792aSdrh   }
105510e5e3cfSdrh   pParse->nTab = base;
10562282792aSdrh   return 0;
10572282792aSdrh }
10582282792aSdrh 
10592282792aSdrh /*
1060832508b7Sdrh ** Recursively scan through an expression tree.  For every reference
1061832508b7Sdrh ** to a column in table number iFrom, change that reference to the
1062832508b7Sdrh ** same column in table number iTo.
1063832508b7Sdrh */
1064832508b7Sdrh static void changeTables(Expr *pExpr, int iFrom, int iTo){
1065832508b7Sdrh   if( pExpr==0 ) return;
1066832508b7Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iFrom ){
1067832508b7Sdrh     pExpr->iTable = iTo;
1068832508b7Sdrh   }else{
10691b2e0329Sdrh     static void changeTablesInList(ExprList*, int, int);
1070832508b7Sdrh     changeTables(pExpr->pLeft, iFrom, iTo);
1071832508b7Sdrh     changeTables(pExpr->pRight, iFrom, iTo);
10721b2e0329Sdrh     changeTablesInList(pExpr->pList, iFrom, iTo);
1073832508b7Sdrh   }
1074832508b7Sdrh }
10751b2e0329Sdrh static void changeTablesInList(ExprList *pList, int iFrom, int iTo){
10761b2e0329Sdrh   if( pList ){
10771b2e0329Sdrh     int i;
10781b2e0329Sdrh     for(i=0; i<pList->nExpr; i++){
10791b2e0329Sdrh       changeTables(pList->a[i].pExpr, iFrom, iTo);
10801b2e0329Sdrh     }
1081832508b7Sdrh   }
1082832508b7Sdrh }
1083832508b7Sdrh 
1084832508b7Sdrh /*
1085832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
1086832508b7Sdrh ** a column in table number iTable with a copy of the corresponding
108784e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
108884e59207Sdrh ** unchanged.)  When making a copy of an expression in pEList, change
108984e59207Sdrh ** references to columns in table iSub into references to table iTable.
1090832508b7Sdrh **
1091832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
1092832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
1093832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
1094832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
1095832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
1096832508b7Sdrh ** of the subquery rather the result set of the subquery.
1097832508b7Sdrh */
1098832508b7Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList, int iSub){
1099832508b7Sdrh   if( pExpr==0 ) return;
110084e59207Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable && pExpr->iColumn>=0 ){
1101832508b7Sdrh     Expr *pNew;
110284e59207Sdrh     assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1103832508b7Sdrh     assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1104832508b7Sdrh     pNew = pEList->a[pExpr->iColumn].pExpr;
1105832508b7Sdrh     assert( pNew!=0 );
1106832508b7Sdrh     pExpr->op = pNew->op;
1107832508b7Sdrh     pExpr->pLeft = sqliteExprDup(pNew->pLeft);
1108832508b7Sdrh     pExpr->pRight = sqliteExprDup(pNew->pRight);
1109832508b7Sdrh     pExpr->pList = sqliteExprListDup(pNew->pList);
1110832508b7Sdrh     pExpr->iTable = pNew->iTable;
1111832508b7Sdrh     pExpr->iColumn = pNew->iColumn;
1112832508b7Sdrh     pExpr->iAgg = pNew->iAgg;
11131b2e0329Sdrh     pExpr->token = pNew->token;
1114832508b7Sdrh     if( iSub!=iTable ){
1115832508b7Sdrh       changeTables(pExpr, iSub, iTable);
1116832508b7Sdrh     }
1117832508b7Sdrh   }else{
1118832508b7Sdrh     static void substExprList(ExprList*,int,ExprList*,int);
1119832508b7Sdrh     substExpr(pExpr->pLeft, iTable, pEList, iSub);
1120832508b7Sdrh     substExpr(pExpr->pRight, iTable, pEList, iSub);
1121832508b7Sdrh     substExprList(pExpr->pList, iTable, pEList, iSub);
1122832508b7Sdrh   }
1123832508b7Sdrh }
1124832508b7Sdrh static void
1125832508b7Sdrh substExprList(ExprList *pList, int iTable, ExprList *pEList, int iSub){
1126832508b7Sdrh   int i;
1127832508b7Sdrh   if( pList==0 ) return;
1128832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
1129832508b7Sdrh     substExpr(pList->a[i].pExpr, iTable, pEList, iSub);
1130832508b7Sdrh   }
1131832508b7Sdrh }
1132832508b7Sdrh 
1133832508b7Sdrh /*
11341350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
11351350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
11361350b030Sdrh ** occurs.
11371350b030Sdrh **
11381350b030Sdrh ** To understand the concept of flattening, consider the following
11391350b030Sdrh ** query:
11401350b030Sdrh **
11411350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
11421350b030Sdrh **
11431350b030Sdrh ** The default way of implementing this query is to execute the
11441350b030Sdrh ** subquery first and store the results in a temporary table, then
11451350b030Sdrh ** run the outer query on that temporary table.  This requires two
11461350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
11471350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
1148832508b7Sdrh ** optimized.
11491350b030Sdrh **
1150832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
11511350b030Sdrh ** a single flat select, like this:
11521350b030Sdrh **
11531350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
11541350b030Sdrh **
11551350b030Sdrh ** The code generated for this simpification gives the same result
1156832508b7Sdrh ** but only has to scan the data once.  And because indices might
1157832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
1158832508b7Sdrh ** avoided.
11591350b030Sdrh **
1160832508b7Sdrh ** Flattening is only attempted if all of the following are true:
11611350b030Sdrh **
1162832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
11631350b030Sdrh **
1164832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
1165832508b7Sdrh **
1166832508b7Sdrh **   (3)  The subquery is not a join.
1167832508b7Sdrh **
1168832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
1169832508b7Sdrh **
1170832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
1171832508b7Sdrh **        aggregates.
1172832508b7Sdrh **
1173832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
1174832508b7Sdrh **        DISTINCT.
1175832508b7Sdrh **
117608192d5fSdrh **   (7)  The subquery has a FROM clause.
117708192d5fSdrh **
1178832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
1179832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
1180832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1181832508b7Sdrh **
1182832508b7Sdrh ** If flattening is not attempted, this routine is a no-op and return 0.
1183832508b7Sdrh ** If flattening is attempted this routine returns 1.
1184832508b7Sdrh **
1185832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
1186832508b7Sdrh ** the subquery before this routine runs.
11871350b030Sdrh */
1188832508b7Sdrh int flattenSubquery(Select *p, int iFrom, int isAgg, int subqueryIsAgg){
11890bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
1190ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
1191ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
11920bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
1193832508b7Sdrh   int i;
1194832508b7Sdrh   int iParent, iSub;
1195832508b7Sdrh   Expr *pWhere;
11961350b030Sdrh 
1197832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
1198832508b7Sdrh   */
1199832508b7Sdrh   if( p==0 ) return 0;
1200832508b7Sdrh   pSrc = p->pSrc;
1201ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
1202832508b7Sdrh   pSub = pSrc->a[iFrom].pSelect;
1203832508b7Sdrh   assert( pSub!=0 );
1204832508b7Sdrh   if( isAgg && subqueryIsAgg ) return 0;
1205ad3cab52Sdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
1206832508b7Sdrh   pSubSrc = pSub->pSrc;
1207832508b7Sdrh   assert( pSubSrc );
1208ad3cab52Sdrh   if( pSubSrc->nSrc!=1 ) return 0;
1209ad3cab52Sdrh   if( pSub->isDistinct && pSrc->nSrc>1 ) return 0;
1210832508b7Sdrh   if( pSub->isDistinct && isAgg ) return 0;
1211832508b7Sdrh   if( p->isDistinct && subqueryIsAgg ) return 0;
1212832508b7Sdrh 
12130bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
1214832508b7Sdrh   ** i-th entry of the FROM clause in the outer query.
1215832508b7Sdrh   */
1216832508b7Sdrh   iParent = p->base + iFrom;
1217832508b7Sdrh   iSub = pSub->base;
1218832508b7Sdrh   substExprList(p->pEList, iParent, pSub->pEList, iSub);
1219832508b7Sdrh   pList = p->pEList;
1220832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
1221832508b7Sdrh     if( pList->a[i].zName==0 ){
1222832508b7Sdrh       Expr *pExpr = pList->a[i].pExpr;
1223832508b7Sdrh       pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
1224832508b7Sdrh     }
1225832508b7Sdrh   }
12261b2e0329Sdrh   if( isAgg ){
1227832508b7Sdrh     substExprList(p->pGroupBy, iParent, pSub->pEList, iSub);
1228832508b7Sdrh     substExpr(p->pHaving, iParent, pSub->pEList, iSub);
12291b2e0329Sdrh   }
1230832508b7Sdrh   substExprList(p->pOrderBy, iParent, pSub->pEList, iSub);
1231832508b7Sdrh   if( pSub->pWhere ){
1232832508b7Sdrh     pWhere = sqliteExprDup(pSub->pWhere);
1233832508b7Sdrh     if( iParent!=iSub ){
1234832508b7Sdrh       changeTables(pWhere, iSub, iParent);
1235832508b7Sdrh     }
1236832508b7Sdrh   }else{
1237832508b7Sdrh     pWhere = 0;
1238832508b7Sdrh   }
1239832508b7Sdrh   if( subqueryIsAgg ){
1240832508b7Sdrh     assert( p->pHaving==0 );
12411b2e0329Sdrh     p->pHaving = p->pWhere;
12421b2e0329Sdrh     p->pWhere = pWhere;
1243832508b7Sdrh     substExpr(p->pHaving, iParent, pSub->pEList, iSub);
12441b2e0329Sdrh     if( pSub->pHaving ){
12451b2e0329Sdrh       Expr *pHaving = sqliteExprDup(pSub->pHaving);
12461b2e0329Sdrh       if( iParent!=iSub ){
12471b2e0329Sdrh         changeTables(pHaving, iSub, iParent);
12481b2e0329Sdrh       }
12491b2e0329Sdrh       if( p->pHaving ){
12501b2e0329Sdrh         p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0);
12511b2e0329Sdrh       }else{
12521b2e0329Sdrh         p->pHaving = pHaving;
12531b2e0329Sdrh       }
12541b2e0329Sdrh     }
12551b2e0329Sdrh     assert( p->pGroupBy==0 );
12561b2e0329Sdrh     p->pGroupBy = sqliteExprListDup(pSub->pGroupBy);
12571b2e0329Sdrh     if( iParent!=iSub ){
12581b2e0329Sdrh       changeTablesInList(p->pGroupBy, iSub, iParent);
12591b2e0329Sdrh     }
1260832508b7Sdrh   }else if( p->pWhere==0 ){
1261832508b7Sdrh     p->pWhere = pWhere;
1262832508b7Sdrh   }else{
1263832508b7Sdrh     substExpr(p->pWhere, iParent, pSub->pEList, iSub);
1264832508b7Sdrh     if( pWhere ){
1265832508b7Sdrh       p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0);
1266832508b7Sdrh     }
1267832508b7Sdrh   }
1268832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
1269832508b7Sdrh   if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
1270832508b7Sdrh     sqliteDeleteTable(0, pSrc->a[iFrom].pTab);
1271832508b7Sdrh   }
1272832508b7Sdrh   pSrc->a[iFrom].pTab = pSubSrc->a[0].pTab;
1273832508b7Sdrh   pSubSrc->a[0].pTab = 0;
1274832508b7Sdrh   pSrc->a[iFrom].pSelect = pSubSrc->a[0].pSelect;
1275832508b7Sdrh   pSubSrc->a[0].pSelect = 0;
1276832508b7Sdrh   sqliteSelectDelete(pSub);
1277832508b7Sdrh   return 1;
12781350b030Sdrh }
12791350b030Sdrh 
12801350b030Sdrh /*
12819562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it
12829562b551Sdrh ** is a simple min() or max() query.  If it is and this query can be
12839562b551Sdrh ** satisfied using a single seek to the beginning or end of an index,
12849562b551Sdrh ** then generate the code for this SELECT return 1.  If this is not a
12859562b551Sdrh ** simple min() or max() query, then return 0;
12869562b551Sdrh **
12879562b551Sdrh ** A simply min() or max() query looks like this:
12889562b551Sdrh **
12899562b551Sdrh **    SELECT min(a) FROM table;
12909562b551Sdrh **    SELECT max(a) FROM table;
12919562b551Sdrh **
12929562b551Sdrh ** The query may have only a single table in its FROM argument.  There
12939562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
12949562b551Sdrh ** be the min() or max() of a single column of the table.  The column
12959562b551Sdrh ** in the min() or max() function must be indexed.
12969562b551Sdrh **
12979562b551Sdrh ** The parameters to this routine are the same as for sqliteSelect().
12989562b551Sdrh ** See the header comment on that routine for additional information.
12999562b551Sdrh */
13009562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
13019562b551Sdrh   Expr *pExpr;
13029562b551Sdrh   int iCol;
13039562b551Sdrh   Table *pTab;
13049562b551Sdrh   Index *pIdx;
13059562b551Sdrh   int base;
13069562b551Sdrh   Vdbe *v;
13079562b551Sdrh   int openOp;
13089562b551Sdrh   int seekOp;
13099562b551Sdrh   int cont;
13109562b551Sdrh   ExprList eList;
13119562b551Sdrh   struct ExprList_item eListItem;
13129562b551Sdrh 
13139562b551Sdrh   /* Check to see if this query is a simple min() or max() query.  Return
13149562b551Sdrh   ** zero if it is  not.
13159562b551Sdrh   */
13169562b551Sdrh   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
1317ad3cab52Sdrh   if( p->pSrc->nSrc!=1 ) return 0;
13189562b551Sdrh   if( p->pEList->nExpr!=1 ) return 0;
13199562b551Sdrh   pExpr = p->pEList->a[0].pExpr;
13209562b551Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
13219562b551Sdrh   if( pExpr->pList==0 || pExpr->pList->nExpr!=1 ) return 0;
13220bce8354Sdrh   if( pExpr->token.n!=3 ) return 0;
13230bce8354Sdrh   if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){
13240bce8354Sdrh     seekOp = OP_Rewind;
13250bce8354Sdrh   }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){
13260bce8354Sdrh     seekOp = OP_Last;
13270bce8354Sdrh   }else{
13280bce8354Sdrh     return 0;
13290bce8354Sdrh   }
13309562b551Sdrh   pExpr = pExpr->pList->a[0].pExpr;
13319562b551Sdrh   if( pExpr->op!=TK_COLUMN ) return 0;
13329562b551Sdrh   iCol = pExpr->iColumn;
13339562b551Sdrh   pTab = p->pSrc->a[0].pTab;
13349562b551Sdrh 
13359562b551Sdrh   /* If we get to here, it means the query is of the correct form.
133617f71934Sdrh   ** Check to make sure we have an index and make pIdx point to the
133717f71934Sdrh   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
133817f71934Sdrh   ** key column, no index is necessary so set pIdx to NULL.  If no
133917f71934Sdrh   ** usable index is found, return 0.
13409562b551Sdrh   */
13419562b551Sdrh   if( iCol<0 ){
13429562b551Sdrh     pIdx = 0;
13439562b551Sdrh   }else{
13449562b551Sdrh     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
13459562b551Sdrh       assert( pIdx->nColumn>=1 );
13469562b551Sdrh       if( pIdx->aiColumn[0]==iCol ) break;
13479562b551Sdrh     }
13489562b551Sdrh     if( pIdx==0 ) return 0;
13499562b551Sdrh   }
13509562b551Sdrh 
135117f71934Sdrh   /* Identify column names if we will be using the callback.  This
13529562b551Sdrh   ** step is skipped if the output is going to a table or a memory cell.
13539562b551Sdrh   */
13549562b551Sdrh   v = sqliteGetVdbe(pParse);
13559562b551Sdrh   if( v==0 ) return 0;
13569562b551Sdrh   if( eDest==SRT_Callback ){
1357832508b7Sdrh     generateColumnNames(pParse, p->base, p->pSrc, p->pEList);
13589562b551Sdrh   }
13599562b551Sdrh 
136017f71934Sdrh   /* Generating code to find the min or the max.  Basically all we have
136117f71934Sdrh   ** to do is find the first or the last entry in the chosen index.  If
136217f71934Sdrh   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
136317f71934Sdrh   ** or last entry in the main table.
13649562b551Sdrh   */
13655cf8e8c7Sdrh   if( !pParse->schemaVerified && (pParse->db->flags & SQLITE_InTrans)==0 ){
13665cf8e8c7Sdrh     sqliteVdbeAddOp(v, OP_VerifyCookie, pParse->db->schema_cookie, 0);
13675cf8e8c7Sdrh     pParse->schemaVerified = 1;
13685cf8e8c7Sdrh   }
13699562b551Sdrh   openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
1370832508b7Sdrh   base = p->base;
13719562b551Sdrh   sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
13725cf8e8c7Sdrh   sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
13739562b551Sdrh   if( pIdx==0 ){
13749562b551Sdrh     sqliteVdbeAddOp(v, seekOp, base, 0);
13759562b551Sdrh   }else{
13769562b551Sdrh     sqliteVdbeAddOp(v, openOp, base+1, pIdx->tnum);
13775cf8e8c7Sdrh     sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
13789562b551Sdrh     sqliteVdbeAddOp(v, seekOp, base+1, 0);
13799562b551Sdrh     sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
13809562b551Sdrh     sqliteVdbeAddOp(v, OP_Close, base+1, 0);
13819562b551Sdrh     sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
13829562b551Sdrh   }
13835cf8e8c7Sdrh   eList.nExpr = 1;
13845cf8e8c7Sdrh   memset(&eListItem, 0, sizeof(eListItem));
13855cf8e8c7Sdrh   eList.a = &eListItem;
13865cf8e8c7Sdrh   eList.a[0].pExpr = pExpr;
13879562b551Sdrh   cont = sqliteVdbeMakeLabel(v);
13889562b551Sdrh   selectInnerLoop(pParse, &eList, base, 1, 0, -1, eDest, iParm, cont, cont);
13899562b551Sdrh   sqliteVdbeResolveLabel(v, cont);
13909562b551Sdrh   sqliteVdbeAddOp(v, OP_Close, base, 0);
13919562b551Sdrh   return 1;
13929562b551Sdrh }
13939562b551Sdrh 
13949562b551Sdrh /*
13959bb61fe7Sdrh ** Generate code for the given SELECT statement.
13969bb61fe7Sdrh **
1397fef5208cSdrh ** The results are distributed in various ways depending on the
1398fef5208cSdrh ** value of eDest and iParm.
1399fef5208cSdrh **
1400fef5208cSdrh **     eDest Value       Result
1401fef5208cSdrh **     ------------    -------------------------------------------
1402fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
1403fef5208cSdrh **
1404fef5208cSdrh **     SRT_Mem         Store first result in memory cell iParm
1405fef5208cSdrh **
1406fef5208cSdrh **     SRT_Set         Store results as keys of a table with cursor iParm
1407fef5208cSdrh **
140882c3d636Sdrh **     SRT_Union       Store results as a key in a temporary table iParm
140982c3d636Sdrh **
1410c4a3c779Sdrh **     SRT_Except      Remove results form the temporary table iParm.
1411c4a3c779Sdrh **
1412c4a3c779Sdrh **     SRT_Table       Store results in temporary table iParm
14139bb61fe7Sdrh **
14149bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
14159bb61fe7Sdrh ** encountered, then an appropriate error message is left in
14169bb61fe7Sdrh ** pParse->zErrMsg.
14179bb61fe7Sdrh **
14189bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
14199bb61fe7Sdrh ** calling function needs to do that.
14201b2e0329Sdrh **
14211b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
14221b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
14231b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
14241b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
14251b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
14261b2e0329Sdrh ** can be changed.
14279bb61fe7Sdrh */
14289bb61fe7Sdrh int sqliteSelect(
1429cce7d176Sdrh   Parse *pParse,         /* The parser context */
14309bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
143182c3d636Sdrh   int eDest,             /* One of: SRT_Callback Mem Set Union Except */
1432832508b7Sdrh   int iParm,             /* Save result in this memory location, if >=0 */
1433832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
1434832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
14351b2e0329Sdrh   int *pParentAgg        /* True if pParent uses aggregate functions */
1436cce7d176Sdrh ){
1437d8bc7086Sdrh   int i;
1438cce7d176Sdrh   WhereInfo *pWInfo;
1439cce7d176Sdrh   Vdbe *v;
1440cce7d176Sdrh   int isAgg = 0;         /* True for select lists like "count(*)" */
1441a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
1442ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
14439bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
14449bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
14452282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
14462282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
144719a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
144819a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
144910e5e3cfSdrh   int base;              /* First cursor available for use */
14501d83f052Sdrh   int rc = 1;            /* Value to return from this function */
14519bb61fe7Sdrh 
1452daffd0e5Sdrh   if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
1453daffd0e5Sdrh 
145482c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
145582c3d636Sdrh   */
145682c3d636Sdrh   if( p->pPrior ){
145782c3d636Sdrh     return multiSelect(pParse, p, eDest, iParm);
145882c3d636Sdrh   }
145982c3d636Sdrh 
146082c3d636Sdrh   /* Make local copies of the parameters for this query.
146182c3d636Sdrh   */
14629bb61fe7Sdrh   pTabList = p->pSrc;
14639bb61fe7Sdrh   pWhere = p->pWhere;
14649bb61fe7Sdrh   pOrderBy = p->pOrderBy;
14652282792aSdrh   pGroupBy = p->pGroupBy;
14662282792aSdrh   pHaving = p->pHaving;
146719a775c2Sdrh   isDistinct = p->isDistinct;
14689bb61fe7Sdrh 
1469832508b7Sdrh   /* Allocate a block of VDBE cursors, one for each table in the FROM clause.
1470832508b7Sdrh   ** The WHERE processing requires that the cursors for the tables in the
1471832508b7Sdrh   ** FROM clause be consecutive.
147210e5e3cfSdrh   */
1473832508b7Sdrh   base = p->base = pParse->nTab;
1474ad3cab52Sdrh   pParse->nTab += pTabList->nSrc;
147510e5e3cfSdrh 
14769bb61fe7Sdrh   /*
14779bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
14789bb61fe7Sdrh   ** errors before this routine starts.
14799bb61fe7Sdrh   */
14801d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
1481cce7d176Sdrh 
1482d8bc7086Sdrh   /* Look up every table in the table list and create an appropriate
1483d8bc7086Sdrh   ** columnlist in pEList if there isn't one already.  (The parser leaves
1484967e8b73Sdrh   ** a NULL in the p->pEList if the SQL said "SELECT * FROM ...")
1485cce7d176Sdrh   */
1486d8bc7086Sdrh   if( fillInColumnList(pParse, p) ){
14871d83f052Sdrh     goto select_end;
1488cce7d176Sdrh   }
1489ad2d8307Sdrh   pWhere = p->pWhere;
1490d8bc7086Sdrh   pEList = p->pEList;
14911d83f052Sdrh   if( pEList==0 ) goto select_end;
1492cce7d176Sdrh 
14932282792aSdrh   /* If writing to memory or generating a set
14942282792aSdrh   ** only a single column may be output.
149519a775c2Sdrh   */
1496fef5208cSdrh   if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
149719a775c2Sdrh     sqliteSetString(&pParse->zErrMsg, "only a single result allowed for "
149819a775c2Sdrh        "a SELECT that is part of an expression", 0);
149919a775c2Sdrh     pParse->nErr++;
15001d83f052Sdrh     goto select_end;
150119a775c2Sdrh   }
150219a775c2Sdrh 
15032282792aSdrh   /* ORDER BY is ignored if we are not sending the result to a callback.
15042282792aSdrh   */
15052282792aSdrh   if( eDest!=SRT_Callback ){
1506acd4c695Sdrh     pOrderBy = 0;
15072282792aSdrh   }
15082282792aSdrh 
150910e5e3cfSdrh   /* At this point, we should have allocated all the cursors that we
1510832508b7Sdrh   ** need to handle subquerys and temporary tables.
151110e5e3cfSdrh   **
1512967e8b73Sdrh   ** Resolve the column names and do a semantics check on all the expressions.
15132282792aSdrh   */
15144794b980Sdrh   for(i=0; i<pEList->nExpr; i++){
1515832508b7Sdrh     if( sqliteExprResolveIds(pParse, base, pTabList, 0, pEList->a[i].pExpr) ){
15161d83f052Sdrh       goto select_end;
1517cce7d176Sdrh     }
15182282792aSdrh     if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
15191d83f052Sdrh       goto select_end;
1520cce7d176Sdrh     }
1521cce7d176Sdrh   }
1522cce7d176Sdrh   if( pWhere ){
1523832508b7Sdrh     if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pWhere) ){
15241d83f052Sdrh       goto select_end;
1525cce7d176Sdrh     }
1526cce7d176Sdrh     if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
15271d83f052Sdrh       goto select_end;
1528cce7d176Sdrh     }
1529cce7d176Sdrh   }
1530cce7d176Sdrh   if( pOrderBy ){
1531cce7d176Sdrh     for(i=0; i<pOrderBy->nExpr; i++){
15322282792aSdrh       Expr *pE = pOrderBy->a[i].pExpr;
15339208643dSdrh       if( sqliteExprIsConstant(pE) ){
1534*e4de1febSdrh         int iCol;
1535*e4de1febSdrh         if( sqliteExprIsInteger(pE, &iCol)==0 ){
15369208643dSdrh           sqliteSetString(&pParse->zErrMsg,
1537*e4de1febSdrh                "ORDER BY terms must not be non-integer constants", 0);
15389208643dSdrh           pParse->nErr++;
15391d83f052Sdrh           goto select_end;
1540*e4de1febSdrh         }else if( iCol<=0 || iCol>pEList->nExpr ){
1541*e4de1febSdrh           char zBuf[2000];
1542*e4de1febSdrh           sprintf(zBuf,"ORDER BY column number %d out of range - should be "
1543*e4de1febSdrh              "between 1 and %d", iCol, pEList->nExpr);
1544*e4de1febSdrh           sqliteSetString(&pParse->zErrMsg, zBuf, 0);
1545*e4de1febSdrh           pParse->nErr++;
1546*e4de1febSdrh           goto select_end;
1547*e4de1febSdrh         }
1548*e4de1febSdrh         sqliteExprDelete(pE);
1549*e4de1febSdrh         pE = pOrderBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
15509208643dSdrh       }
1551832508b7Sdrh       if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
15521d83f052Sdrh         goto select_end;
1553cce7d176Sdrh       }
15542282792aSdrh       if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
15551d83f052Sdrh         goto select_end;
1556cce7d176Sdrh       }
1557cce7d176Sdrh     }
1558cce7d176Sdrh   }
15592282792aSdrh   if( pGroupBy ){
15602282792aSdrh     for(i=0; i<pGroupBy->nExpr; i++){
15612282792aSdrh       Expr *pE = pGroupBy->a[i].pExpr;
15629208643dSdrh       if( sqliteExprIsConstant(pE) ){
15639208643dSdrh         sqliteSetString(&pParse->zErrMsg,
15649208643dSdrh              "GROUP BY expressions should not be constant", 0);
15659208643dSdrh         pParse->nErr++;
15661d83f052Sdrh         goto select_end;
15679208643dSdrh       }
1568832508b7Sdrh       if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
15691d83f052Sdrh         goto select_end;
15702282792aSdrh       }
15712282792aSdrh       if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
15721d83f052Sdrh         goto select_end;
15732282792aSdrh       }
15742282792aSdrh     }
15752282792aSdrh   }
15762282792aSdrh   if( pHaving ){
15772282792aSdrh     if( pGroupBy==0 ){
1578da93281eSdrh       sqliteSetString(&pParse->zErrMsg, "a GROUP BY clause is required "
1579da93281eSdrh          "before HAVING", 0);
15802282792aSdrh       pParse->nErr++;
15811d83f052Sdrh       goto select_end;
15822282792aSdrh     }
1583832508b7Sdrh     if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pHaving) ){
15841d83f052Sdrh       goto select_end;
15852282792aSdrh     }
1586da93281eSdrh     if( sqliteExprCheck(pParse, pHaving, isAgg, 0) ){
15871d83f052Sdrh       goto select_end;
15882282792aSdrh     }
1589cce7d176Sdrh   }
1590cce7d176Sdrh 
15919562b551Sdrh   /* Check for the special case of a min() or max() function by itself
15929562b551Sdrh   ** in the result set.
15939562b551Sdrh   */
15949562b551Sdrh   if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
15955cf8e8c7Sdrh     rc = 0;
15969562b551Sdrh     goto select_end;
15979562b551Sdrh   }
15989562b551Sdrh 
1599d820cb1bSdrh   /* Begin generating code.
1600d820cb1bSdrh   */
1601d820cb1bSdrh   v = sqliteGetVdbe(pParse);
1602d820cb1bSdrh   if( v==0 ) goto select_end;
1603d820cb1bSdrh 
16040bb28106Sdrh   /* Identify column names if we will be using in the callback.  This
16050bb28106Sdrh   ** step is skipped if the output is going to a table or a memory cell.
16060bb28106Sdrh   */
16070bb28106Sdrh   if( eDest==SRT_Callback ){
16080bb28106Sdrh     generateColumnNames(pParse, p->base, pTabList, pEList);
16090bb28106Sdrh   }
16100bb28106Sdrh 
16110bb28106Sdrh   /* Set the limiter
16120bb28106Sdrh   */
16130bb28106Sdrh   if( p->nLimit<=0 ){
16140bb28106Sdrh     p->nOffset = 0;
16150bb28106Sdrh   }else{
16160bb28106Sdrh     if( p->nOffset<0 ) p->nOffset = 0;
16170bb28106Sdrh     sqliteVdbeAddOp(v, OP_Limit, p->nLimit, p->nOffset);
16180bb28106Sdrh   }
16190bb28106Sdrh 
1620d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
1621d820cb1bSdrh   */
1622ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
1623a76b5dfcSdrh     if( pTabList->a[i].pSelect==0 ) continue;
16242d0794e3Sdrh     sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable, base+i,
16251b2e0329Sdrh                  p, i, &isAgg);
1626832508b7Sdrh     pTabList = p->pSrc;
1627832508b7Sdrh     pWhere = p->pWhere;
1628acd4c695Sdrh     if( eDest==SRT_Callback ){
1629832508b7Sdrh       pOrderBy = p->pOrderBy;
1630acd4c695Sdrh     }
1631832508b7Sdrh     pGroupBy = p->pGroupBy;
1632832508b7Sdrh     pHaving = p->pHaving;
1633832508b7Sdrh     isDistinct = p->isDistinct;
16341b2e0329Sdrh   }
16351b2e0329Sdrh 
16361b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
16371b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
16381b2e0329Sdrh   */
16391b2e0329Sdrh   if( pParent && pParentAgg &&
16401b2e0329Sdrh       flattenSubquery(pParent, parentTab, *pParentAgg, isAgg) ){
16411b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
16421b2e0329Sdrh     return rc;
16431b2e0329Sdrh   }
1644832508b7Sdrh 
16452d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
16462d0794e3Sdrh   */
16472d0794e3Sdrh   if( eDest==SRT_TempTable ){
16482d0794e3Sdrh     sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
16492d0794e3Sdrh   }
16502d0794e3Sdrh 
16512282792aSdrh   /* Do an analysis of aggregate expressions.
1652efb7251dSdrh   */
1653d820cb1bSdrh   sqliteAggregateInfoReset(pParse);
16542282792aSdrh   if( isAgg ){
16550bce8354Sdrh     assert( pParse->nAgg==0 );
16562282792aSdrh     for(i=0; i<pEList->nExpr; i++){
16572282792aSdrh       if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
16581d83f052Sdrh         goto select_end;
16592282792aSdrh       }
16602282792aSdrh     }
16612282792aSdrh     if( pGroupBy ){
16622282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
16632282792aSdrh         if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
16641d83f052Sdrh           goto select_end;
16652282792aSdrh         }
16662282792aSdrh       }
16672282792aSdrh     }
16682282792aSdrh     if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
16691d83f052Sdrh       goto select_end;
16702282792aSdrh     }
1671191b690eSdrh     if( pOrderBy ){
1672191b690eSdrh       for(i=0; i<pOrderBy->nExpr; i++){
1673191b690eSdrh         if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
16741d83f052Sdrh           goto select_end;
1675191b690eSdrh         }
1676191b690eSdrh       }
1677191b690eSdrh     }
1678efb7251dSdrh   }
1679efb7251dSdrh 
16802282792aSdrh   /* Reset the aggregator
1681cce7d176Sdrh   */
1682cce7d176Sdrh   if( isAgg ){
168399fcd718Sdrh     sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
1684e5095355Sdrh     for(i=0; i<pParse->nAgg; i++){
16850bce8354Sdrh       FuncDef *pFunc;
16860bce8354Sdrh       if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
16871350b030Sdrh         sqliteVdbeAddOp(v, OP_AggInit, 0, i);
16880bce8354Sdrh         sqliteVdbeChangeP3(v, -1, (char*)pFunc, P3_POINTER);
1689e5095355Sdrh       }
1690e5095355Sdrh     }
16911bee3d7bSdrh     if( pGroupBy==0 ){
16921bee3d7bSdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
16931bee3d7bSdrh       sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
16941bee3d7bSdrh     }
1695cce7d176Sdrh   }
1696cce7d176Sdrh 
169719a775c2Sdrh   /* Initialize the memory cell to NULL
169819a775c2Sdrh   */
1699fef5208cSdrh   if( eDest==SRT_Mem ){
170099fcd718Sdrh     sqliteVdbeAddOp(v, OP_String, 0, 0);
17018721ce4aSdrh     sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
170219a775c2Sdrh   }
170319a775c2Sdrh 
1704832508b7Sdrh   /* Open a temporary table to use for the distinct set.
1705cce7d176Sdrh   */
170619a775c2Sdrh   if( isDistinct ){
1707832508b7Sdrh     distinct = pParse->nTab++;
1708c6b52df3Sdrh     sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
1709832508b7Sdrh   }else{
1710832508b7Sdrh     distinct = -1;
1711efb7251dSdrh   }
1712832508b7Sdrh 
1713832508b7Sdrh   /* Begin the database scan
1714832508b7Sdrh   */
1715832508b7Sdrh   pWInfo = sqliteWhereBegin(pParse, p->base, pTabList, pWhere, 0);
17161d83f052Sdrh   if( pWInfo==0 ) goto select_end;
1717cce7d176Sdrh 
17182282792aSdrh   /* Use the standard inner loop if we are not dealing with
17192282792aSdrh   ** aggregates
1720cce7d176Sdrh   */
1721da9d6c45Sdrh   if( !isAgg ){
172282c3d636Sdrh     if( selectInnerLoop(pParse, pEList, 0, 0, pOrderBy, distinct, eDest, iParm,
17232282792aSdrh                     pWInfo->iContinue, pWInfo->iBreak) ){
17241d83f052Sdrh        goto select_end;
1725cce7d176Sdrh     }
1726da9d6c45Sdrh   }
1727cce7d176Sdrh 
17282282792aSdrh   /* If we are dealing with aggregates, then to the special aggregate
17292282792aSdrh   ** processing.
1730efb7251dSdrh   */
17312282792aSdrh   else{
17322282792aSdrh     if( pGroupBy ){
17331bee3d7bSdrh       int lbl1;
17342282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
17352282792aSdrh         sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
1736efb7251dSdrh       }
173799fcd718Sdrh       sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
17381bee3d7bSdrh       lbl1 = sqliteVdbeMakeLabel(v);
173999fcd718Sdrh       sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
17402282792aSdrh       for(i=0; i<pParse->nAgg; i++){
17412282792aSdrh         if( pParse->aAgg[i].isAgg ) continue;
17422282792aSdrh         sqliteExprCode(pParse, pParse->aAgg[i].pExpr);
174399fcd718Sdrh         sqliteVdbeAddOp(v, OP_AggSet, 0, i);
17442282792aSdrh       }
17452282792aSdrh       sqliteVdbeResolveLabel(v, lbl1);
17462282792aSdrh     }
17472282792aSdrh     for(i=0; i<pParse->nAgg; i++){
17482282792aSdrh       Expr *pE;
17490bce8354Sdrh       int j;
17502282792aSdrh       if( !pParse->aAgg[i].isAgg ) continue;
17512282792aSdrh       pE = pParse->aAgg[i].pExpr;
17522282792aSdrh       assert( pE->op==TK_AGG_FUNCTION );
17530bce8354Sdrh       if( pE->pList ){
1754e5095355Sdrh         for(j=0; j<pE->pList->nExpr; j++){
1755e5095355Sdrh           sqliteExprCode(pParse, pE->pList->a[j].pExpr);
1756e5095355Sdrh         }
17572282792aSdrh       }
17581350b030Sdrh       sqliteVdbeAddOp(v, OP_Integer, i, 0);
1759f55f25f0Sdrh       sqliteVdbeAddOp(v, OP_AggFunc, 0, pE->pList ? pE->pList->nExpr : 0);
17600bce8354Sdrh       assert( pParse->aAgg[i].pFunc!=0 );
17610bce8354Sdrh       assert( pParse->aAgg[i].pFunc->xStep!=0 );
17620bce8354Sdrh       sqliteVdbeChangeP3(v, -1, (char*)pParse->aAgg[i].pFunc, P3_POINTER);
17632282792aSdrh     }
17642282792aSdrh   }
17652282792aSdrh 
1766cce7d176Sdrh   /* End the database scan loop.
1767cce7d176Sdrh   */
1768cce7d176Sdrh   sqliteWhereEnd(pWInfo);
1769cce7d176Sdrh 
17702282792aSdrh   /* If we are processing aggregates, we need to set up a second loop
17712282792aSdrh   ** over all of the aggregate values and process them.
17722282792aSdrh   */
17732282792aSdrh   if( isAgg ){
17742282792aSdrh     int endagg = sqliteVdbeMakeLabel(v);
17752282792aSdrh     int startagg;
177699fcd718Sdrh     startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
17772282792aSdrh     pParse->useAgg = 1;
17782282792aSdrh     if( pHaving ){
1779f5905aa7Sdrh       sqliteExprIfFalse(pParse, pHaving, startagg, 1);
17802282792aSdrh     }
178182c3d636Sdrh     if( selectInnerLoop(pParse, pEList, 0, 0, pOrderBy, distinct, eDest, iParm,
17822282792aSdrh                     startagg, endagg) ){
17831d83f052Sdrh       goto select_end;
17842282792aSdrh     }
178599fcd718Sdrh     sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
178699fcd718Sdrh     sqliteVdbeResolveLabel(v, endagg);
178799fcd718Sdrh     sqliteVdbeAddOp(v, OP_Noop, 0, 0);
17882282792aSdrh     pParse->useAgg = 0;
17892282792aSdrh   }
17902282792aSdrh 
1791cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
1792cce7d176Sdrh   ** and send them to the callback one by one.
1793cce7d176Sdrh   */
1794cce7d176Sdrh   if( pOrderBy ){
1795d8bc7086Sdrh     generateSortTail(v, pEList->nExpr);
1796cce7d176Sdrh   }
17976a535340Sdrh 
17986a535340Sdrh 
17996a535340Sdrh   /* Issue a null callback if that is what the user wants.
18006a535340Sdrh   */
18016a535340Sdrh   if( (pParse->db->flags & SQLITE_NullCallback)!=0 && eDest==SRT_Callback ){
18026a535340Sdrh     sqliteVdbeAddOp(v, OP_NullCallback, pEList->nExpr, 0);
18036a535340Sdrh   }
18046a535340Sdrh 
18051d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
18061d83f052Sdrh   ** to indicate no errors.
18071d83f052Sdrh   */
18081d83f052Sdrh   rc = 0;
18091d83f052Sdrh 
18101d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
18111d83f052Sdrh   ** successful coding of the SELECT.
18121d83f052Sdrh   */
18131d83f052Sdrh select_end:
1814832508b7Sdrh   pParse->nTab = base;
18151d83f052Sdrh   sqliteAggregateInfoReset(pParse);
18161d83f052Sdrh   return rc;
1817cce7d176Sdrh }
1818