xref: /sqlite-3.40.0/src/select.c (revision 4b59ab5e)
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*4b59ab5eSdrh ** $Id: select.c,v 1.108 2002/08/24 18:24:54 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);
159*4b59ab5eSdrh   dummy.base = 1;
160*4b59ab5eSdrh   dummy.dyn = 0;
161ad2d8307Sdrh   pE1a = sqliteExpr(TK_ID, 0, 0, &dummy);
162ad2d8307Sdrh   pE2a = sqliteExpr(TK_ID, 0, 0, &dummy);
163ad2d8307Sdrh   dummy.z = pTab1->zName;
164ad2d8307Sdrh   dummy.n = strlen(dummy.z);
165ad2d8307Sdrh   pE1b = sqliteExpr(TK_ID, 0, 0, &dummy);
166ad2d8307Sdrh   dummy.z = pTab2->zName;
167ad2d8307Sdrh   dummy.n = strlen(dummy.z);
168ad2d8307Sdrh   pE2b = sqliteExpr(TK_ID, 0, 0, &dummy);
169ad2d8307Sdrh   pE1c = sqliteExpr(TK_DOT, pE1b, pE1a, 0);
170ad2d8307Sdrh   pE2c = sqliteExpr(TK_DOT, pE2b, pE2a, 0);
171ad2d8307Sdrh   pE = sqliteExpr(TK_EQ, pE1c, pE2c, 0);
1721cc093c2Sdrh   pE->isJoinExpr = 1;
173ad2d8307Sdrh   if( *ppExpr ){
174ad2d8307Sdrh     *ppExpr = sqliteExpr(TK_AND, *ppExpr, pE, 0);
175ad2d8307Sdrh   }else{
176ad2d8307Sdrh     *ppExpr = pE;
177ad2d8307Sdrh   }
178ad2d8307Sdrh }
179ad2d8307Sdrh 
180ad2d8307Sdrh /*
1811cc093c2Sdrh ** Set the Expr.isJoinExpr flag on all terms of the given expression.
1821cc093c2Sdrh **
1831cc093c2Sdrh ** The Expr.isJoinExpr flag is used at on terms of an expression to tell
1841cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
1851cc093c2Sdrh ** join restriction and not a part of the more general WHERE clause.
1861cc093c2Sdrh */
1871cc093c2Sdrh static void setJoinExpr(Expr *p){
1881cc093c2Sdrh   while( p ){
1891cc093c2Sdrh     p->isJoinExpr = 1;
1901cc093c2Sdrh     setJoinExpr(p->pLeft);
1911cc093c2Sdrh     p = p->pRight;
1921cc093c2Sdrh   }
1931cc093c2Sdrh }
1941cc093c2Sdrh 
1951cc093c2Sdrh /*
196ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
197ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
198ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
199ad2d8307Sdrh **
200ad2d8307Sdrh ** This routine returns the number of errors encountered.
201ad2d8307Sdrh */
202ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
203ad2d8307Sdrh   SrcList *pSrc;
204ad2d8307Sdrh   int i, j;
205ad2d8307Sdrh   pSrc = p->pSrc;
206ad2d8307Sdrh   for(i=0; i<pSrc->nSrc-1; i++){
207ad2d8307Sdrh     struct SrcList_item *pTerm = &pSrc->a[i];
208ad2d8307Sdrh     struct SrcList_item *pOther = &pSrc->a[i+1];
209ad2d8307Sdrh 
210ad2d8307Sdrh     if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
211ad2d8307Sdrh 
212ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
213ad2d8307Sdrh     ** every column that the two tables have in common.
214ad2d8307Sdrh     */
215ad2d8307Sdrh     if( pTerm->jointype & JT_NATURAL ){
216ad2d8307Sdrh       Table *pTab;
217ad2d8307Sdrh       if( pTerm->pOn || pTerm->pUsing ){
218ad2d8307Sdrh         sqliteSetString(&pParse->zErrMsg, "a NATURAL join may not have "
219ad2d8307Sdrh            "an ON or USING clause", 0);
220ad2d8307Sdrh         pParse->nErr++;
221ad2d8307Sdrh         return 1;
222ad2d8307Sdrh       }
223ad2d8307Sdrh       pTab = pTerm->pTab;
224ad2d8307Sdrh       for(j=0; j<pTab->nCol; j++){
225ad2d8307Sdrh         if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
226ad2d8307Sdrh           addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
227ad2d8307Sdrh         }
228ad2d8307Sdrh       }
229ad2d8307Sdrh     }
230ad2d8307Sdrh 
231ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
232ad2d8307Sdrh     */
233ad2d8307Sdrh     if( pTerm->pOn && pTerm->pUsing ){
234ad2d8307Sdrh       sqliteSetString(&pParse->zErrMsg, "cannot have both ON and USING "
235ad2d8307Sdrh         "clauses in the same join", 0);
236ad2d8307Sdrh       pParse->nErr++;
237ad2d8307Sdrh       return 1;
238ad2d8307Sdrh     }
239ad2d8307Sdrh 
240ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
241ad2d8307Sdrh     ** and AND operator.
242ad2d8307Sdrh     */
243ad2d8307Sdrh     if( pTerm->pOn ){
2441cc093c2Sdrh       setJoinExpr(pTerm->pOn);
245ad2d8307Sdrh       if( p->pWhere==0 ){
246ad2d8307Sdrh         p->pWhere = pTerm->pOn;
247ad2d8307Sdrh       }else{
248ad2d8307Sdrh         p->pWhere = sqliteExpr(TK_AND, p->pWhere, pTerm->pOn, 0);
249ad2d8307Sdrh       }
250ad2d8307Sdrh       pTerm->pOn = 0;
251ad2d8307Sdrh     }
252ad2d8307Sdrh 
253ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
254ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
255ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
256ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
257ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
258ad2d8307Sdrh     ** not contained in both tables to be joined.
259ad2d8307Sdrh     */
260ad2d8307Sdrh     if( pTerm->pUsing ){
261ad2d8307Sdrh       IdList *pList;
262ad2d8307Sdrh       int j;
263ad2d8307Sdrh       assert( i<pSrc->nSrc-1 );
264ad2d8307Sdrh       pList = pTerm->pUsing;
265ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
266bf5cd97eSdrh         if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
267bf5cd97eSdrh             columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
268ad2d8307Sdrh           sqliteSetString(&pParse->zErrMsg, "cannot join using column ",
269bf5cd97eSdrh             pList->a[j].zName, " - column not present in both tables", 0);
270ad2d8307Sdrh           pParse->nErr++;
271ad2d8307Sdrh           return 1;
272ad2d8307Sdrh         }
273bf5cd97eSdrh         addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
274ad2d8307Sdrh       }
275ad2d8307Sdrh     }
276ad2d8307Sdrh   }
277ad2d8307Sdrh   return 0;
278ad2d8307Sdrh }
279ad2d8307Sdrh 
280ad2d8307Sdrh /*
2819bb61fe7Sdrh ** Delete the given Select structure and all of its substructures.
2829bb61fe7Sdrh */
2839bb61fe7Sdrh void sqliteSelectDelete(Select *p){
28482c3d636Sdrh   if( p==0 ) return;
2859bb61fe7Sdrh   sqliteExprListDelete(p->pEList);
286ad3cab52Sdrh   sqliteSrcListDelete(p->pSrc);
2879bb61fe7Sdrh   sqliteExprDelete(p->pWhere);
2889bb61fe7Sdrh   sqliteExprListDelete(p->pGroupBy);
2899bb61fe7Sdrh   sqliteExprDelete(p->pHaving);
2909bb61fe7Sdrh   sqliteExprListDelete(p->pOrderBy);
29182c3d636Sdrh   sqliteSelectDelete(p->pPrior);
292a76b5dfcSdrh   sqliteFree(p->zSelect);
2939bb61fe7Sdrh   sqliteFree(p);
2949bb61fe7Sdrh }
2959bb61fe7Sdrh 
2969bb61fe7Sdrh /*
2972282792aSdrh ** Delete the aggregate information from the parse structure.
2982282792aSdrh */
2991d83f052Sdrh static void sqliteAggregateInfoReset(Parse *pParse){
3002282792aSdrh   sqliteFree(pParse->aAgg);
3012282792aSdrh   pParse->aAgg = 0;
3022282792aSdrh   pParse->nAgg = 0;
3032282792aSdrh   pParse->useAgg = 0;
3042282792aSdrh }
3052282792aSdrh 
3062282792aSdrh /*
307c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
308c926afbcSdrh ** stack into the sorter.
309c926afbcSdrh */
310c926afbcSdrh static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
311c926afbcSdrh   char *zSortOrder;
312c926afbcSdrh   int i;
313c926afbcSdrh   zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
314c926afbcSdrh   if( zSortOrder==0 ) return;
315c926afbcSdrh   for(i=0; i<pOrderBy->nExpr; i++){
31638640e15Sdrh     int order = pOrderBy->a[i].sortOrder;
31738640e15Sdrh     int type;
31838640e15Sdrh     int c;
31938640e15Sdrh     if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
32038640e15Sdrh       type = SQLITE_SO_TEXT;
32138640e15Sdrh     }else if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_NUM ){
32238640e15Sdrh       type = SQLITE_SO_NUM;
323491791a8Sdrh     }else if( pParse->db->file_format>=4 ){
32438640e15Sdrh       type = sqliteExprType(pOrderBy->a[i].pExpr);
32538640e15Sdrh     }else{
32638640e15Sdrh       type = SQLITE_SO_NUM;
32738640e15Sdrh     }
32838640e15Sdrh     if( (order & SQLITE_SO_DIRMASK)==SQLITE_SO_ASC ){
32938640e15Sdrh       c = type==SQLITE_SO_TEXT ? 'A' : '+';
33038640e15Sdrh     }else{
33138640e15Sdrh       c = type==SQLITE_SO_TEXT ? 'D' : '-';
33238640e15Sdrh     }
33338640e15Sdrh     zSortOrder[i] = c;
334c926afbcSdrh     sqliteExprCode(pParse, pOrderBy->a[i].pExpr);
335c926afbcSdrh   }
336c926afbcSdrh   zSortOrder[pOrderBy->nExpr] = 0;
337c926afbcSdrh   sqliteVdbeAddOp(v, OP_SortMakeKey, pOrderBy->nExpr, 0);
338c926afbcSdrh   sqliteVdbeChangeP3(v, -1, zSortOrder, strlen(zSortOrder));
339c926afbcSdrh   sqliteFree(zSortOrder);
340c926afbcSdrh   sqliteVdbeAddOp(v, OP_SortPut, 0, 0);
341c926afbcSdrh }
342c926afbcSdrh 
343c926afbcSdrh /*
34438640e15Sdrh ** This routine adds a P3 argument to the last VDBE opcode that was
34538640e15Sdrh ** inserted. The P3 argument added is a string suitable for the
34638640e15Sdrh ** OP_MakeKey or OP_MakeIdxKey opcodes.  The string consists of
34738640e15Sdrh ** characters 't' or 'n' depending on whether or not the various
34838640e15Sdrh ** fields of the key to be generated should be treated as numeric
34938640e15Sdrh ** or as text.  See the OP_MakeKey and OP_MakeIdxKey opcode
35038640e15Sdrh ** documentation for additional information about the P3 string.
35138640e15Sdrh ** See also the sqliteAddIdxKeyType() routine.
35238640e15Sdrh */
35338640e15Sdrh void sqliteAddKeyType(Vdbe *v, ExprList *pEList){
35438640e15Sdrh   int nColumn = pEList->nExpr;
35538640e15Sdrh   char *zType = sqliteMalloc( nColumn+1 );
35638640e15Sdrh   int i;
35738640e15Sdrh   if( zType==0 ) return;
35838640e15Sdrh   for(i=0; i<nColumn; i++){
35938640e15Sdrh     zType[i] = sqliteExprType(pEList->a[i].pExpr)==SQLITE_SO_NUM ? 'n' : 't';
36038640e15Sdrh   }
36138640e15Sdrh   zType[i] = 0;
36238640e15Sdrh   sqliteVdbeChangeP3(v, -1, zType, nColumn);
36338640e15Sdrh   sqliteFree(zType);
36438640e15Sdrh }
36538640e15Sdrh 
36638640e15Sdrh /*
3672282792aSdrh ** This routine generates the code for the inside of the inner loop
3682282792aSdrh ** of a SELECT.
36982c3d636Sdrh **
37038640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
37138640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
37238640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
37338640e15Sdrh ** datatypes for each column.
3742282792aSdrh */
3752282792aSdrh static int selectInnerLoop(
3762282792aSdrh   Parse *pParse,          /* The parser context */
377df199a25Sdrh   Select *p,              /* The complete select statement being coded */
3782282792aSdrh   ExprList *pEList,       /* List of values being extracted */
37982c3d636Sdrh   int srcTab,             /* Pull data from this table */
380967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
3812282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
3822282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
3832282792aSdrh   int eDest,              /* How to dispose of the results */
3842282792aSdrh   int iParm,              /* An argument to the disposal method */
3852282792aSdrh   int iContinue,          /* Jump here to continue with next row */
3862282792aSdrh   int iBreak              /* Jump here to break out of the inner loop */
3872282792aSdrh ){
3882282792aSdrh   Vdbe *v = pParse->pVdbe;
3892282792aSdrh   int i;
39038640e15Sdrh 
391daffd0e5Sdrh   if( v==0 ) return 0;
39238640e15Sdrh   assert( pEList!=0 );
3932282792aSdrh 
394df199a25Sdrh   /* If there was a LIMIT clause on the SELECT statement, then do the check
395df199a25Sdrh   ** to see if this row should be output.
396df199a25Sdrh   */
397df199a25Sdrh   if( pOrderBy==0 ){
398df199a25Sdrh     if( p->nOffset>0 ){
399d11d382cSdrh       int addr = sqliteVdbeCurrentAddr(v);
400d11d382cSdrh       sqliteVdbeAddOp(v, OP_MemIncr, p->nOffset, addr+2);
401d11d382cSdrh       sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
402df199a25Sdrh     }
403d11d382cSdrh     if( p->nLimit>=0 ){
404d11d382cSdrh       sqliteVdbeAddOp(v, OP_MemIncr, p->nLimit, iBreak);
405df199a25Sdrh     }
406df199a25Sdrh   }
407df199a25Sdrh 
408967e8b73Sdrh   /* Pull the requested columns.
4092282792aSdrh   */
41038640e15Sdrh   if( nColumn>0 ){
411967e8b73Sdrh     for(i=0; i<nColumn; i++){
41299fcd718Sdrh       sqliteVdbeAddOp(v, OP_Column, srcTab, i);
41382c3d636Sdrh     }
41438640e15Sdrh   }else{
41538640e15Sdrh     nColumn = pEList->nExpr;
41638640e15Sdrh     for(i=0; i<pEList->nExpr; i++){
41738640e15Sdrh       sqliteExprCode(pParse, pEList->a[i].pExpr);
41838640e15Sdrh     }
41982c3d636Sdrh   }
4202282792aSdrh 
421daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
422daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
423daffd0e5Sdrh   ** part of the result.
4242282792aSdrh   */
425f5905aa7Sdrh   if( distinct>=0 && pEList && pEList->nExpr>0 ){
4260bd1f4eaSdrh #if NULL_ALWAYS_DISTINCT
4270bd1f4eaSdrh     sqliteVdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqliteVdbeCurrentAddr(v)+7);
4280bd1f4eaSdrh #endif
42999fcd718Sdrh     sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
430491791a8Sdrh     if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pEList);
431f5905aa7Sdrh     sqliteVdbeAddOp(v, OP_Distinct, distinct, sqliteVdbeCurrentAddr(v)+3);
43299fcd718Sdrh     sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
43399fcd718Sdrh     sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
43499fcd718Sdrh     sqliteVdbeAddOp(v, OP_String, 0, 0);
4356b12545fSdrh     sqliteVdbeAddOp(v, OP_PutStrKey, distinct, 0);
4362282792aSdrh   }
43782c3d636Sdrh 
438c926afbcSdrh   switch( eDest ){
43982c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
44082c3d636Sdrh     ** table iParm.
4412282792aSdrh     */
442c926afbcSdrh     case SRT_Union: {
4430bd1f4eaSdrh       sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
444f5905aa7Sdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
4456b12545fSdrh       sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
446c926afbcSdrh       break;
447c926afbcSdrh     }
44882c3d636Sdrh 
4495974a30fSdrh     /* Store the result as data using a unique key.
4505974a30fSdrh     */
451c926afbcSdrh     case SRT_Table:
452c926afbcSdrh     case SRT_TempTable: {
45399fcd718Sdrh       sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
454c926afbcSdrh       if( pOrderBy ){
455c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
456c926afbcSdrh       }else{
45799fcd718Sdrh         sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
45899fcd718Sdrh         sqliteVdbeAddOp(v, OP_Pull, 1, 0);
4596b12545fSdrh         sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
460c926afbcSdrh       }
461c926afbcSdrh       break;
462c926afbcSdrh     }
4635974a30fSdrh 
46482c3d636Sdrh     /* Construct a record from the query result, but instead of
46582c3d636Sdrh     ** saving that record, use it as a key to delete elements from
46682c3d636Sdrh     ** the temporary table iParm.
46782c3d636Sdrh     */
468c926afbcSdrh     case SRT_Except: {
4690bd1f4eaSdrh       int addr;
4700bd1f4eaSdrh       addr = sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
47199fcd718Sdrh       sqliteVdbeAddOp(v, OP_NotFound, iParm, addr+3);
47299fcd718Sdrh       sqliteVdbeAddOp(v, OP_Delete, iParm, 0);
473c926afbcSdrh       break;
474c926afbcSdrh     }
4752282792aSdrh 
4762282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
4772282792aSdrh     ** then there should be a single item on the stack.  Write this
4782282792aSdrh     ** item into the set table with bogus data.
4792282792aSdrh     */
480c926afbcSdrh     case SRT_Set: {
481a9f9d1c0Sdrh       int lbl = sqliteVdbeMakeLabel(v);
482967e8b73Sdrh       assert( nColumn==1 );
483a9f9d1c0Sdrh       sqliteVdbeAddOp(v, OP_IsNull, -1, lbl);
484c926afbcSdrh       if( pOrderBy ){
485c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
486c926afbcSdrh       }else{
487a9f9d1c0Sdrh         sqliteVdbeAddOp(v, OP_String, 0, 0);
4886b12545fSdrh         sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
489c926afbcSdrh       }
490a9f9d1c0Sdrh       sqliteVdbeResolveLabel(v, lbl);
491c926afbcSdrh       break;
492c926afbcSdrh     }
49382c3d636Sdrh 
4942282792aSdrh     /* If this is a scalar select that is part of an expression, then
4952282792aSdrh     ** store the results in the appropriate memory cell and break out
4962282792aSdrh     ** of the scan loop.
4972282792aSdrh     */
498c926afbcSdrh     case SRT_Mem: {
499967e8b73Sdrh       assert( nColumn==1 );
500c926afbcSdrh       if( pOrderBy ){
501c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
502c926afbcSdrh       }else{
5038721ce4aSdrh         sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
50499fcd718Sdrh         sqliteVdbeAddOp(v, OP_Goto, 0, iBreak);
505c926afbcSdrh       }
506c926afbcSdrh       break;
507c926afbcSdrh     }
5082282792aSdrh 
509f46f905aSdrh     /* Send the data to the callback function.
510f46f905aSdrh     */
511f46f905aSdrh     case SRT_Callback:
512f46f905aSdrh     case SRT_Sorter: {
513f46f905aSdrh       if( pOrderBy ){
514f46f905aSdrh         sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
515f46f905aSdrh         pushOntoSorter(pParse, v, pOrderBy);
516f46f905aSdrh       }else{
517f46f905aSdrh         assert( eDest==SRT_Callback );
518f46f905aSdrh         sqliteVdbeAddOp(v, OP_Callback, nColumn, 0);
519f46f905aSdrh       }
520f46f905aSdrh       break;
521f46f905aSdrh     }
522f46f905aSdrh 
523d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
524d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
525d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
526d7489c39Sdrh     ** about the actual results of the select.
527d7489c39Sdrh     */
528c926afbcSdrh     default: {
529f46f905aSdrh       assert( eDest==SRT_Discard );
530f46f905aSdrh       sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
531c926afbcSdrh       break;
532c926afbcSdrh     }
533c926afbcSdrh   }
53482c3d636Sdrh   return 0;
53582c3d636Sdrh }
53682c3d636Sdrh 
53782c3d636Sdrh /*
538d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
539d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
540d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
541d8bc7086Sdrh ** routine generates the code needed to do that.
542d8bc7086Sdrh */
543c926afbcSdrh static void generateSortTail(
544c926afbcSdrh   Select *p,       /* The SELECT statement */
545c926afbcSdrh   Vdbe *v,         /* Generate code into this VDBE */
546c926afbcSdrh   int nColumn,     /* Number of columns of data */
547c926afbcSdrh   int eDest,       /* Write the sorted results here */
548c926afbcSdrh   int iParm        /* Optional parameter associated with eDest */
549c926afbcSdrh ){
550d8bc7086Sdrh   int end = sqliteVdbeMakeLabel(v);
551d8bc7086Sdrh   int addr;
552f46f905aSdrh   if( eDest==SRT_Sorter ) return;
55399fcd718Sdrh   sqliteVdbeAddOp(v, OP_Sort, 0, 0);
55499fcd718Sdrh   addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end);
555df199a25Sdrh   if( p->nOffset>0 ){
556d11d382cSdrh     sqliteVdbeAddOp(v, OP_MemIncr, p->nOffset, addr+4);
557d11d382cSdrh     sqliteVdbeAddOp(v, OP_Pop, 1, 0);
558d11d382cSdrh     sqliteVdbeAddOp(v, OP_Goto, 0, addr);
559df199a25Sdrh   }
560d11d382cSdrh   if( p->nLimit>=0 ){
561d11d382cSdrh     sqliteVdbeAddOp(v, OP_MemIncr, p->nLimit, end);
562df199a25Sdrh   }
563c926afbcSdrh   switch( eDest ){
564c926afbcSdrh     case SRT_Callback: {
565df199a25Sdrh       sqliteVdbeAddOp(v, OP_SortCallback, nColumn, 0);
566c926afbcSdrh       break;
567c926afbcSdrh     }
568c926afbcSdrh     case SRT_Table:
569c926afbcSdrh     case SRT_TempTable: {
570c926afbcSdrh       sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
571c926afbcSdrh       sqliteVdbeAddOp(v, OP_Pull, 1, 0);
572c926afbcSdrh       sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
573c926afbcSdrh       break;
574c926afbcSdrh     }
575c926afbcSdrh     case SRT_Set: {
576c926afbcSdrh       assert( nColumn==1 );
577c926afbcSdrh       sqliteVdbeAddOp(v, OP_IsNull, -1, sqliteVdbeCurrentAddr(v)+3);
578c926afbcSdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
579c926afbcSdrh       sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
580c926afbcSdrh       break;
581c926afbcSdrh     }
582c926afbcSdrh     case SRT_Mem: {
583c926afbcSdrh       assert( nColumn==1 );
584c926afbcSdrh       sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
585c926afbcSdrh       sqliteVdbeAddOp(v, OP_Goto, 0, end);
586c926afbcSdrh       break;
587c926afbcSdrh     }
588c926afbcSdrh     default: {
589f46f905aSdrh       /* Do nothing */
590c926afbcSdrh       break;
591c926afbcSdrh     }
592c926afbcSdrh   }
59399fcd718Sdrh   sqliteVdbeAddOp(v, OP_Goto, 0, addr);
59499fcd718Sdrh   sqliteVdbeResolveLabel(v, end);
595a8b38d28Sdrh   sqliteVdbeAddOp(v, OP_SortReset, 0, 0);
596d8bc7086Sdrh }
597d8bc7086Sdrh 
598d8bc7086Sdrh /*
59982c3d636Sdrh ** Generate code that will tell the VDBE how many columns there
60082c3d636Sdrh ** are in the result and the name for each column.  This information
60182c3d636Sdrh ** is used to provide "argc" and "azCol[]" values in the callback.
60282c3d636Sdrh */
603832508b7Sdrh static void generateColumnNames(
604832508b7Sdrh   Parse *pParse,      /* Parser context */
605832508b7Sdrh   int base,           /* VDBE cursor corresponding to first entry in pTabList */
606ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
607832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
608832508b7Sdrh ){
609d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
61082c3d636Sdrh   int i;
611daffd0e5Sdrh   if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return;
612d8bc7086Sdrh   pParse->colNamesSet = 1;
6135080aaa7Sdrh   if( pParse->db->flags & SQLITE_ReportTypes ){
6145080aaa7Sdrh     sqliteVdbeAddOp(v, OP_ColumnCount, pEList->nExpr*2, 0);
6155080aaa7Sdrh   }else{
6165080aaa7Sdrh     sqliteVdbeAddOp(v, OP_ColumnCount, pEList->nExpr, 0);
6175080aaa7Sdrh   }
61882c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
61982c3d636Sdrh     Expr *p;
620b1363206Sdrh     char *zType = 0;
6211bee3d7bSdrh     int showFullNames;
62282c3d636Sdrh     if( pEList->a[i].zName ){
62382c3d636Sdrh       char *zName = pEList->a[i].zName;
62499fcd718Sdrh       sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
62599fcd718Sdrh       sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
62682c3d636Sdrh       continue;
62782c3d636Sdrh     }
62882c3d636Sdrh     p = pEList->a[i].pExpr;
629daffd0e5Sdrh     if( p==0 ) continue;
6301bee3d7bSdrh     showFullNames = (pParse->db->flags & SQLITE_FullColNames)!=0;
631fa173a76Sdrh     if( p->op==TK_COLUMN && pTabList ){
632832508b7Sdrh       Table *pTab = pTabList->a[p->iTable - base].pTab;
63397665873Sdrh       char *zCol;
6348aff1015Sdrh       int iCol = p->iColumn;
6358aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
63697665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
637b1363206Sdrh       if( iCol<0 ){
638b1363206Sdrh         zCol = "_ROWID_";
639b1363206Sdrh         zType = "INTEGER";
640b1363206Sdrh       }else{
641b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
642b1363206Sdrh         zType = pTab->aCol[iCol].zType;
643b1363206Sdrh       }
644*4b59ab5eSdrh       if( p->token.z && p->token.z[0] && !showFullNames ){
645fa173a76Sdrh         int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
646*4b59ab5eSdrh         sqliteVdbeChangeP3(v, -1, p->token.z, p->token.n);
647fa173a76Sdrh         sqliteVdbeCompressSpace(v, addr);
648fa173a76Sdrh       }else if( pTabList->nSrc>1 || showFullNames ){
64982c3d636Sdrh         char *zName = 0;
65082c3d636Sdrh         char *zTab;
65182c3d636Sdrh 
652832508b7Sdrh         zTab = pTabList->a[p->iTable - base].zAlias;
65301a34661Sdrh         if( showFullNames || zTab==0 ) zTab = pTab->zName;
65497665873Sdrh         sqliteSetString(&zName, zTab, ".", zCol, 0);
65599fcd718Sdrh         sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
65699fcd718Sdrh         sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
65782c3d636Sdrh         sqliteFree(zName);
65882c3d636Sdrh       }else{
65999fcd718Sdrh         sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
66022f70c32Sdrh         sqliteVdbeChangeP3(v, -1, zCol, 0);
66182c3d636Sdrh       }
662*4b59ab5eSdrh     }else if( p->token.z && p->token.z[0] && !showFullNames ){
663fa173a76Sdrh       int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
664*4b59ab5eSdrh       sqliteVdbeChangeP3(v, -1, p->token.z, p->token.n);
665fa173a76Sdrh       sqliteVdbeCompressSpace(v, addr);
666*4b59ab5eSdrh     }else if( p->token.z && p->token.z[0] ){
6671bee3d7bSdrh       int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
668*4b59ab5eSdrh       sqliteVdbeChangeP3(v, -1, p->token.z, p->token.n);
6691bee3d7bSdrh       sqliteVdbeCompressSpace(v, addr);
6701bee3d7bSdrh     }else{
6711bee3d7bSdrh       char zName[30];
6721bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
6731bee3d7bSdrh       sprintf(zName, "column%d", i+1);
6741bee3d7bSdrh       sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
6751bee3d7bSdrh       sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
67682c3d636Sdrh     }
6775080aaa7Sdrh     if( pParse->db->flags & SQLITE_ReportTypes ){
678b1363206Sdrh       if( zType==0 ){
679b1363206Sdrh         if( sqliteExprType(p)==SQLITE_SO_TEXT ){
680b1363206Sdrh           zType = "TEXT";
681b1363206Sdrh         }else{
682b1363206Sdrh           zType = "NUMERIC";
683b1363206Sdrh         }
684b1363206Sdrh       }
6855080aaa7Sdrh       sqliteVdbeAddOp(v, OP_ColumnName, i + pEList->nExpr, 0);
686b1363206Sdrh       sqliteVdbeChangeP3(v, -1, zType, P3_STATIC);
68782c3d636Sdrh     }
68882c3d636Sdrh   }
6895080aaa7Sdrh }
69082c3d636Sdrh 
69182c3d636Sdrh /*
692d8bc7086Sdrh ** Name of the connection operator, used for error messages.
693d8bc7086Sdrh */
694d8bc7086Sdrh static const char *selectOpName(int id){
695d8bc7086Sdrh   char *z;
696d8bc7086Sdrh   switch( id ){
697d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
698d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
699d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
700d8bc7086Sdrh     default:           z = "UNION";       break;
701d8bc7086Sdrh   }
702d8bc7086Sdrh   return z;
703d8bc7086Sdrh }
704d8bc7086Sdrh 
705d8bc7086Sdrh /*
70622f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
70722f70c32Sdrh ** the result set of that SELECT.
70822f70c32Sdrh */
70922f70c32Sdrh Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
71022f70c32Sdrh   Table *pTab;
71122f70c32Sdrh   int i;
71222f70c32Sdrh   ExprList *pEList;
71322f70c32Sdrh   static int fillInColumnList(Parse*, Select*);
71422f70c32Sdrh 
71522f70c32Sdrh   if( fillInColumnList(pParse, pSelect) ){
71622f70c32Sdrh     return 0;
71722f70c32Sdrh   }
71822f70c32Sdrh   pTab = sqliteMalloc( sizeof(Table) );
71922f70c32Sdrh   if( pTab==0 ){
72022f70c32Sdrh     return 0;
72122f70c32Sdrh   }
72222f70c32Sdrh   pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
72322f70c32Sdrh   pEList = pSelect->pEList;
72422f70c32Sdrh   pTab->nCol = pEList->nExpr;
725417be79cSdrh   assert( pTab->nCol>0 );
72622f70c32Sdrh   pTab->aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
72722f70c32Sdrh   for(i=0; i<pTab->nCol; i++){
72822f70c32Sdrh     Expr *p;
72922f70c32Sdrh     if( pEList->a[i].zName ){
73022f70c32Sdrh       pTab->aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
731*4b59ab5eSdrh     }else if( (p=pEList->a[i].pExpr)->token.z && p->token.z[0] ){
732*4b59ab5eSdrh       sqliteSetNString(&pTab->aCol[i].zName, p->token.z, p->token.n, 0);
733d820cb1bSdrh     }else if( p->op==TK_DOT && p->pRight && p->pRight->token.z &&
734d820cb1bSdrh            p->pRight->token.z[0] ){
735d820cb1bSdrh       sqliteSetNString(&pTab->aCol[i].zName,
736d820cb1bSdrh            p->pRight->token.z, p->pRight->token.n, 0);
73722f70c32Sdrh     }else{
73822f70c32Sdrh       char zBuf[30];
73922f70c32Sdrh       sprintf(zBuf, "column%d", i+1);
74022f70c32Sdrh       pTab->aCol[i].zName = sqliteStrDup(zBuf);
74122f70c32Sdrh     }
74222f70c32Sdrh   }
74322f70c32Sdrh   pTab->iPKey = -1;
74422f70c32Sdrh   return pTab;
74522f70c32Sdrh }
74622f70c32Sdrh 
74722f70c32Sdrh /*
748ad2d8307Sdrh ** For the given SELECT statement, do three things.
749d8bc7086Sdrh **
750ad3cab52Sdrh **    (1)  Fill in the pTabList->a[].pTab fields in the SrcList that
751967e8b73Sdrh **         defines the set of tables that should be scanned.
752d8bc7086Sdrh **
753ad2d8307Sdrh **    (2)  Add terms to the WHERE clause to accomodate the NATURAL keyword
754ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
755ad2d8307Sdrh **
756ad2d8307Sdrh **    (3)  Scan the list of columns in the result set (pEList) looking
75754473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
75854473229Sdrh **         If found, expand each "*" to be every column in every table
75954473229Sdrh **         and TABLE.* to be every column in TABLE.
760d8bc7086Sdrh **
761d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
762d8bc7086Sdrh ** in pParse and return non-zero.
763d8bc7086Sdrh */
764d8bc7086Sdrh static int fillInColumnList(Parse *pParse, Select *p){
76554473229Sdrh   int i, j, k, rc;
766ad3cab52Sdrh   SrcList *pTabList;
767daffd0e5Sdrh   ExprList *pEList;
768a76b5dfcSdrh   Table *pTab;
769daffd0e5Sdrh 
770daffd0e5Sdrh   if( p==0 || p->pSrc==0 ) return 1;
771daffd0e5Sdrh   pTabList = p->pSrc;
772daffd0e5Sdrh   pEList = p->pEList;
773d8bc7086Sdrh 
774d8bc7086Sdrh   /* Look up every table in the table list.
775d8bc7086Sdrh   */
776ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
777d8bc7086Sdrh     if( pTabList->a[i].pTab ){
778d8bc7086Sdrh       /* This routine has run before!  No need to continue */
779d8bc7086Sdrh       return 0;
780d8bc7086Sdrh     }
781daffd0e5Sdrh     if( pTabList->a[i].zName==0 ){
78222f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
78322f70c32Sdrh       assert( pTabList->a[i].pSelect!=0 );
784ad2d8307Sdrh       if( pTabList->a[i].zAlias==0 ){
785ad2d8307Sdrh         char zFakeName[60];
786ad2d8307Sdrh         sprintf(zFakeName, "sqlite_subquery_%p_",
787ad2d8307Sdrh            (void*)pTabList->a[i].pSelect);
788ad2d8307Sdrh         sqliteSetString(&pTabList->a[i].zAlias, zFakeName, 0);
789ad2d8307Sdrh       }
79022f70c32Sdrh       pTabList->a[i].pTab = pTab =
79122f70c32Sdrh         sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias,
79222f70c32Sdrh                                         pTabList->a[i].pSelect);
79322f70c32Sdrh       if( pTab==0 ){
794daffd0e5Sdrh         return 1;
795daffd0e5Sdrh       }
79622f70c32Sdrh       pTab->isTransient = 1;
79722f70c32Sdrh     }else{
798a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
799a76b5dfcSdrh       pTabList->a[i].pTab = pTab =
800a76b5dfcSdrh         sqliteFindTable(pParse->db, pTabList->a[i].zName);
801a76b5dfcSdrh       if( pTab==0 ){
802d8bc7086Sdrh         sqliteSetString(&pParse->zErrMsg, "no such table: ",
803d8bc7086Sdrh            pTabList->a[i].zName, 0);
804d8bc7086Sdrh         pParse->nErr++;
805d8bc7086Sdrh         return 1;
806d8bc7086Sdrh       }
807a76b5dfcSdrh       if( pTab->pSelect ){
808417be79cSdrh         if( sqliteViewGetColumnNames(pParse, pTab) ){
809417be79cSdrh           return 1;
810417be79cSdrh         }
811ff78bd2fSdrh         pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect);
812a76b5dfcSdrh       }
813d8bc7086Sdrh     }
81422f70c32Sdrh   }
815d8bc7086Sdrh 
816ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
817ad2d8307Sdrh   */
818ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
819ad2d8307Sdrh 
8207c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
82154473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
82254473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
8237c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
8247c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
8257c917d19Sdrh   ** each one to the list of all columns in all tables.
82654473229Sdrh   **
82754473229Sdrh   ** The first loop just checks to see if there are any "*" operators
82854473229Sdrh   ** that need expanding.
829d8bc7086Sdrh   */
8307c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
83154473229Sdrh     Expr *pE = pEList->a[k].pExpr;
83254473229Sdrh     if( pE->op==TK_ALL ) break;
83354473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
83454473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
8357c917d19Sdrh   }
83654473229Sdrh   rc = 0;
8377c917d19Sdrh   if( k<pEList->nExpr ){
83854473229Sdrh     /*
83954473229Sdrh     ** If we get here it means the result set contains one or more "*"
84054473229Sdrh     ** operators that need to be expanded.  Loop through each expression
84154473229Sdrh     ** in the result set and expand them one by one.
84254473229Sdrh     */
8437c917d19Sdrh     struct ExprList_item *a = pEList->a;
8447c917d19Sdrh     ExprList *pNew = 0;
8457c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
84654473229Sdrh       Expr *pE = a[k].pExpr;
84754473229Sdrh       if( pE->op!=TK_ALL &&
84854473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
84954473229Sdrh         /* This particular expression does not need to be expanded.
85054473229Sdrh         */
8517c917d19Sdrh         pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
8527c917d19Sdrh         pNew->a[pNew->nExpr-1].zName = a[k].zName;
8537c917d19Sdrh         a[k].pExpr = 0;
8547c917d19Sdrh         a[k].zName = 0;
8557c917d19Sdrh       }else{
85654473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
85754473229Sdrh         ** expanded. */
85854473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
85954473229Sdrh         Token *pName;           /* text of name of TABLE */
86054473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
86154473229Sdrh           pName = &pE->pLeft->token;
86254473229Sdrh         }else{
86354473229Sdrh           pName = 0;
86454473229Sdrh         }
865ad3cab52Sdrh         for(i=0; i<pTabList->nSrc; i++){
866d8bc7086Sdrh           Table *pTab = pTabList->a[i].pTab;
86754473229Sdrh           char *zTabName = pTabList->a[i].zAlias;
86854473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
86954473229Sdrh             zTabName = pTab->zName;
87054473229Sdrh           }
87154473229Sdrh           if( pName && (zTabName==0 || zTabName[0]==0 ||
872c754fa54Sdrh                  sqliteStrNICmp(pName->z, zTabName, pName->n)!=0 ||
873c754fa54Sdrh                  zTabName[pName->n]!=0) ){
87454473229Sdrh             continue;
87554473229Sdrh           }
87654473229Sdrh           tableSeen = 1;
877d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
87822f70c32Sdrh             Expr *pExpr, *pLeft, *pRight;
879ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
880ad2d8307Sdrh 
881ad2d8307Sdrh             if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
882ad2d8307Sdrh                 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
883ad2d8307Sdrh               /* In a NATURAL join, omit the join columns from the
884ad2d8307Sdrh               ** table on the right */
885ad2d8307Sdrh               continue;
886ad2d8307Sdrh             }
887ad2d8307Sdrh             if( i>0 && sqliteIdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
888ad2d8307Sdrh               /* In a join with a USING clause, omit columns in the
889ad2d8307Sdrh               ** using clause from the table on the right. */
890ad2d8307Sdrh               continue;
891ad2d8307Sdrh             }
89222f70c32Sdrh             pRight = sqliteExpr(TK_ID, 0, 0, 0);
89322f70c32Sdrh             if( pRight==0 ) break;
894ad2d8307Sdrh             pRight->token.z = zName;
895ad2d8307Sdrh             pRight->token.n = strlen(zName);
896*4b59ab5eSdrh             pRight->token.dyn = 0;
897*4b59ab5eSdrh             pRight->token.base = 1;
898*4b59ab5eSdrh             if( zTabName && pTabList->nSrc>1 ){
89922f70c32Sdrh               pLeft = sqliteExpr(TK_ID, 0, 0, 0);
90022f70c32Sdrh               pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
90122f70c32Sdrh               if( pExpr==0 ) break;
902*4b59ab5eSdrh               pLeft->token.z = zTabName;
903*4b59ab5eSdrh               pLeft->token.n = strlen(zTabName);
904*4b59ab5eSdrh               pLeft->token.dyn = 0;
905*4b59ab5eSdrh               pLeft->token.base = 1;
906*4b59ab5eSdrh               sqliteSetString((char**)&pExpr->token.z, zTabName, ".", zName, 0);
907*4b59ab5eSdrh               pExpr->token.n = strlen(pExpr->token.z);
908*4b59ab5eSdrh               pExpr->token.base = 0;
909*4b59ab5eSdrh               pExpr->token.dyn = 1;
91022f70c32Sdrh             }else{
91122f70c32Sdrh               pExpr = pRight;
91222f70c32Sdrh             }
9137c917d19Sdrh             pNew = sqliteExprListAppend(pNew, pExpr, 0);
914d8bc7086Sdrh           }
915d8bc7086Sdrh         }
91654473229Sdrh         if( !tableSeen ){
917f5db2d3eSdrh           if( pName ){
91854473229Sdrh             sqliteSetNString(&pParse->zErrMsg, "no such table: ", -1,
91954473229Sdrh               pName->z, pName->n, 0);
920f5db2d3eSdrh           }else{
921f5db2d3eSdrh             sqliteSetString(&pParse->zErrMsg, "no tables specified", 0);
922f5db2d3eSdrh           }
92354473229Sdrh           rc = 1;
92454473229Sdrh         }
9257c917d19Sdrh       }
9267c917d19Sdrh     }
9277c917d19Sdrh     sqliteExprListDelete(pEList);
9287c917d19Sdrh     p->pEList = pNew;
929d8bc7086Sdrh   }
93054473229Sdrh   return rc;
931d8bc7086Sdrh }
932d8bc7086Sdrh 
933d8bc7086Sdrh /*
934ff78bd2fSdrh ** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
935ff78bd2fSdrh ** in a select structure.  It just sets the pointers to NULL.  This
936ff78bd2fSdrh ** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
937ff78bd2fSdrh ** pointer is not NULL, this routine is called recursively on that pointer.
938ff78bd2fSdrh **
939ff78bd2fSdrh ** This routine is called on the Select structure that defines a
940ff78bd2fSdrh ** VIEW in order to undo any bindings to tables.  This is necessary
941ff78bd2fSdrh ** because those tables might be DROPed by a subsequent SQL command.
942ff78bd2fSdrh */
943ff78bd2fSdrh void sqliteSelectUnbind(Select *p){
944ff78bd2fSdrh   int i;
945ad3cab52Sdrh   SrcList *pSrc = p->pSrc;
946ff78bd2fSdrh   Table *pTab;
947ff78bd2fSdrh   if( p==0 ) return;
948ad3cab52Sdrh   for(i=0; i<pSrc->nSrc; i++){
949ff78bd2fSdrh     if( (pTab = pSrc->a[i].pTab)!=0 ){
950ff78bd2fSdrh       if( pTab->isTransient ){
951ff78bd2fSdrh         sqliteDeleteTable(0, pTab);
952*4b59ab5eSdrh #if 0
953ff78bd2fSdrh         sqliteSelectDelete(pSrc->a[i].pSelect);
954ff78bd2fSdrh         pSrc->a[i].pSelect = 0;
955*4b59ab5eSdrh #endif
956ff78bd2fSdrh       }
957ff78bd2fSdrh       pSrc->a[i].pTab = 0;
958ff78bd2fSdrh       if( pSrc->a[i].pSelect ){
959ff78bd2fSdrh         sqliteSelectUnbind(pSrc->a[i].pSelect);
960ff78bd2fSdrh       }
961ff78bd2fSdrh     }
962ff78bd2fSdrh   }
963ff78bd2fSdrh }
964ff78bd2fSdrh 
965ff78bd2fSdrh /*
966d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with
967d8bc7086Sdrh ** columns in a result.  For each ORDER BY expression, the opcode of
968967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of
969d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable
970d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter.
971d8bc7086Sdrh **
972d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first.  A match
973d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT.
974d8bc7086Sdrh **
975d8bc7086Sdrh ** Any entry that does not match is flagged as an error.  The number
976d8bc7086Sdrh ** of errors is returned.
977d8bc7086Sdrh */
978d8bc7086Sdrh static int matchOrderbyToColumn(
979d8bc7086Sdrh   Parse *pParse,          /* A place to leave error messages */
980d8bc7086Sdrh   Select *pSelect,        /* Match to result columns of this SELECT */
981d8bc7086Sdrh   ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
982e4de1febSdrh   int iTable,             /* Insert this value in iTable */
983d8bc7086Sdrh   int mustComplete        /* If TRUE all ORDER BYs must match */
984d8bc7086Sdrh ){
985d8bc7086Sdrh   int nErr = 0;
986d8bc7086Sdrh   int i, j;
987d8bc7086Sdrh   ExprList *pEList;
988d8bc7086Sdrh 
989daffd0e5Sdrh   if( pSelect==0 || pOrderBy==0 ) return 1;
990d8bc7086Sdrh   if( mustComplete ){
991d8bc7086Sdrh     for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
992d8bc7086Sdrh   }
993d8bc7086Sdrh   if( fillInColumnList(pParse, pSelect) ){
994d8bc7086Sdrh     return 1;
995d8bc7086Sdrh   }
996d8bc7086Sdrh   if( pSelect->pPrior ){
99792cd52f5Sdrh     if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
99892cd52f5Sdrh       return 1;
99992cd52f5Sdrh     }
1000d8bc7086Sdrh   }
1001d8bc7086Sdrh   pEList = pSelect->pEList;
1002d8bc7086Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
1003d8bc7086Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
1004e4de1febSdrh     int iCol = -1;
1005d8bc7086Sdrh     if( pOrderBy->a[i].done ) continue;
1006e4de1febSdrh     if( sqliteExprIsInteger(pE, &iCol) ){
1007e4de1febSdrh       if( iCol<=0 || iCol>pEList->nExpr ){
1008e4de1febSdrh         char zBuf[200];
1009e4de1febSdrh         sprintf(zBuf,"ORDER BY position %d should be between 1 and %d",
1010e4de1febSdrh            iCol, pEList->nExpr);
1011e4de1febSdrh         sqliteSetString(&pParse->zErrMsg, zBuf, 0);
1012e4de1febSdrh         pParse->nErr++;
1013e4de1febSdrh         nErr++;
1014e4de1febSdrh         break;
1015e4de1febSdrh       }
1016e4de1febSdrh       iCol--;
1017e4de1febSdrh     }
1018e4de1febSdrh     for(j=0; iCol<0 && j<pEList->nExpr; j++){
10194cfa7934Sdrh       if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
1020a76b5dfcSdrh         char *zName, *zLabel;
1021a76b5dfcSdrh         zName = pEList->a[j].zName;
1022a76b5dfcSdrh         assert( pE->token.z );
1023a76b5dfcSdrh         zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
1024d8bc7086Sdrh         sqliteDequote(zLabel);
1025d8bc7086Sdrh         if( sqliteStrICmp(zName, zLabel)==0 ){
1026e4de1febSdrh           iCol = j;
1027d8bc7086Sdrh         }
10286e142f54Sdrh         sqliteFree(zLabel);
1029d8bc7086Sdrh       }
1030e4de1febSdrh       if( iCol<0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
1031e4de1febSdrh         iCol = j;
1032d8bc7086Sdrh       }
1033e4de1febSdrh     }
1034e4de1febSdrh     if( iCol>=0 ){
1035967e8b73Sdrh       pE->op = TK_COLUMN;
1036e4de1febSdrh       pE->iColumn = iCol;
1037d8bc7086Sdrh       pE->iTable = iTable;
1038d8bc7086Sdrh       pOrderBy->a[i].done = 1;
1039d8bc7086Sdrh     }
1040e4de1febSdrh     if( iCol<0 && mustComplete ){
1041d8bc7086Sdrh       char zBuf[30];
1042d8bc7086Sdrh       sprintf(zBuf,"%d",i+1);
1043d8bc7086Sdrh       sqliteSetString(&pParse->zErrMsg, "ORDER BY term number ", zBuf,
1044d8bc7086Sdrh         " does not match any result column", 0);
1045d8bc7086Sdrh       pParse->nErr++;
1046d8bc7086Sdrh       nErr++;
1047d8bc7086Sdrh       break;
1048d8bc7086Sdrh     }
1049d8bc7086Sdrh   }
1050d8bc7086Sdrh   return nErr;
1051d8bc7086Sdrh }
1052d8bc7086Sdrh 
1053d8bc7086Sdrh /*
1054d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1055d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1056d8bc7086Sdrh */
1057d8bc7086Sdrh Vdbe *sqliteGetVdbe(Parse *pParse){
1058d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1059d8bc7086Sdrh   if( v==0 ){
10604c504391Sdrh     v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
1061d8bc7086Sdrh   }
1062d8bc7086Sdrh   return v;
1063d8bc7086Sdrh }
1064d8bc7086Sdrh 
1065d8bc7086Sdrh 
1066d8bc7086Sdrh /*
106782c3d636Sdrh ** This routine is called to process a query that is really the union
106882c3d636Sdrh ** or intersection of two or more separate queries.
1069c926afbcSdrh **
1070c926afbcSdrh ** "p" points to the right-most of the two queries.  The results should
1071c926afbcSdrh ** be stored in eDest with parameter iParm.
107282c3d636Sdrh */
107382c3d636Sdrh static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
107410e5e3cfSdrh   int rc;             /* Success code from a subroutine */
107510e5e3cfSdrh   Select *pPrior;     /* Another SELECT immediately to our left */
107610e5e3cfSdrh   Vdbe *v;            /* Generate code to this VDBE */
107710e5e3cfSdrh   int base;           /* Baseline value for pParse->nTab */
107882c3d636Sdrh 
1079d8bc7086Sdrh   /* Make sure there is no ORDER BY clause on prior SELECTs.  Only the
1080d8bc7086Sdrh   ** last SELECT in the series may have an ORDER BY.
108182c3d636Sdrh   */
1082daffd0e5Sdrh   if( p==0 || p->pPrior==0 ) return 1;
1083d8bc7086Sdrh   pPrior = p->pPrior;
1084d8bc7086Sdrh   if( pPrior->pOrderBy ){
1085d8bc7086Sdrh     sqliteSetString(&pParse->zErrMsg,"ORDER BY clause should come after ",
1086d8bc7086Sdrh       selectOpName(p->op), " not before", 0);
108782c3d636Sdrh     pParse->nErr++;
108882c3d636Sdrh     return 1;
108982c3d636Sdrh   }
109082c3d636Sdrh 
1091d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
1092d8bc7086Sdrh   */
1093d8bc7086Sdrh   v = sqliteGetVdbe(pParse);
1094d8bc7086Sdrh   if( v==0 ) return 1;
1095d8bc7086Sdrh 
10961cc3d75fSdrh   /* Create the destination temporary table if necessary
10971cc3d75fSdrh   */
10981cc3d75fSdrh   if( eDest==SRT_TempTable ){
10991cc3d75fSdrh     sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
11001cc3d75fSdrh     eDest = SRT_Table;
11011cc3d75fSdrh   }
11021cc3d75fSdrh 
1103f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1104d8bc7086Sdrh   */
110510e5e3cfSdrh   base = pParse->nTab;
110682c3d636Sdrh   switch( p->op ){
1107f46f905aSdrh     case TK_ALL: {
1108f46f905aSdrh       if( p->pOrderBy==0 ){
1109f46f905aSdrh         rc = sqliteSelect(pParse, pPrior, eDest, iParm, 0, 0, 0);
1110f46f905aSdrh         if( rc ) return rc;
1111f46f905aSdrh         p->pPrior = 0;
1112f46f905aSdrh         rc = sqliteSelect(pParse, p, eDest, iParm, 0, 0, 0);
1113f46f905aSdrh         p->pPrior = pPrior;
1114f46f905aSdrh         if( rc ) return rc;
1115f46f905aSdrh         break;
1116f46f905aSdrh       }
1117f46f905aSdrh       /* For UNION ALL ... ORDER BY fall through to the next case */
1118f46f905aSdrh     }
111982c3d636Sdrh     case TK_EXCEPT:
112082c3d636Sdrh     case TK_UNION: {
1121d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1122d8bc7086Sdrh       int op;          /* One of the SRT_ operations to apply to self */
1123d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
1124c926afbcSdrh       ExprList *pOrderBy;  /* The ORDER BY clause for the right SELECT */
112582c3d636Sdrh 
1126d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
1127c926afbcSdrh       if( eDest==priorOp && p->pOrderBy==0 ){
1128d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1129c926afbcSdrh         ** right.
1130d8bc7086Sdrh         */
113182c3d636Sdrh         unionTab = iParm;
113282c3d636Sdrh       }else{
1133d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1134d8bc7086Sdrh         ** intermediate results.
1135d8bc7086Sdrh         */
113682c3d636Sdrh         unionTab = pParse->nTab++;
1137d8bc7086Sdrh         if( p->pOrderBy
1138d8bc7086Sdrh         && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
1139d8bc7086Sdrh           return 1;
1140d8bc7086Sdrh         }
1141d8bc7086Sdrh         if( p->op!=TK_ALL ){
1142c6b52df3Sdrh           sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
114399fcd718Sdrh           sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
1144345fda3eSdrh         }else{
114599fcd718Sdrh           sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
114682c3d636Sdrh         }
1147d8bc7086Sdrh       }
1148d8bc7086Sdrh 
1149d8bc7086Sdrh       /* Code the SELECT statements to our left
1150d8bc7086Sdrh       */
1151832508b7Sdrh       rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
115282c3d636Sdrh       if( rc ) return rc;
1153d8bc7086Sdrh 
1154d8bc7086Sdrh       /* Code the current SELECT statement
1155d8bc7086Sdrh       */
1156d8bc7086Sdrh       switch( p->op ){
1157d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
1158d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
1159d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
1160d8bc7086Sdrh       }
116182c3d636Sdrh       p->pPrior = 0;
1162c926afbcSdrh       pOrderBy = p->pOrderBy;
1163c926afbcSdrh       p->pOrderBy = 0;
1164832508b7Sdrh       rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0);
116582c3d636Sdrh       p->pPrior = pPrior;
1166c926afbcSdrh       p->pOrderBy = pOrderBy;
116782c3d636Sdrh       if( rc ) return rc;
1168d8bc7086Sdrh 
1169d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1170d8bc7086Sdrh       ** it is that we currently need.
1171d8bc7086Sdrh       */
1172c926afbcSdrh       if( eDest!=priorOp || unionTab!=iParm ){
11736b56344dSdrh         int iCont, iBreak, iStart;
117482c3d636Sdrh         assert( p->pEList );
117541202ccaSdrh         if( eDest==SRT_Callback ){
1176832508b7Sdrh           generateColumnNames(pParse, p->base, 0, p->pEList);
117741202ccaSdrh         }
117882c3d636Sdrh         iBreak = sqliteVdbeMakeLabel(v);
11796b56344dSdrh         iCont = sqliteVdbeMakeLabel(v);
11806b56344dSdrh         sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
11816b56344dSdrh         iStart = sqliteVdbeCurrentAddr(v);
118238640e15Sdrh         rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
1183d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
118482c3d636Sdrh                              iCont, iBreak);
118582c3d636Sdrh         if( rc ) return 1;
11866b56344dSdrh         sqliteVdbeResolveLabel(v, iCont);
11876b56344dSdrh         sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
118899fcd718Sdrh         sqliteVdbeResolveLabel(v, iBreak);
118999fcd718Sdrh         sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
1190d8bc7086Sdrh         if( p->pOrderBy ){
1191c926afbcSdrh           generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
1192d8bc7086Sdrh         }
119382c3d636Sdrh       }
119482c3d636Sdrh       break;
119582c3d636Sdrh     }
119682c3d636Sdrh     case TK_INTERSECT: {
119782c3d636Sdrh       int tab1, tab2;
11986b56344dSdrh       int iCont, iBreak, iStart;
119982c3d636Sdrh 
1200d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
12016206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
1202d8bc7086Sdrh       ** by allocating the tables we will need.
1203d8bc7086Sdrh       */
120482c3d636Sdrh       tab1 = pParse->nTab++;
120582c3d636Sdrh       tab2 = pParse->nTab++;
1206d8bc7086Sdrh       if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
1207d8bc7086Sdrh         return 1;
1208d8bc7086Sdrh       }
1209c6b52df3Sdrh       sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
121099fcd718Sdrh       sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
1211d8bc7086Sdrh 
1212d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1213d8bc7086Sdrh       */
1214832508b7Sdrh       rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
121582c3d636Sdrh       if( rc ) return rc;
1216d8bc7086Sdrh 
1217d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1218d8bc7086Sdrh       */
1219c6b52df3Sdrh       sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
122099fcd718Sdrh       sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
122182c3d636Sdrh       p->pPrior = 0;
1222832508b7Sdrh       rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0);
122382c3d636Sdrh       p->pPrior = pPrior;
122482c3d636Sdrh       if( rc ) return rc;
1225d8bc7086Sdrh 
1226d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1227d8bc7086Sdrh       ** tables.
1228d8bc7086Sdrh       */
122982c3d636Sdrh       assert( p->pEList );
123041202ccaSdrh       if( eDest==SRT_Callback ){
1231832508b7Sdrh         generateColumnNames(pParse, p->base, 0, p->pEList);
123241202ccaSdrh       }
123382c3d636Sdrh       iBreak = sqliteVdbeMakeLabel(v);
12346b56344dSdrh       iCont = sqliteVdbeMakeLabel(v);
12356b56344dSdrh       sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
12366b56344dSdrh       iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
123799fcd718Sdrh       sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
123838640e15Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
1239d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
124082c3d636Sdrh                              iCont, iBreak);
124182c3d636Sdrh       if( rc ) return 1;
12426b56344dSdrh       sqliteVdbeResolveLabel(v, iCont);
12436b56344dSdrh       sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
124499fcd718Sdrh       sqliteVdbeResolveLabel(v, iBreak);
124599fcd718Sdrh       sqliteVdbeAddOp(v, OP_Close, tab2, 0);
124699fcd718Sdrh       sqliteVdbeAddOp(v, OP_Close, tab1, 0);
1247d8bc7086Sdrh       if( p->pOrderBy ){
1248c926afbcSdrh         generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
1249d8bc7086Sdrh       }
125082c3d636Sdrh       break;
125182c3d636Sdrh     }
125282c3d636Sdrh   }
125382c3d636Sdrh   assert( p->pEList && pPrior->pEList );
125482c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
1255d8bc7086Sdrh     sqliteSetString(&pParse->zErrMsg, "SELECTs to the left and right of ",
1256d8bc7086Sdrh       selectOpName(p->op), " do not have the same number of result columns", 0);
125782c3d636Sdrh     pParse->nErr++;
125882c3d636Sdrh     return 1;
12592282792aSdrh   }
126010e5e3cfSdrh   pParse->nTab = base;
12612282792aSdrh   return 0;
12622282792aSdrh }
12632282792aSdrh 
12642282792aSdrh /*
1265832508b7Sdrh ** Recursively scan through an expression tree.  For every reference
1266832508b7Sdrh ** to a column in table number iFrom, change that reference to the
1267832508b7Sdrh ** same column in table number iTo.
1268832508b7Sdrh */
1269832508b7Sdrh static void changeTables(Expr *pExpr, int iFrom, int iTo){
1270832508b7Sdrh   if( pExpr==0 ) return;
1271832508b7Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iFrom ){
1272832508b7Sdrh     pExpr->iTable = iTo;
1273832508b7Sdrh   }else{
12741b2e0329Sdrh     static void changeTablesInList(ExprList*, int, int);
1275832508b7Sdrh     changeTables(pExpr->pLeft, iFrom, iTo);
1276832508b7Sdrh     changeTables(pExpr->pRight, iFrom, iTo);
12771b2e0329Sdrh     changeTablesInList(pExpr->pList, iFrom, iTo);
1278832508b7Sdrh   }
1279832508b7Sdrh }
12801b2e0329Sdrh static void changeTablesInList(ExprList *pList, int iFrom, int iTo){
12811b2e0329Sdrh   if( pList ){
12821b2e0329Sdrh     int i;
12831b2e0329Sdrh     for(i=0; i<pList->nExpr; i++){
12841b2e0329Sdrh       changeTables(pList->a[i].pExpr, iFrom, iTo);
12851b2e0329Sdrh     }
1286832508b7Sdrh   }
1287832508b7Sdrh }
1288832508b7Sdrh 
1289832508b7Sdrh /*
1290832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
1291832508b7Sdrh ** a column in table number iTable with a copy of the corresponding
129284e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
129384e59207Sdrh ** unchanged.)  When making a copy of an expression in pEList, change
129484e59207Sdrh ** references to columns in table iSub into references to table iTable.
1295832508b7Sdrh **
1296832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
1297832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
1298832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
1299832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
1300832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
1301832508b7Sdrh ** of the subquery rather the result set of the subquery.
1302832508b7Sdrh */
1303832508b7Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList, int iSub){
1304832508b7Sdrh   if( pExpr==0 ) return;
130584e59207Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable && pExpr->iColumn>=0 ){
1306832508b7Sdrh     Expr *pNew;
130784e59207Sdrh     assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1308832508b7Sdrh     assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1309832508b7Sdrh     pNew = pEList->a[pExpr->iColumn].pExpr;
1310832508b7Sdrh     assert( pNew!=0 );
1311832508b7Sdrh     pExpr->op = pNew->op;
1312832508b7Sdrh     pExpr->pLeft = sqliteExprDup(pNew->pLeft);
1313832508b7Sdrh     pExpr->pRight = sqliteExprDup(pNew->pRight);
1314832508b7Sdrh     pExpr->pList = sqliteExprListDup(pNew->pList);
1315832508b7Sdrh     pExpr->iTable = pNew->iTable;
1316832508b7Sdrh     pExpr->iColumn = pNew->iColumn;
1317832508b7Sdrh     pExpr->iAgg = pNew->iAgg;
1318*4b59ab5eSdrh     pExpr->nFuncName = pNew->nFuncName;
1319*4b59ab5eSdrh     sqliteTokenCopy(&pExpr->token, &pNew->token);
1320832508b7Sdrh     if( iSub!=iTable ){
1321832508b7Sdrh       changeTables(pExpr, iSub, iTable);
1322832508b7Sdrh     }
1323832508b7Sdrh   }else{
1324832508b7Sdrh     static void substExprList(ExprList*,int,ExprList*,int);
1325832508b7Sdrh     substExpr(pExpr->pLeft, iTable, pEList, iSub);
1326832508b7Sdrh     substExpr(pExpr->pRight, iTable, pEList, iSub);
1327832508b7Sdrh     substExprList(pExpr->pList, iTable, pEList, iSub);
1328832508b7Sdrh   }
1329832508b7Sdrh }
1330832508b7Sdrh static void
1331832508b7Sdrh substExprList(ExprList *pList, int iTable, ExprList *pEList, int iSub){
1332832508b7Sdrh   int i;
1333832508b7Sdrh   if( pList==0 ) return;
1334832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
1335832508b7Sdrh     substExpr(pList->a[i].pExpr, iTable, pEList, iSub);
1336832508b7Sdrh   }
1337832508b7Sdrh }
1338832508b7Sdrh 
1339832508b7Sdrh /*
13401350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
13411350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
13421350b030Sdrh ** occurs.
13431350b030Sdrh **
13441350b030Sdrh ** To understand the concept of flattening, consider the following
13451350b030Sdrh ** query:
13461350b030Sdrh **
13471350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
13481350b030Sdrh **
13491350b030Sdrh ** The default way of implementing this query is to execute the
13501350b030Sdrh ** subquery first and store the results in a temporary table, then
13511350b030Sdrh ** run the outer query on that temporary table.  This requires two
13521350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
13531350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
1354832508b7Sdrh ** optimized.
13551350b030Sdrh **
1356832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
13571350b030Sdrh ** a single flat select, like this:
13581350b030Sdrh **
13591350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
13601350b030Sdrh **
13611350b030Sdrh ** The code generated for this simpification gives the same result
1362832508b7Sdrh ** but only has to scan the data once.  And because indices might
1363832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
1364832508b7Sdrh ** avoided.
13651350b030Sdrh **
1366832508b7Sdrh ** Flattening is only attempted if all of the following are true:
13671350b030Sdrh **
1368832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
13691350b030Sdrh **
1370832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
1371832508b7Sdrh **
1372832508b7Sdrh **   (3)  The subquery is not a join.
1373832508b7Sdrh **
1374832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
1375832508b7Sdrh **
1376832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
1377832508b7Sdrh **        aggregates.
1378832508b7Sdrh **
1379832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
1380832508b7Sdrh **        DISTINCT.
1381832508b7Sdrh **
138208192d5fSdrh **   (7)  The subquery has a FROM clause.
138308192d5fSdrh **
1384df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
1385df199a25Sdrh **
1386df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
1387df199a25Sdrh **        aggregates.
1388df199a25Sdrh **
1389df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
1390df199a25Sdrh **        use LIMIT.
1391df199a25Sdrh **
1392832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
1393832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
1394832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1395832508b7Sdrh **
1396832508b7Sdrh ** If flattening is not attempted, this routine is a no-op and return 0.
1397832508b7Sdrh ** If flattening is attempted this routine returns 1.
1398832508b7Sdrh **
1399832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
1400832508b7Sdrh ** the subquery before this routine runs.
14011350b030Sdrh */
1402832508b7Sdrh int flattenSubquery(Select *p, int iFrom, int isAgg, int subqueryIsAgg){
14030bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
1404ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
1405ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
14060bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
1407832508b7Sdrh   int i;
1408832508b7Sdrh   int iParent, iSub;
1409832508b7Sdrh   Expr *pWhere;
14101350b030Sdrh 
1411832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
1412832508b7Sdrh   */
1413832508b7Sdrh   if( p==0 ) return 0;
1414832508b7Sdrh   pSrc = p->pSrc;
1415ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
1416832508b7Sdrh   pSub = pSrc->a[iFrom].pSelect;
1417832508b7Sdrh   assert( pSub!=0 );
1418832508b7Sdrh   if( isAgg && subqueryIsAgg ) return 0;
1419ad3cab52Sdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
1420832508b7Sdrh   pSubSrc = pSub->pSrc;
1421832508b7Sdrh   assert( pSubSrc );
1422ad3cab52Sdrh   if( pSubSrc->nSrc!=1 ) return 0;
1423df199a25Sdrh   if( (pSub->isDistinct || pSub->nLimit>=0) &&  (pSrc->nSrc>1 || isAgg) ){
1424df199a25Sdrh      return 0;
1425df199a25Sdrh   }
1426d11d382cSdrh   if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
1427832508b7Sdrh 
14280bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
1429832508b7Sdrh   ** i-th entry of the FROM clause in the outer query.
1430832508b7Sdrh   */
1431832508b7Sdrh   iParent = p->base + iFrom;
1432832508b7Sdrh   iSub = pSub->base;
1433832508b7Sdrh   substExprList(p->pEList, iParent, pSub->pEList, iSub);
1434832508b7Sdrh   pList = p->pEList;
1435832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
1436832508b7Sdrh     if( pList->a[i].zName==0 ){
1437832508b7Sdrh       Expr *pExpr = pList->a[i].pExpr;
1438*4b59ab5eSdrh       assert( pExpr->token.z!=0 );
1439*4b59ab5eSdrh       pList->a[i].zName = sqliteStrNDup(pExpr->token.z, pExpr->token.n);
1440832508b7Sdrh     }
1441832508b7Sdrh   }
14421b2e0329Sdrh   if( isAgg ){
1443832508b7Sdrh     substExprList(p->pGroupBy, iParent, pSub->pEList, iSub);
1444832508b7Sdrh     substExpr(p->pHaving, iParent, pSub->pEList, iSub);
14451b2e0329Sdrh   }
1446832508b7Sdrh   substExprList(p->pOrderBy, iParent, pSub->pEList, iSub);
1447832508b7Sdrh   if( pSub->pWhere ){
1448832508b7Sdrh     pWhere = sqliteExprDup(pSub->pWhere);
1449832508b7Sdrh     if( iParent!=iSub ){
1450832508b7Sdrh       changeTables(pWhere, iSub, iParent);
1451832508b7Sdrh     }
1452832508b7Sdrh   }else{
1453832508b7Sdrh     pWhere = 0;
1454832508b7Sdrh   }
1455832508b7Sdrh   if( subqueryIsAgg ){
1456832508b7Sdrh     assert( p->pHaving==0 );
14571b2e0329Sdrh     p->pHaving = p->pWhere;
14581b2e0329Sdrh     p->pWhere = pWhere;
1459832508b7Sdrh     substExpr(p->pHaving, iParent, pSub->pEList, iSub);
14601b2e0329Sdrh     if( pSub->pHaving ){
14611b2e0329Sdrh       Expr *pHaving = sqliteExprDup(pSub->pHaving);
14621b2e0329Sdrh       if( iParent!=iSub ){
14631b2e0329Sdrh         changeTables(pHaving, iSub, iParent);
14641b2e0329Sdrh       }
14651b2e0329Sdrh       if( p->pHaving ){
14661b2e0329Sdrh         p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0);
14671b2e0329Sdrh       }else{
14681b2e0329Sdrh         p->pHaving = pHaving;
14691b2e0329Sdrh       }
14701b2e0329Sdrh     }
14711b2e0329Sdrh     assert( p->pGroupBy==0 );
14721b2e0329Sdrh     p->pGroupBy = sqliteExprListDup(pSub->pGroupBy);
14731b2e0329Sdrh     if( iParent!=iSub ){
14741b2e0329Sdrh       changeTablesInList(p->pGroupBy, iSub, iParent);
14751b2e0329Sdrh     }
1476832508b7Sdrh   }else if( p->pWhere==0 ){
1477832508b7Sdrh     p->pWhere = pWhere;
1478832508b7Sdrh   }else{
1479832508b7Sdrh     substExpr(p->pWhere, iParent, pSub->pEList, iSub);
1480832508b7Sdrh     if( pWhere ){
1481832508b7Sdrh       p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0);
1482832508b7Sdrh     }
1483832508b7Sdrh   }
1484832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
1485df199a25Sdrh   if( pSub->nLimit>=0 ){
1486df199a25Sdrh     if( p->nLimit<0 ){
1487df199a25Sdrh       p->nLimit = pSub->nLimit;
1488df199a25Sdrh     }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1489df199a25Sdrh       p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1490df199a25Sdrh     }
1491df199a25Sdrh   }
1492df199a25Sdrh   p->nOffset += pSub->nOffset;
1493832508b7Sdrh   if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
1494832508b7Sdrh     sqliteDeleteTable(0, pSrc->a[iFrom].pTab);
1495832508b7Sdrh   }
1496832508b7Sdrh   pSrc->a[iFrom].pTab = pSubSrc->a[0].pTab;
1497832508b7Sdrh   pSubSrc->a[0].pTab = 0;
1498832508b7Sdrh   pSrc->a[iFrom].pSelect = pSubSrc->a[0].pSelect;
1499832508b7Sdrh   pSubSrc->a[0].pSelect = 0;
1500832508b7Sdrh   sqliteSelectDelete(pSub);
1501832508b7Sdrh   return 1;
15021350b030Sdrh }
15031350b030Sdrh 
15041350b030Sdrh /*
15059562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it
15069562b551Sdrh ** is a simple min() or max() query.  If it is and this query can be
15079562b551Sdrh ** satisfied using a single seek to the beginning or end of an index,
15089562b551Sdrh ** then generate the code for this SELECT return 1.  If this is not a
15099562b551Sdrh ** simple min() or max() query, then return 0;
15109562b551Sdrh **
15119562b551Sdrh ** A simply min() or max() query looks like this:
15129562b551Sdrh **
15139562b551Sdrh **    SELECT min(a) FROM table;
15149562b551Sdrh **    SELECT max(a) FROM table;
15159562b551Sdrh **
15169562b551Sdrh ** The query may have only a single table in its FROM argument.  There
15179562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
15189562b551Sdrh ** be the min() or max() of a single column of the table.  The column
15199562b551Sdrh ** in the min() or max() function must be indexed.
15209562b551Sdrh **
15219562b551Sdrh ** The parameters to this routine are the same as for sqliteSelect().
15229562b551Sdrh ** See the header comment on that routine for additional information.
15239562b551Sdrh */
15249562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
15259562b551Sdrh   Expr *pExpr;
15269562b551Sdrh   int iCol;
15279562b551Sdrh   Table *pTab;
15289562b551Sdrh   Index *pIdx;
15299562b551Sdrh   int base;
15309562b551Sdrh   Vdbe *v;
15319562b551Sdrh   int openOp;
15329562b551Sdrh   int seekOp;
15339562b551Sdrh   int cont;
15349562b551Sdrh   ExprList eList;
15359562b551Sdrh   struct ExprList_item eListItem;
15369562b551Sdrh 
15379562b551Sdrh   /* Check to see if this query is a simple min() or max() query.  Return
15389562b551Sdrh   ** zero if it is  not.
15399562b551Sdrh   */
15409562b551Sdrh   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
1541ad3cab52Sdrh   if( p->pSrc->nSrc!=1 ) return 0;
15429562b551Sdrh   if( p->pEList->nExpr!=1 ) return 0;
15439562b551Sdrh   pExpr = p->pEList->a[0].pExpr;
15449562b551Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
15459562b551Sdrh   if( pExpr->pList==0 || pExpr->pList->nExpr!=1 ) return 0;
1546*4b59ab5eSdrh   if( pExpr->nFuncName!=3 ) return 0;
15470bce8354Sdrh   if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){
15480bce8354Sdrh     seekOp = OP_Rewind;
15490bce8354Sdrh   }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){
15500bce8354Sdrh     seekOp = OP_Last;
15510bce8354Sdrh   }else{
15520bce8354Sdrh     return 0;
15530bce8354Sdrh   }
15549562b551Sdrh   pExpr = pExpr->pList->a[0].pExpr;
15559562b551Sdrh   if( pExpr->op!=TK_COLUMN ) return 0;
15569562b551Sdrh   iCol = pExpr->iColumn;
15579562b551Sdrh   pTab = p->pSrc->a[0].pTab;
15589562b551Sdrh 
15599562b551Sdrh   /* If we get to here, it means the query is of the correct form.
156017f71934Sdrh   ** Check to make sure we have an index and make pIdx point to the
156117f71934Sdrh   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
156217f71934Sdrh   ** key column, no index is necessary so set pIdx to NULL.  If no
156317f71934Sdrh   ** usable index is found, return 0.
15649562b551Sdrh   */
15659562b551Sdrh   if( iCol<0 ){
15669562b551Sdrh     pIdx = 0;
15679562b551Sdrh   }else{
15689562b551Sdrh     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
15699562b551Sdrh       assert( pIdx->nColumn>=1 );
15709562b551Sdrh       if( pIdx->aiColumn[0]==iCol ) break;
15719562b551Sdrh     }
15729562b551Sdrh     if( pIdx==0 ) return 0;
15739562b551Sdrh   }
15749562b551Sdrh 
157517f71934Sdrh   /* Identify column names if we will be using the callback.  This
15769562b551Sdrh   ** step is skipped if the output is going to a table or a memory cell.
15779562b551Sdrh   */
15789562b551Sdrh   v = sqliteGetVdbe(pParse);
15799562b551Sdrh   if( v==0 ) return 0;
15809562b551Sdrh   if( eDest==SRT_Callback ){
1581832508b7Sdrh     generateColumnNames(pParse, p->base, p->pSrc, p->pEList);
15829562b551Sdrh   }
15839562b551Sdrh 
158417f71934Sdrh   /* Generating code to find the min or the max.  Basically all we have
158517f71934Sdrh   ** to do is find the first or the last entry in the chosen index.  If
158617f71934Sdrh   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
158717f71934Sdrh   ** or last entry in the main table.
15889562b551Sdrh   */
15895cf8e8c7Sdrh   if( !pParse->schemaVerified && (pParse->db->flags & SQLITE_InTrans)==0 ){
15905cf8e8c7Sdrh     sqliteVdbeAddOp(v, OP_VerifyCookie, pParse->db->schema_cookie, 0);
15915cf8e8c7Sdrh     pParse->schemaVerified = 1;
15925cf8e8c7Sdrh   }
15939562b551Sdrh   openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
1594832508b7Sdrh   base = p->base;
15959562b551Sdrh   sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
15965cf8e8c7Sdrh   sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
15979562b551Sdrh   if( pIdx==0 ){
15989562b551Sdrh     sqliteVdbeAddOp(v, seekOp, base, 0);
15999562b551Sdrh   }else{
16009562b551Sdrh     sqliteVdbeAddOp(v, openOp, base+1, pIdx->tnum);
16015cf8e8c7Sdrh     sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
16029562b551Sdrh     sqliteVdbeAddOp(v, seekOp, base+1, 0);
16039562b551Sdrh     sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
16049562b551Sdrh     sqliteVdbeAddOp(v, OP_Close, base+1, 0);
16059562b551Sdrh     sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
16069562b551Sdrh   }
16075cf8e8c7Sdrh   eList.nExpr = 1;
16085cf8e8c7Sdrh   memset(&eListItem, 0, sizeof(eListItem));
16095cf8e8c7Sdrh   eList.a = &eListItem;
16105cf8e8c7Sdrh   eList.a[0].pExpr = pExpr;
16119562b551Sdrh   cont = sqliteVdbeMakeLabel(v);
161238640e15Sdrh   selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont);
16139562b551Sdrh   sqliteVdbeResolveLabel(v, cont);
16149562b551Sdrh   sqliteVdbeAddOp(v, OP_Close, base, 0);
16159562b551Sdrh   return 1;
16169562b551Sdrh }
16179562b551Sdrh 
16189562b551Sdrh /*
16199bb61fe7Sdrh ** Generate code for the given SELECT statement.
16209bb61fe7Sdrh **
1621fef5208cSdrh ** The results are distributed in various ways depending on the
1622fef5208cSdrh ** value of eDest and iParm.
1623fef5208cSdrh **
1624fef5208cSdrh **     eDest Value       Result
1625fef5208cSdrh **     ------------    -------------------------------------------
1626fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
1627fef5208cSdrh **
1628fef5208cSdrh **     SRT_Mem         Store first result in memory cell iParm
1629fef5208cSdrh **
1630fef5208cSdrh **     SRT_Set         Store results as keys of a table with cursor iParm
1631fef5208cSdrh **
163282c3d636Sdrh **     SRT_Union       Store results as a key in a temporary table iParm
163382c3d636Sdrh **
1634c4a3c779Sdrh **     SRT_Except      Remove results form the temporary table iParm.
1635c4a3c779Sdrh **
1636c4a3c779Sdrh **     SRT_Table       Store results in temporary table iParm
16379bb61fe7Sdrh **
16389bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
16399bb61fe7Sdrh ** encountered, then an appropriate error message is left in
16409bb61fe7Sdrh ** pParse->zErrMsg.
16419bb61fe7Sdrh **
16429bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
16439bb61fe7Sdrh ** calling function needs to do that.
16441b2e0329Sdrh **
16451b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
16461b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
16471b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
16481b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
16491b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
16501b2e0329Sdrh ** can be changed.
16519bb61fe7Sdrh */
16529bb61fe7Sdrh int sqliteSelect(
1653cce7d176Sdrh   Parse *pParse,         /* The parser context */
16549bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
165582c3d636Sdrh   int eDest,             /* One of: SRT_Callback Mem Set Union Except */
1656832508b7Sdrh   int iParm,             /* Save result in this memory location, if >=0 */
1657832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
1658832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
16591b2e0329Sdrh   int *pParentAgg        /* True if pParent uses aggregate functions */
1660cce7d176Sdrh ){
1661d8bc7086Sdrh   int i;
1662cce7d176Sdrh   WhereInfo *pWInfo;
1663cce7d176Sdrh   Vdbe *v;
1664cce7d176Sdrh   int isAgg = 0;         /* True for select lists like "count(*)" */
1665a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
1666ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
16679bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
16689bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
16692282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
16702282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
167119a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
167219a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
167310e5e3cfSdrh   int base;              /* First cursor available for use */
16741d83f052Sdrh   int rc = 1;            /* Value to return from this function */
16759bb61fe7Sdrh 
1676daffd0e5Sdrh   if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
1677daffd0e5Sdrh 
167882c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
167982c3d636Sdrh   */
168082c3d636Sdrh   if( p->pPrior ){
168182c3d636Sdrh     return multiSelect(pParse, p, eDest, iParm);
168282c3d636Sdrh   }
168382c3d636Sdrh 
168482c3d636Sdrh   /* Make local copies of the parameters for this query.
168582c3d636Sdrh   */
16869bb61fe7Sdrh   pTabList = p->pSrc;
16879bb61fe7Sdrh   pWhere = p->pWhere;
16889bb61fe7Sdrh   pOrderBy = p->pOrderBy;
16892282792aSdrh   pGroupBy = p->pGroupBy;
16902282792aSdrh   pHaving = p->pHaving;
169119a775c2Sdrh   isDistinct = p->isDistinct;
16929bb61fe7Sdrh 
1693832508b7Sdrh   /* Allocate a block of VDBE cursors, one for each table in the FROM clause.
1694832508b7Sdrh   ** The WHERE processing requires that the cursors for the tables in the
1695832508b7Sdrh   ** FROM clause be consecutive.
169610e5e3cfSdrh   */
1697832508b7Sdrh   base = p->base = pParse->nTab;
1698ad3cab52Sdrh   pParse->nTab += pTabList->nSrc;
169910e5e3cfSdrh 
17009bb61fe7Sdrh   /*
17019bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
17029bb61fe7Sdrh   ** errors before this routine starts.
17039bb61fe7Sdrh   */
17041d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
1705cce7d176Sdrh 
1706d8bc7086Sdrh   /* Look up every table in the table list and create an appropriate
1707d8bc7086Sdrh   ** columnlist in pEList if there isn't one already.  (The parser leaves
1708967e8b73Sdrh   ** a NULL in the p->pEList if the SQL said "SELECT * FROM ...")
1709cce7d176Sdrh   */
1710d8bc7086Sdrh   if( fillInColumnList(pParse, p) ){
17111d83f052Sdrh     goto select_end;
1712cce7d176Sdrh   }
1713ad2d8307Sdrh   pWhere = p->pWhere;
1714d8bc7086Sdrh   pEList = p->pEList;
17151d83f052Sdrh   if( pEList==0 ) goto select_end;
1716cce7d176Sdrh 
17172282792aSdrh   /* If writing to memory or generating a set
17182282792aSdrh   ** only a single column may be output.
171919a775c2Sdrh   */
1720fef5208cSdrh   if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
172119a775c2Sdrh     sqliteSetString(&pParse->zErrMsg, "only a single result allowed for "
172219a775c2Sdrh        "a SELECT that is part of an expression", 0);
172319a775c2Sdrh     pParse->nErr++;
17241d83f052Sdrh     goto select_end;
172519a775c2Sdrh   }
172619a775c2Sdrh 
1727c926afbcSdrh   /* ORDER BY is ignored for some destinations.
17282282792aSdrh   */
1729c926afbcSdrh   switch( eDest ){
1730c926afbcSdrh     case SRT_Union:
1731c926afbcSdrh     case SRT_Except:
1732c926afbcSdrh     case SRT_Discard:
1733acd4c695Sdrh       pOrderBy = 0;
1734c926afbcSdrh       break;
1735c926afbcSdrh     default:
1736c926afbcSdrh       break;
17372282792aSdrh   }
17382282792aSdrh 
173910e5e3cfSdrh   /* At this point, we should have allocated all the cursors that we
1740832508b7Sdrh   ** need to handle subquerys and temporary tables.
174110e5e3cfSdrh   **
1742967e8b73Sdrh   ** Resolve the column names and do a semantics check on all the expressions.
17432282792aSdrh   */
17444794b980Sdrh   for(i=0; i<pEList->nExpr; i++){
1745832508b7Sdrh     if( sqliteExprResolveIds(pParse, base, pTabList, 0, pEList->a[i].pExpr) ){
17461d83f052Sdrh       goto select_end;
1747cce7d176Sdrh     }
17482282792aSdrh     if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
17491d83f052Sdrh       goto select_end;
1750cce7d176Sdrh     }
1751cce7d176Sdrh   }
1752cce7d176Sdrh   if( pWhere ){
1753832508b7Sdrh     if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pWhere) ){
17541d83f052Sdrh       goto select_end;
1755cce7d176Sdrh     }
1756cce7d176Sdrh     if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
17571d83f052Sdrh       goto select_end;
1758cce7d176Sdrh     }
1759cce7d176Sdrh   }
1760cce7d176Sdrh   if( pOrderBy ){
1761cce7d176Sdrh     for(i=0; i<pOrderBy->nExpr; i++){
17622282792aSdrh       Expr *pE = pOrderBy->a[i].pExpr;
17639208643dSdrh       if( sqliteExprIsConstant(pE) ){
1764e4de1febSdrh         int iCol;
1765e4de1febSdrh         if( sqliteExprIsInteger(pE, &iCol)==0 ){
17669208643dSdrh           sqliteSetString(&pParse->zErrMsg,
1767e4de1febSdrh                "ORDER BY terms must not be non-integer constants", 0);
17689208643dSdrh           pParse->nErr++;
17691d83f052Sdrh           goto select_end;
1770e4de1febSdrh         }else if( iCol<=0 || iCol>pEList->nExpr ){
1771e4de1febSdrh           char zBuf[2000];
1772e4de1febSdrh           sprintf(zBuf,"ORDER BY column number %d out of range - should be "
1773e4de1febSdrh              "between 1 and %d", iCol, pEList->nExpr);
1774e4de1febSdrh           sqliteSetString(&pParse->zErrMsg, zBuf, 0);
1775e4de1febSdrh           pParse->nErr++;
1776e4de1febSdrh           goto select_end;
1777e4de1febSdrh         }
1778e4de1febSdrh         sqliteExprDelete(pE);
1779e4de1febSdrh         pE = pOrderBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
17809208643dSdrh       }
1781832508b7Sdrh       if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
17821d83f052Sdrh         goto select_end;
1783cce7d176Sdrh       }
17842282792aSdrh       if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
17851d83f052Sdrh         goto select_end;
1786cce7d176Sdrh       }
1787cce7d176Sdrh     }
1788cce7d176Sdrh   }
17892282792aSdrh   if( pGroupBy ){
17902282792aSdrh     for(i=0; i<pGroupBy->nExpr; i++){
17912282792aSdrh       Expr *pE = pGroupBy->a[i].pExpr;
17929208643dSdrh       if( sqliteExprIsConstant(pE) ){
17939208643dSdrh         sqliteSetString(&pParse->zErrMsg,
17949208643dSdrh              "GROUP BY expressions should not be constant", 0);
17959208643dSdrh         pParse->nErr++;
17961d83f052Sdrh         goto select_end;
17979208643dSdrh       }
1798832508b7Sdrh       if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
17991d83f052Sdrh         goto select_end;
18002282792aSdrh       }
18012282792aSdrh       if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
18021d83f052Sdrh         goto select_end;
18032282792aSdrh       }
18042282792aSdrh     }
18052282792aSdrh   }
18062282792aSdrh   if( pHaving ){
18072282792aSdrh     if( pGroupBy==0 ){
1808da93281eSdrh       sqliteSetString(&pParse->zErrMsg, "a GROUP BY clause is required "
1809da93281eSdrh          "before HAVING", 0);
18102282792aSdrh       pParse->nErr++;
18111d83f052Sdrh       goto select_end;
18122282792aSdrh     }
1813832508b7Sdrh     if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pHaving) ){
18141d83f052Sdrh       goto select_end;
18152282792aSdrh     }
1816da93281eSdrh     if( sqliteExprCheck(pParse, pHaving, isAgg, 0) ){
18171d83f052Sdrh       goto select_end;
18182282792aSdrh     }
1819cce7d176Sdrh   }
1820cce7d176Sdrh 
18219562b551Sdrh   /* Check for the special case of a min() or max() function by itself
18229562b551Sdrh   ** in the result set.
18239562b551Sdrh   */
18249562b551Sdrh   if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
18255cf8e8c7Sdrh     rc = 0;
18269562b551Sdrh     goto select_end;
18279562b551Sdrh   }
18289562b551Sdrh 
1829d820cb1bSdrh   /* Begin generating code.
1830d820cb1bSdrh   */
1831d820cb1bSdrh   v = sqliteGetVdbe(pParse);
1832d820cb1bSdrh   if( v==0 ) goto select_end;
1833d820cb1bSdrh 
18340bb28106Sdrh   /* Identify column names if we will be using in the callback.  This
18350bb28106Sdrh   ** step is skipped if the output is going to a table or a memory cell.
18360bb28106Sdrh   */
18370bb28106Sdrh   if( eDest==SRT_Callback ){
18380bb28106Sdrh     generateColumnNames(pParse, p->base, pTabList, pEList);
18390bb28106Sdrh   }
18400bb28106Sdrh 
18410bb28106Sdrh   /* Set the limiter
18420bb28106Sdrh   */
18430bb28106Sdrh   if( p->nLimit<=0 ){
1844d11d382cSdrh     p->nLimit = -1;
18450bb28106Sdrh     p->nOffset = 0;
18460bb28106Sdrh   }else{
1847d11d382cSdrh     int iMem = pParse->nMem++;
1848d11d382cSdrh     sqliteVdbeAddOp(v, OP_Integer, -p->nLimit, 0);
1849bf5cd97eSdrh     sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
1850d11d382cSdrh     p->nLimit = iMem;
1851d11d382cSdrh     if( p->nOffset<=0 ){
1852d11d382cSdrh       p->nOffset = 0;
1853d11d382cSdrh     }else{
1854d11d382cSdrh       iMem = pParse->nMem++;
1855d11d382cSdrh       sqliteVdbeAddOp(v, OP_Integer, -p->nOffset, 0);
1856bf5cd97eSdrh       sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
1857d11d382cSdrh       p->nOffset = iMem;
1858d11d382cSdrh     }
18590bb28106Sdrh   }
18600bb28106Sdrh 
1861d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
1862d820cb1bSdrh   */
1863ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
1864a76b5dfcSdrh     if( pTabList->a[i].pSelect==0 ) continue;
18652d0794e3Sdrh     sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable, base+i,
18661b2e0329Sdrh                  p, i, &isAgg);
1867832508b7Sdrh     pTabList = p->pSrc;
1868832508b7Sdrh     pWhere = p->pWhere;
1869acd4c695Sdrh     if( eDest==SRT_Callback ){
1870832508b7Sdrh       pOrderBy = p->pOrderBy;
1871acd4c695Sdrh     }
1872832508b7Sdrh     pGroupBy = p->pGroupBy;
1873832508b7Sdrh     pHaving = p->pHaving;
1874832508b7Sdrh     isDistinct = p->isDistinct;
18751b2e0329Sdrh   }
18761b2e0329Sdrh 
18771b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
18781b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
18791b2e0329Sdrh   */
18801b2e0329Sdrh   if( pParent && pParentAgg &&
18811b2e0329Sdrh       flattenSubquery(pParent, parentTab, *pParentAgg, isAgg) ){
18821b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
18831b2e0329Sdrh     return rc;
18841b2e0329Sdrh   }
1885832508b7Sdrh 
18862d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
18872d0794e3Sdrh   */
18882d0794e3Sdrh   if( eDest==SRT_TempTable ){
18892d0794e3Sdrh     sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
18902d0794e3Sdrh   }
18912d0794e3Sdrh 
18922282792aSdrh   /* Do an analysis of aggregate expressions.
1893efb7251dSdrh   */
1894d820cb1bSdrh   sqliteAggregateInfoReset(pParse);
18952282792aSdrh   if( isAgg ){
18960bce8354Sdrh     assert( pParse->nAgg==0 );
18972282792aSdrh     for(i=0; i<pEList->nExpr; i++){
18982282792aSdrh       if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
18991d83f052Sdrh         goto select_end;
19002282792aSdrh       }
19012282792aSdrh     }
19022282792aSdrh     if( pGroupBy ){
19032282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
19042282792aSdrh         if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
19051d83f052Sdrh           goto select_end;
19062282792aSdrh         }
19072282792aSdrh       }
19082282792aSdrh     }
19092282792aSdrh     if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
19101d83f052Sdrh       goto select_end;
19112282792aSdrh     }
1912191b690eSdrh     if( pOrderBy ){
1913191b690eSdrh       for(i=0; i<pOrderBy->nExpr; i++){
1914191b690eSdrh         if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
19151d83f052Sdrh           goto select_end;
1916191b690eSdrh         }
1917191b690eSdrh       }
1918191b690eSdrh     }
1919efb7251dSdrh   }
1920efb7251dSdrh 
19212282792aSdrh   /* Reset the aggregator
1922cce7d176Sdrh   */
1923cce7d176Sdrh   if( isAgg ){
192499fcd718Sdrh     sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
1925e5095355Sdrh     for(i=0; i<pParse->nAgg; i++){
19260bce8354Sdrh       FuncDef *pFunc;
19270bce8354Sdrh       if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
19281350b030Sdrh         sqliteVdbeAddOp(v, OP_AggInit, 0, i);
19290bce8354Sdrh         sqliteVdbeChangeP3(v, -1, (char*)pFunc, P3_POINTER);
1930e5095355Sdrh       }
1931e5095355Sdrh     }
19321bee3d7bSdrh     if( pGroupBy==0 ){
19331bee3d7bSdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
19341bee3d7bSdrh       sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
19351bee3d7bSdrh     }
1936cce7d176Sdrh   }
1937cce7d176Sdrh 
193819a775c2Sdrh   /* Initialize the memory cell to NULL
193919a775c2Sdrh   */
1940fef5208cSdrh   if( eDest==SRT_Mem ){
194199fcd718Sdrh     sqliteVdbeAddOp(v, OP_String, 0, 0);
19428721ce4aSdrh     sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
194319a775c2Sdrh   }
194419a775c2Sdrh 
1945832508b7Sdrh   /* Open a temporary table to use for the distinct set.
1946cce7d176Sdrh   */
194719a775c2Sdrh   if( isDistinct ){
1948832508b7Sdrh     distinct = pParse->nTab++;
1949c6b52df3Sdrh     sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
1950832508b7Sdrh   }else{
1951832508b7Sdrh     distinct = -1;
1952efb7251dSdrh   }
1953832508b7Sdrh 
1954832508b7Sdrh   /* Begin the database scan
1955832508b7Sdrh   */
195668d2e591Sdrh   pWInfo = sqliteWhereBegin(pParse, p->base, pTabList, pWhere, 0,
195768d2e591Sdrh                             pGroupBy ? 0 : &pOrderBy);
19581d83f052Sdrh   if( pWInfo==0 ) goto select_end;
1959cce7d176Sdrh 
19602282792aSdrh   /* Use the standard inner loop if we are not dealing with
19612282792aSdrh   ** aggregates
1962cce7d176Sdrh   */
1963da9d6c45Sdrh   if( !isAgg ){
1964df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
1965df199a25Sdrh                     iParm, pWInfo->iContinue, pWInfo->iBreak) ){
19661d83f052Sdrh        goto select_end;
1967cce7d176Sdrh     }
1968da9d6c45Sdrh   }
1969cce7d176Sdrh 
1970e3184744Sdrh   /* If we are dealing with aggregates, then do the special aggregate
19712282792aSdrh   ** processing.
1972efb7251dSdrh   */
19732282792aSdrh   else{
19742282792aSdrh     if( pGroupBy ){
19751bee3d7bSdrh       int lbl1;
19762282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
19772282792aSdrh         sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
1978efb7251dSdrh       }
197999fcd718Sdrh       sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
1980491791a8Sdrh       if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pGroupBy);
19811bee3d7bSdrh       lbl1 = sqliteVdbeMakeLabel(v);
198299fcd718Sdrh       sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
19832282792aSdrh       for(i=0; i<pParse->nAgg; i++){
19842282792aSdrh         if( pParse->aAgg[i].isAgg ) continue;
19852282792aSdrh         sqliteExprCode(pParse, pParse->aAgg[i].pExpr);
198699fcd718Sdrh         sqliteVdbeAddOp(v, OP_AggSet, 0, i);
19872282792aSdrh       }
19882282792aSdrh       sqliteVdbeResolveLabel(v, lbl1);
19892282792aSdrh     }
19902282792aSdrh     for(i=0; i<pParse->nAgg; i++){
19912282792aSdrh       Expr *pE;
19920bce8354Sdrh       int j;
19932282792aSdrh       if( !pParse->aAgg[i].isAgg ) continue;
19942282792aSdrh       pE = pParse->aAgg[i].pExpr;
19952282792aSdrh       assert( pE->op==TK_AGG_FUNCTION );
19960bce8354Sdrh       if( pE->pList ){
1997e5095355Sdrh         for(j=0; j<pE->pList->nExpr; j++){
1998e5095355Sdrh           sqliteExprCode(pParse, pE->pList->a[j].pExpr);
1999e5095355Sdrh         }
20002282792aSdrh       }
20011350b030Sdrh       sqliteVdbeAddOp(v, OP_Integer, i, 0);
2002f55f25f0Sdrh       sqliteVdbeAddOp(v, OP_AggFunc, 0, pE->pList ? pE->pList->nExpr : 0);
20030bce8354Sdrh       assert( pParse->aAgg[i].pFunc!=0 );
20040bce8354Sdrh       assert( pParse->aAgg[i].pFunc->xStep!=0 );
20050bce8354Sdrh       sqliteVdbeChangeP3(v, -1, (char*)pParse->aAgg[i].pFunc, P3_POINTER);
20062282792aSdrh     }
20072282792aSdrh   }
20082282792aSdrh 
2009cce7d176Sdrh   /* End the database scan loop.
2010cce7d176Sdrh   */
2011cce7d176Sdrh   sqliteWhereEnd(pWInfo);
2012cce7d176Sdrh 
20132282792aSdrh   /* If we are processing aggregates, we need to set up a second loop
20142282792aSdrh   ** over all of the aggregate values and process them.
20152282792aSdrh   */
20162282792aSdrh   if( isAgg ){
20172282792aSdrh     int endagg = sqliteVdbeMakeLabel(v);
20182282792aSdrh     int startagg;
201999fcd718Sdrh     startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
20202282792aSdrh     pParse->useAgg = 1;
20212282792aSdrh     if( pHaving ){
2022f5905aa7Sdrh       sqliteExprIfFalse(pParse, pHaving, startagg, 1);
20232282792aSdrh     }
2024df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2025df199a25Sdrh                     iParm, startagg, endagg) ){
20261d83f052Sdrh       goto select_end;
20272282792aSdrh     }
202899fcd718Sdrh     sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
202999fcd718Sdrh     sqliteVdbeResolveLabel(v, endagg);
203099fcd718Sdrh     sqliteVdbeAddOp(v, OP_Noop, 0, 0);
20312282792aSdrh     pParse->useAgg = 0;
20322282792aSdrh   }
20332282792aSdrh 
2034cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
2035cce7d176Sdrh   ** and send them to the callback one by one.
2036cce7d176Sdrh   */
2037cce7d176Sdrh   if( pOrderBy ){
2038c926afbcSdrh     generateSortTail(p, v, pEList->nExpr, eDest, iParm);
2039cce7d176Sdrh   }
20406a535340Sdrh 
20416a535340Sdrh 
20426a535340Sdrh   /* Issue a null callback if that is what the user wants.
20436a535340Sdrh   */
20446a535340Sdrh   if( (pParse->db->flags & SQLITE_NullCallback)!=0 && eDest==SRT_Callback ){
20456a535340Sdrh     sqliteVdbeAddOp(v, OP_NullCallback, pEList->nExpr, 0);
20466a535340Sdrh   }
20476a535340Sdrh 
20481d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
20491d83f052Sdrh   ** to indicate no errors.
20501d83f052Sdrh   */
20511d83f052Sdrh   rc = 0;
20521d83f052Sdrh 
20531d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
20541d83f052Sdrh   ** successful coding of the SELECT.
20551d83f052Sdrh   */
20561d83f052Sdrh select_end:
2057832508b7Sdrh   pParse->nTab = base;
20581d83f052Sdrh   sqliteAggregateInfoReset(pParse);
20591d83f052Sdrh   return rc;
2060cce7d176Sdrh }
2061