xref: /sqlite-3.40.0/src/select.c (revision 36a3c70b)
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*36a3c70bSdanielk1977 ** $Id: select.c,v 1.164 2004/05/11 06:55:14 danielk1977 Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19315555caSdrh 
20cce7d176Sdrh /*
219bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that
229bb61fe7Sdrh ** structure.
23cce7d176Sdrh */
244adee20fSdanielk1977 Select *sqlite3SelectNew(
25daffd0e5Sdrh   ExprList *pEList,     /* which columns to include in the result */
26ad3cab52Sdrh   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
27daffd0e5Sdrh   Expr *pWhere,         /* the WHERE clause */
28daffd0e5Sdrh   ExprList *pGroupBy,   /* the GROUP BY clause */
29daffd0e5Sdrh   Expr *pHaving,        /* the HAVING clause */
30daffd0e5Sdrh   ExprList *pOrderBy,   /* the ORDER BY clause */
319bbca4c1Sdrh   int isDistinct,       /* true if the DISTINCT keyword is present */
329bbca4c1Sdrh   int nLimit,           /* LIMIT value.  -1 means not used */
33ef0cae50Sdrh   int nOffset           /* OFFSET value.  0 means no offset */
349bb61fe7Sdrh ){
359bb61fe7Sdrh   Select *pNew;
369bb61fe7Sdrh   pNew = sqliteMalloc( sizeof(*pNew) );
37daffd0e5Sdrh   if( pNew==0 ){
384adee20fSdanielk1977     sqlite3ExprListDelete(pEList);
394adee20fSdanielk1977     sqlite3SrcListDelete(pSrc);
404adee20fSdanielk1977     sqlite3ExprDelete(pWhere);
414adee20fSdanielk1977     sqlite3ExprListDelete(pGroupBy);
424adee20fSdanielk1977     sqlite3ExprDelete(pHaving);
434adee20fSdanielk1977     sqlite3ExprListDelete(pOrderBy);
44daffd0e5Sdrh   }else{
45b733d037Sdrh     if( pEList==0 ){
464adee20fSdanielk1977       pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0);
47b733d037Sdrh     }
489bb61fe7Sdrh     pNew->pEList = pEList;
499bb61fe7Sdrh     pNew->pSrc = pSrc;
509bb61fe7Sdrh     pNew->pWhere = pWhere;
519bb61fe7Sdrh     pNew->pGroupBy = pGroupBy;
529bb61fe7Sdrh     pNew->pHaving = pHaving;
539bb61fe7Sdrh     pNew->pOrderBy = pOrderBy;
549bb61fe7Sdrh     pNew->isDistinct = isDistinct;
5582c3d636Sdrh     pNew->op = TK_SELECT;
569bbca4c1Sdrh     pNew->nLimit = nLimit;
579bbca4c1Sdrh     pNew->nOffset = nOffset;
587b58daeaSdrh     pNew->iLimit = -1;
597b58daeaSdrh     pNew->iOffset = -1;
60daffd0e5Sdrh   }
619bb61fe7Sdrh   return pNew;
629bb61fe7Sdrh }
639bb61fe7Sdrh 
649bb61fe7Sdrh /*
6501f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
6601f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
6701f3f253Sdrh ** in terms of the following bit values:
6801f3f253Sdrh **
6901f3f253Sdrh **     JT_INNER
7001f3f253Sdrh **     JT_OUTER
7101f3f253Sdrh **     JT_NATURAL
7201f3f253Sdrh **     JT_LEFT
7301f3f253Sdrh **     JT_RIGHT
7401f3f253Sdrh **
7501f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
7601f3f253Sdrh **
7701f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
7801f3f253Sdrh ** a join type, but put an error in the pParse structure.
7901f3f253Sdrh */
804adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
8101f3f253Sdrh   int jointype = 0;
8201f3f253Sdrh   Token *apAll[3];
8301f3f253Sdrh   Token *p;
8401f3f253Sdrh   static struct {
8501f3f253Sdrh     const char *zKeyword;
8601f3f253Sdrh     int nChar;
8701f3f253Sdrh     int code;
8801f3f253Sdrh   } keywords[] = {
8901f3f253Sdrh     { "natural", 7, JT_NATURAL },
90195e6967Sdrh     { "left",    4, JT_LEFT|JT_OUTER },
91195e6967Sdrh     { "right",   5, JT_RIGHT|JT_OUTER },
92195e6967Sdrh     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
9301f3f253Sdrh     { "outer",   5, JT_OUTER },
9401f3f253Sdrh     { "inner",   5, JT_INNER },
9501f3f253Sdrh     { "cross",   5, JT_INNER },
9601f3f253Sdrh   };
9701f3f253Sdrh   int i, j;
9801f3f253Sdrh   apAll[0] = pA;
9901f3f253Sdrh   apAll[1] = pB;
10001f3f253Sdrh   apAll[2] = pC;
101195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
10201f3f253Sdrh     p = apAll[i];
10301f3f253Sdrh     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
10401f3f253Sdrh       if( p->n==keywords[j].nChar
1054adee20fSdanielk1977           && sqlite3StrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
10601f3f253Sdrh         jointype |= keywords[j].code;
10701f3f253Sdrh         break;
10801f3f253Sdrh       }
10901f3f253Sdrh     }
11001f3f253Sdrh     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
11101f3f253Sdrh       jointype |= JT_ERROR;
11201f3f253Sdrh       break;
11301f3f253Sdrh     }
11401f3f253Sdrh   }
115ad2d8307Sdrh   if(
116ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
117195e6967Sdrh      (jointype & JT_ERROR)!=0
118ad2d8307Sdrh   ){
11901f3f253Sdrh     static Token dummy = { 0, 0 };
12001f3f253Sdrh     char *zSp1 = " ", *zSp2 = " ";
12101f3f253Sdrh     if( pB==0 ){ pB = &dummy; zSp1 = 0; }
12201f3f253Sdrh     if( pC==0 ){ pC = &dummy; zSp2 = 0; }
1234adee20fSdanielk1977     sqlite3SetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
12401f3f253Sdrh        pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0);
12501f3f253Sdrh     pParse->nErr++;
12601f3f253Sdrh     jointype = JT_INNER;
127195e6967Sdrh   }else if( jointype & JT_RIGHT ){
1284adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
129da93d238Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported");
130195e6967Sdrh     jointype = JT_INNER;
13101f3f253Sdrh   }
13201f3f253Sdrh   return jointype;
13301f3f253Sdrh }
13401f3f253Sdrh 
13501f3f253Sdrh /*
136ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
137ad2d8307Sdrh ** is not contained in the table.
138ad2d8307Sdrh */
139ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
140ad2d8307Sdrh   int i;
141ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
1424adee20fSdanielk1977     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
143ad2d8307Sdrh   }
144ad2d8307Sdrh   return -1;
145ad2d8307Sdrh }
146ad2d8307Sdrh 
147ad2d8307Sdrh /*
148ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the
149ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2.
150ad2d8307Sdrh */
151ad2d8307Sdrh static void addWhereTerm(
152ad2d8307Sdrh   const char *zCol,        /* Name of the column */
153ad2d8307Sdrh   const Table *pTab1,      /* First table */
154ad2d8307Sdrh   const Table *pTab2,      /* Second table */
155ad2d8307Sdrh   Expr **ppExpr            /* Add the equality term to this expression */
156ad2d8307Sdrh ){
157ad2d8307Sdrh   Token dummy;
158ad2d8307Sdrh   Expr *pE1a, *pE1b, *pE1c;
159ad2d8307Sdrh   Expr *pE2a, *pE2b, *pE2c;
160ad2d8307Sdrh   Expr *pE;
161ad2d8307Sdrh 
162ad2d8307Sdrh   dummy.z = zCol;
163ad2d8307Sdrh   dummy.n = strlen(zCol);
1644b59ab5eSdrh   dummy.dyn = 0;
1654adee20fSdanielk1977   pE1a = sqlite3Expr(TK_ID, 0, 0, &dummy);
1664adee20fSdanielk1977   pE2a = sqlite3Expr(TK_ID, 0, 0, &dummy);
167ad2d8307Sdrh   dummy.z = pTab1->zName;
168ad2d8307Sdrh   dummy.n = strlen(dummy.z);
1694adee20fSdanielk1977   pE1b = sqlite3Expr(TK_ID, 0, 0, &dummy);
170ad2d8307Sdrh   dummy.z = pTab2->zName;
171ad2d8307Sdrh   dummy.n = strlen(dummy.z);
1724adee20fSdanielk1977   pE2b = sqlite3Expr(TK_ID, 0, 0, &dummy);
1734adee20fSdanielk1977   pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
1744adee20fSdanielk1977   pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
1754adee20fSdanielk1977   pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
1761f16230bSdrh   ExprSetProperty(pE, EP_FromJoin);
177ad2d8307Sdrh   if( *ppExpr ){
1784adee20fSdanielk1977     *ppExpr = sqlite3Expr(TK_AND, *ppExpr, pE, 0);
179ad2d8307Sdrh   }else{
180ad2d8307Sdrh     *ppExpr = pE;
181ad2d8307Sdrh   }
182ad2d8307Sdrh }
183ad2d8307Sdrh 
184ad2d8307Sdrh /*
1851f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
1861cc093c2Sdrh **
187e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
1881cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
1891f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
1901f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
1911f16230bSdrh ** WHERE clause during join processing but we need to remember that they
1921f16230bSdrh ** originated in the ON or USING clause.
1931cc093c2Sdrh */
1941cc093c2Sdrh static void setJoinExpr(Expr *p){
1951cc093c2Sdrh   while( p ){
1961f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
1971cc093c2Sdrh     setJoinExpr(p->pLeft);
1981cc093c2Sdrh     p = p->pRight;
1991cc093c2Sdrh   }
2001cc093c2Sdrh }
2011cc093c2Sdrh 
2021cc093c2Sdrh /*
203ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
204ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
205ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
206ad2d8307Sdrh **
207ad2d8307Sdrh ** This routine returns the number of errors encountered.
208ad2d8307Sdrh */
209ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
210ad2d8307Sdrh   SrcList *pSrc;
211ad2d8307Sdrh   int i, j;
212ad2d8307Sdrh   pSrc = p->pSrc;
213ad2d8307Sdrh   for(i=0; i<pSrc->nSrc-1; i++){
214ad2d8307Sdrh     struct SrcList_item *pTerm = &pSrc->a[i];
215ad2d8307Sdrh     struct SrcList_item *pOther = &pSrc->a[i+1];
216ad2d8307Sdrh 
217ad2d8307Sdrh     if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
218ad2d8307Sdrh 
219ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
220ad2d8307Sdrh     ** every column that the two tables have in common.
221ad2d8307Sdrh     */
222ad2d8307Sdrh     if( pTerm->jointype & JT_NATURAL ){
223ad2d8307Sdrh       Table *pTab;
224ad2d8307Sdrh       if( pTerm->pOn || pTerm->pUsing ){
2254adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
226ad2d8307Sdrh            "an ON or USING clause", 0);
227ad2d8307Sdrh         return 1;
228ad2d8307Sdrh       }
229ad2d8307Sdrh       pTab = pTerm->pTab;
230ad2d8307Sdrh       for(j=0; j<pTab->nCol; j++){
231ad2d8307Sdrh         if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
232ad2d8307Sdrh           addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
233ad2d8307Sdrh         }
234ad2d8307Sdrh       }
235ad2d8307Sdrh     }
236ad2d8307Sdrh 
237ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
238ad2d8307Sdrh     */
239ad2d8307Sdrh     if( pTerm->pOn && pTerm->pUsing ){
2404adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
241da93d238Sdrh         "clauses in the same join");
242ad2d8307Sdrh       return 1;
243ad2d8307Sdrh     }
244ad2d8307Sdrh 
245ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
246ad2d8307Sdrh     ** and AND operator.
247ad2d8307Sdrh     */
248ad2d8307Sdrh     if( pTerm->pOn ){
2491cc093c2Sdrh       setJoinExpr(pTerm->pOn);
250ad2d8307Sdrh       if( p->pWhere==0 ){
251ad2d8307Sdrh         p->pWhere = pTerm->pOn;
252ad2d8307Sdrh       }else{
2534adee20fSdanielk1977         p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pTerm->pOn, 0);
254ad2d8307Sdrh       }
255ad2d8307Sdrh       pTerm->pOn = 0;
256ad2d8307Sdrh     }
257ad2d8307Sdrh 
258ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
259ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
260ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
261ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
262ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
263ad2d8307Sdrh     ** not contained in both tables to be joined.
264ad2d8307Sdrh     */
265ad2d8307Sdrh     if( pTerm->pUsing ){
266ad2d8307Sdrh       IdList *pList;
267ad2d8307Sdrh       int j;
268ad2d8307Sdrh       assert( i<pSrc->nSrc-1 );
269ad2d8307Sdrh       pList = pTerm->pUsing;
270ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
271bf5cd97eSdrh         if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
272bf5cd97eSdrh             columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
2734adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
274da93d238Sdrh             "not present in both tables", pList->a[j].zName);
275ad2d8307Sdrh           return 1;
276ad2d8307Sdrh         }
277bf5cd97eSdrh         addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
278ad2d8307Sdrh       }
279ad2d8307Sdrh     }
280ad2d8307Sdrh   }
281ad2d8307Sdrh   return 0;
282ad2d8307Sdrh }
283ad2d8307Sdrh 
284ad2d8307Sdrh /*
2859bb61fe7Sdrh ** Delete the given Select structure and all of its substructures.
2869bb61fe7Sdrh */
2874adee20fSdanielk1977 void sqlite3SelectDelete(Select *p){
28882c3d636Sdrh   if( p==0 ) return;
2894adee20fSdanielk1977   sqlite3ExprListDelete(p->pEList);
2904adee20fSdanielk1977   sqlite3SrcListDelete(p->pSrc);
2914adee20fSdanielk1977   sqlite3ExprDelete(p->pWhere);
2924adee20fSdanielk1977   sqlite3ExprListDelete(p->pGroupBy);
2934adee20fSdanielk1977   sqlite3ExprDelete(p->pHaving);
2944adee20fSdanielk1977   sqlite3ExprListDelete(p->pOrderBy);
2954adee20fSdanielk1977   sqlite3SelectDelete(p->pPrior);
296a76b5dfcSdrh   sqliteFree(p->zSelect);
2979bb61fe7Sdrh   sqliteFree(p);
2989bb61fe7Sdrh }
2999bb61fe7Sdrh 
3009bb61fe7Sdrh /*
3012282792aSdrh ** Delete the aggregate information from the parse structure.
3022282792aSdrh */
3031d83f052Sdrh static void sqliteAggregateInfoReset(Parse *pParse){
3042282792aSdrh   sqliteFree(pParse->aAgg);
3052282792aSdrh   pParse->aAgg = 0;
3062282792aSdrh   pParse->nAgg = 0;
3072282792aSdrh   pParse->useAgg = 0;
3082282792aSdrh }
3092282792aSdrh 
3102282792aSdrh /*
311c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
312c926afbcSdrh ** stack into the sorter.
313c926afbcSdrh */
314c926afbcSdrh static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
315c926afbcSdrh   char *zSortOrder;
316c926afbcSdrh   int i;
317c926afbcSdrh   zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
318c926afbcSdrh   if( zSortOrder==0 ) return;
319c926afbcSdrh   for(i=0; i<pOrderBy->nExpr; i++){
32038640e15Sdrh     int order = pOrderBy->a[i].sortOrder;
32138640e15Sdrh     int type;
32238640e15Sdrh     int c;
32338640e15Sdrh     if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
32438640e15Sdrh       type = SQLITE_SO_TEXT;
32538640e15Sdrh     }else if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_NUM ){
32638640e15Sdrh       type = SQLITE_SO_NUM;
32738640e15Sdrh     }else{
328*36a3c70bSdanielk1977       type = sqlite3ExprType(pOrderBy->a[i].pExpr);
32938640e15Sdrh     }
33038640e15Sdrh     if( (order & SQLITE_SO_DIRMASK)==SQLITE_SO_ASC ){
33138640e15Sdrh       c = type==SQLITE_SO_TEXT ? 'A' : '+';
33238640e15Sdrh     }else{
33338640e15Sdrh       c = type==SQLITE_SO_TEXT ? 'D' : '-';
33438640e15Sdrh     }
33538640e15Sdrh     zSortOrder[i] = c;
3364adee20fSdanielk1977     sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr);
337c926afbcSdrh   }
338c926afbcSdrh   zSortOrder[pOrderBy->nExpr] = 0;
3394adee20fSdanielk1977   sqlite3VdbeOp3(v, OP_SortMakeKey, pOrderBy->nExpr, 0, zSortOrder, P3_DYNAMIC);
3404adee20fSdanielk1977   sqlite3VdbeAddOp(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.
3514adee20fSdanielk1977 ** See also the sqlite3AddIdxKeyType() routine.
35238640e15Sdrh */
3534adee20fSdanielk1977 void sqlite3AddKeyType(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++){
3594adee20fSdanielk1977     zType[i] = sqlite3ExprType(pEList->a[i].pExpr)==SQLITE_SO_NUM ? 'n' : 't';
36038640e15Sdrh   }
36138640e15Sdrh   zType[i] = 0;
3624adee20fSdanielk1977   sqlite3VdbeChangeP3(v, -1, zType, P3_DYNAMIC);
36338640e15Sdrh }
36438640e15Sdrh 
36538640e15Sdrh /*
3662282792aSdrh ** This routine generates the code for the inside of the inner loop
3672282792aSdrh ** of a SELECT.
36882c3d636Sdrh **
36938640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
37038640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
37138640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
37238640e15Sdrh ** datatypes for each column.
3732282792aSdrh */
3742282792aSdrh static int selectInnerLoop(
3752282792aSdrh   Parse *pParse,          /* The parser context */
376df199a25Sdrh   Select *p,              /* The complete select statement being coded */
3772282792aSdrh   ExprList *pEList,       /* List of values being extracted */
37882c3d636Sdrh   int srcTab,             /* Pull data from this table */
379967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
3802282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
3812282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
3822282792aSdrh   int eDest,              /* How to dispose of the results */
3832282792aSdrh   int iParm,              /* An argument to the disposal method */
3842282792aSdrh   int iContinue,          /* Jump here to continue with next row */
3852282792aSdrh   int iBreak              /* Jump here to break out of the inner loop */
3862282792aSdrh ){
3872282792aSdrh   Vdbe *v = pParse->pVdbe;
3882282792aSdrh   int i;
38938640e15Sdrh 
390daffd0e5Sdrh   if( v==0 ) return 0;
39138640e15Sdrh   assert( pEList!=0 );
3922282792aSdrh 
393df199a25Sdrh   /* If there was a LIMIT clause on the SELECT statement, then do the check
394df199a25Sdrh   ** to see if this row should be output.
395df199a25Sdrh   */
396df199a25Sdrh   if( pOrderBy==0 ){
3977b58daeaSdrh     if( p->iOffset>=0 ){
3984adee20fSdanielk1977       int addr = sqlite3VdbeCurrentAddr(v);
3994adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+2);
4004adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
401df199a25Sdrh     }
4027b58daeaSdrh     if( p->iLimit>=0 ){
4034adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
404df199a25Sdrh     }
405df199a25Sdrh   }
406df199a25Sdrh 
407967e8b73Sdrh   /* Pull the requested columns.
4082282792aSdrh   */
40938640e15Sdrh   if( nColumn>0 ){
410967e8b73Sdrh     for(i=0; i<nColumn; i++){
4114adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
41282c3d636Sdrh     }
41338640e15Sdrh   }else{
41438640e15Sdrh     nColumn = pEList->nExpr;
41538640e15Sdrh     for(i=0; i<pEList->nExpr; i++){
4164adee20fSdanielk1977       sqlite3ExprCode(pParse, pEList->a[i].pExpr);
41738640e15Sdrh     }
41882c3d636Sdrh   }
4192282792aSdrh 
420daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
421daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
422daffd0e5Sdrh   ** part of the result.
4232282792aSdrh   */
424f5905aa7Sdrh   if( distinct>=0 && pEList && pEList->nExpr>0 ){
4250bd1f4eaSdrh #if NULL_ALWAYS_DISTINCT
4264adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
4270bd1f4eaSdrh #endif
4284adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
429*36a3c70bSdanielk1977     sqlite3AddKeyType(v, pEList);
4304adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
4314adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
4324adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
4334adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_String, 0, 0);
4344adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
4352282792aSdrh   }
43682c3d636Sdrh 
437c926afbcSdrh   switch( eDest ){
43882c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
43982c3d636Sdrh     ** table iParm.
4402282792aSdrh     */
441c926afbcSdrh     case SRT_Union: {
4424adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
4434adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_String, 0, 0);
4444adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
445c926afbcSdrh       break;
446c926afbcSdrh     }
44782c3d636Sdrh 
4485974a30fSdrh     /* Store the result as data using a unique key.
4495974a30fSdrh     */
450c926afbcSdrh     case SRT_Table:
451c926afbcSdrh     case SRT_TempTable: {
4524adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
453c926afbcSdrh       if( pOrderBy ){
454c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
455c926afbcSdrh       }else{
4564adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
4574adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
4584adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
459c926afbcSdrh       }
460c926afbcSdrh       break;
461c926afbcSdrh     }
4625974a30fSdrh 
46382c3d636Sdrh     /* Construct a record from the query result, but instead of
46482c3d636Sdrh     ** saving that record, use it as a key to delete elements from
46582c3d636Sdrh     ** the temporary table iParm.
46682c3d636Sdrh     */
467c926afbcSdrh     case SRT_Except: {
4680bd1f4eaSdrh       int addr;
4694adee20fSdanielk1977       addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
4704adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
4714adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
472c926afbcSdrh       break;
473c926afbcSdrh     }
4742282792aSdrh 
4752282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
4762282792aSdrh     ** then there should be a single item on the stack.  Write this
4772282792aSdrh     ** item into the set table with bogus data.
4782282792aSdrh     */
479c926afbcSdrh     case SRT_Set: {
4804adee20fSdanielk1977       int addr1 = sqlite3VdbeCurrentAddr(v);
48152b36cabSdrh       int addr2;
482967e8b73Sdrh       assert( nColumn==1 );
4834adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
4844adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
4854adee20fSdanielk1977       addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
486c926afbcSdrh       if( pOrderBy ){
487c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
488c926afbcSdrh       }else{
4894adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_String, 0, 0);
4904adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
491c926afbcSdrh       }
4924adee20fSdanielk1977       sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
493c926afbcSdrh       break;
494c926afbcSdrh     }
49582c3d636Sdrh 
4962282792aSdrh     /* If this is a scalar select that is part of an expression, then
4972282792aSdrh     ** store the results in the appropriate memory cell and break out
4982282792aSdrh     ** of the scan loop.
4992282792aSdrh     */
500c926afbcSdrh     case SRT_Mem: {
501967e8b73Sdrh       assert( nColumn==1 );
502c926afbcSdrh       if( pOrderBy ){
503c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
504c926afbcSdrh       }else{
5054adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
5064adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
507c926afbcSdrh       }
508c926afbcSdrh       break;
509c926afbcSdrh     }
5102282792aSdrh 
511f46f905aSdrh     /* Send the data to the callback function.
512f46f905aSdrh     */
513f46f905aSdrh     case SRT_Callback:
514f46f905aSdrh     case SRT_Sorter: {
515f46f905aSdrh       if( pOrderBy ){
5164adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
517f46f905aSdrh         pushOntoSorter(pParse, v, pOrderBy);
518f46f905aSdrh       }else{
519f46f905aSdrh         assert( eDest==SRT_Callback );
5204adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
521f46f905aSdrh       }
522f46f905aSdrh       break;
523f46f905aSdrh     }
524f46f905aSdrh 
525142e30dfSdrh     /* Invoke a subroutine to handle the results.  The subroutine itself
526142e30dfSdrh     ** is responsible for popping the results off of the stack.
527142e30dfSdrh     */
528142e30dfSdrh     case SRT_Subroutine: {
529ac82fcf5Sdrh       if( pOrderBy ){
5304adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
531ac82fcf5Sdrh         pushOntoSorter(pParse, v, pOrderBy);
532ac82fcf5Sdrh       }else{
5334adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
534ac82fcf5Sdrh       }
535142e30dfSdrh       break;
536142e30dfSdrh     }
537142e30dfSdrh 
538d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
539d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
540d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
541d7489c39Sdrh     ** about the actual results of the select.
542d7489c39Sdrh     */
543c926afbcSdrh     default: {
544f46f905aSdrh       assert( eDest==SRT_Discard );
5454adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
546c926afbcSdrh       break;
547c926afbcSdrh     }
548c926afbcSdrh   }
54982c3d636Sdrh   return 0;
55082c3d636Sdrh }
55182c3d636Sdrh 
55282c3d636Sdrh /*
553d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
554d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
555d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
556d8bc7086Sdrh ** routine generates the code needed to do that.
557d8bc7086Sdrh */
558c926afbcSdrh static void generateSortTail(
559c926afbcSdrh   Select *p,       /* The SELECT statement */
560c926afbcSdrh   Vdbe *v,         /* Generate code into this VDBE */
561c926afbcSdrh   int nColumn,     /* Number of columns of data */
562c926afbcSdrh   int eDest,       /* Write the sorted results here */
563c926afbcSdrh   int iParm        /* Optional parameter associated with eDest */
564c926afbcSdrh ){
5654adee20fSdanielk1977   int end1 = sqlite3VdbeMakeLabel(v);
5664adee20fSdanielk1977   int end2 = sqlite3VdbeMakeLabel(v);
567d8bc7086Sdrh   int addr;
568f46f905aSdrh   if( eDest==SRT_Sorter ) return;
5694adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Sort, 0, 0);
5704adee20fSdanielk1977   addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
5717b58daeaSdrh   if( p->iOffset>=0 ){
5724adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+4);
5734adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
5744adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
575df199a25Sdrh   }
5767b58daeaSdrh   if( p->iLimit>=0 ){
5774adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, end2);
578df199a25Sdrh   }
579c926afbcSdrh   switch( eDest ){
580c926afbcSdrh     case SRT_Callback: {
5814adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_SortCallback, nColumn, 0);
582c926afbcSdrh       break;
583c926afbcSdrh     }
584c926afbcSdrh     case SRT_Table:
585c926afbcSdrh     case SRT_TempTable: {
5864adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
5874adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
5884adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
589c926afbcSdrh       break;
590c926afbcSdrh     }
591c926afbcSdrh     case SRT_Set: {
592c926afbcSdrh       assert( nColumn==1 );
5934adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
5944adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
5954adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
5964adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_String, 0, 0);
5974adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
598c926afbcSdrh       break;
599c926afbcSdrh     }
600c926afbcSdrh     case SRT_Mem: {
601c926afbcSdrh       assert( nColumn==1 );
6024adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
6034adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
604c926afbcSdrh       break;
605c926afbcSdrh     }
606ac82fcf5Sdrh     case SRT_Subroutine: {
607ac82fcf5Sdrh       int i;
608ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
6094adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
610ac82fcf5Sdrh       }
6114adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
6124adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
613ac82fcf5Sdrh       break;
614ac82fcf5Sdrh     }
615c926afbcSdrh     default: {
616f46f905aSdrh       /* Do nothing */
617c926afbcSdrh       break;
618c926afbcSdrh     }
619c926afbcSdrh   }
6204adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
6214adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, end2);
6224adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
6234adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, end1);
6244adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
625d8bc7086Sdrh }
626d8bc7086Sdrh 
627d8bc7086Sdrh /*
628fcb78a49Sdrh ** Generate code that will tell the VDBE the datatypes of
629fcb78a49Sdrh ** columns in the result set.
630e78e8284Sdrh **
631e78e8284Sdrh ** This routine only generates code if the "PRAGMA show_datatypes=on"
632e78e8284Sdrh ** has been executed.  The datatypes are reported out in the azCol
633e78e8284Sdrh ** parameter to the callback function.  The first N azCol[] entries
634e78e8284Sdrh ** are the names of the columns, and the second N entries are the
635e78e8284Sdrh ** datatypes for the columns.
636e78e8284Sdrh **
637e78e8284Sdrh ** The "datatype" for a result that is a column of a type is the
638e78e8284Sdrh ** datatype definition extracted from the CREATE TABLE statement.
639e78e8284Sdrh ** The datatype for an expression is either TEXT or NUMERIC.  The
640e78e8284Sdrh ** datatype for a ROWID field is INTEGER.
641fcb78a49Sdrh */
642fcb78a49Sdrh static void generateColumnTypes(
643fcb78a49Sdrh   Parse *pParse,      /* Parser context */
644fcb78a49Sdrh   SrcList *pTabList,  /* List of tables */
645fcb78a49Sdrh   ExprList *pEList    /* Expressions defining the result set */
646fcb78a49Sdrh ){
647fcb78a49Sdrh   Vdbe *v = pParse->pVdbe;
6486a3ea0e6Sdrh   int i, j;
649fcb78a49Sdrh   for(i=0; i<pEList->nExpr; i++){
650fcb78a49Sdrh     Expr *p = pEList->a[i].pExpr;
651fcb78a49Sdrh     char *zType = 0;
652fcb78a49Sdrh     if( p==0 ) continue;
653fcb78a49Sdrh     if( p->op==TK_COLUMN && pTabList ){
6546a3ea0e6Sdrh       Table *pTab;
655fcb78a49Sdrh       int iCol = p->iColumn;
6566a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
6576a3ea0e6Sdrh       assert( j<pTabList->nSrc );
6586a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
659fcb78a49Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
660fcb78a49Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
661fcb78a49Sdrh       if( iCol<0 ){
662fcb78a49Sdrh         zType = "INTEGER";
663fcb78a49Sdrh       }else{
664fcb78a49Sdrh         zType = pTab->aCol[iCol].zType;
665fcb78a49Sdrh       }
666fcb78a49Sdrh     }else{
6674adee20fSdanielk1977       if( sqlite3ExprType(p)==SQLITE_SO_TEXT ){
668fcb78a49Sdrh         zType = "TEXT";
669fcb78a49Sdrh       }else{
670fcb78a49Sdrh         zType = "NUMERIC";
671fcb78a49Sdrh       }
672fcb78a49Sdrh     }
6734adee20fSdanielk1977     sqlite3VdbeOp3(v, OP_ColumnName, i + pEList->nExpr, 0, zType, 0);
674fcb78a49Sdrh   }
675fcb78a49Sdrh }
676fcb78a49Sdrh 
677fcb78a49Sdrh /*
678fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
679fcb78a49Sdrh ** in the result set.  This information is used to provide the
680fcabd464Sdrh ** azCol[] values in the callback.
68182c3d636Sdrh */
682832508b7Sdrh static void generateColumnNames(
683832508b7Sdrh   Parse *pParse,      /* Parser context */
684ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
685832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
686832508b7Sdrh ){
687d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
6886a3ea0e6Sdrh   int i, j;
689fcabd464Sdrh   sqlite *db = pParse->db;
690fcabd464Sdrh   int fullNames, shortNames;
691fcabd464Sdrh 
692d6502758Sdrh   assert( v!=0 );
6936f8a503dSdanielk1977   if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
694d8bc7086Sdrh   pParse->colNamesSet = 1;
695fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
696fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
69782c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
69882c3d636Sdrh     Expr *p;
699d6502758Sdrh     int p2 = i==pEList->nExpr-1;
7005a38705eSdrh     p = pEList->a[i].pExpr;
7015a38705eSdrh     if( p==0 ) continue;
70282c3d636Sdrh     if( pEList->a[i].zName ){
70382c3d636Sdrh       char *zName = pEList->a[i].zName;
7044adee20fSdanielk1977       sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
70582c3d636Sdrh       continue;
70682c3d636Sdrh     }
707fa173a76Sdrh     if( p->op==TK_COLUMN && pTabList ){
7086a3ea0e6Sdrh       Table *pTab;
70997665873Sdrh       char *zCol;
7108aff1015Sdrh       int iCol = p->iColumn;
7116a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
7126a3ea0e6Sdrh       assert( j<pTabList->nSrc );
7136a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
7148aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
71597665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
716b1363206Sdrh       if( iCol<0 ){
717b1363206Sdrh         zCol = "_ROWID_";
718b1363206Sdrh       }else{
719b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
720b1363206Sdrh       }
721fcabd464Sdrh       if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
7224adee20fSdanielk1977         int addr = sqlite3VdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
7234adee20fSdanielk1977         sqlite3VdbeCompressSpace(v, addr);
724fcabd464Sdrh       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
72582c3d636Sdrh         char *zName = 0;
72682c3d636Sdrh         char *zTab;
72782c3d636Sdrh 
7286a3ea0e6Sdrh         zTab = pTabList->a[j].zAlias;
729fcabd464Sdrh         if( fullNames || zTab==0 ) zTab = pTab->zName;
7304adee20fSdanielk1977         sqlite3SetString(&zName, zTab, ".", zCol, 0);
7314adee20fSdanielk1977         sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, P3_DYNAMIC);
73282c3d636Sdrh       }else{
7334adee20fSdanielk1977         sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zCol, 0);
73482c3d636Sdrh       }
7356977fea8Sdrh     }else if( p->span.z && p->span.z[0] ){
7364adee20fSdanielk1977       int addr = sqlite3VdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
7374adee20fSdanielk1977       sqlite3VdbeCompressSpace(v, addr);
7381bee3d7bSdrh     }else{
7391bee3d7bSdrh       char zName[30];
7401bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
7411bee3d7bSdrh       sprintf(zName, "column%d", i+1);
7424adee20fSdanielk1977       sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
74382c3d636Sdrh     }
74482c3d636Sdrh   }
7455080aaa7Sdrh }
74682c3d636Sdrh 
74782c3d636Sdrh /*
748d8bc7086Sdrh ** Name of the connection operator, used for error messages.
749d8bc7086Sdrh */
750d8bc7086Sdrh static const char *selectOpName(int id){
751d8bc7086Sdrh   char *z;
752d8bc7086Sdrh   switch( id ){
753d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
754d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
755d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
756d8bc7086Sdrh     default:           z = "UNION";       break;
757d8bc7086Sdrh   }
758d8bc7086Sdrh   return z;
759d8bc7086Sdrh }
760d8bc7086Sdrh 
761d8bc7086Sdrh /*
762315555caSdrh ** Forward declaration
763315555caSdrh */
764315555caSdrh static int fillInColumnList(Parse*, Select*);
765315555caSdrh 
766315555caSdrh /*
76722f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
76822f70c32Sdrh ** the result set of that SELECT.
76922f70c32Sdrh */
7704adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
77122f70c32Sdrh   Table *pTab;
772b733d037Sdrh   int i, j;
77322f70c32Sdrh   ExprList *pEList;
774b733d037Sdrh   Column *aCol;
77522f70c32Sdrh 
77622f70c32Sdrh   if( fillInColumnList(pParse, pSelect) ){
77722f70c32Sdrh     return 0;
77822f70c32Sdrh   }
77922f70c32Sdrh   pTab = sqliteMalloc( sizeof(Table) );
78022f70c32Sdrh   if( pTab==0 ){
78122f70c32Sdrh     return 0;
78222f70c32Sdrh   }
78322f70c32Sdrh   pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
78422f70c32Sdrh   pEList = pSelect->pEList;
78522f70c32Sdrh   pTab->nCol = pEList->nExpr;
786417be79cSdrh   assert( pTab->nCol>0 );
787b733d037Sdrh   pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
78822f70c32Sdrh   for(i=0; i<pTab->nCol; i++){
789b733d037Sdrh     Expr *p, *pR;
79022f70c32Sdrh     if( pEList->a[i].zName ){
791b733d037Sdrh       aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
792b733d037Sdrh     }else if( (p=pEList->a[i].pExpr)->op==TK_DOT
793b733d037Sdrh                && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
794b733d037Sdrh       int cnt;
7954adee20fSdanielk1977       sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, 0);
796b733d037Sdrh       for(j=cnt=0; j<i; j++){
7974adee20fSdanielk1977         if( sqlite3StrICmp(aCol[j].zName, aCol[i].zName)==0 ){
798b733d037Sdrh           int n;
799b733d037Sdrh           char zBuf[30];
800b733d037Sdrh           sprintf(zBuf,"_%d",++cnt);
801b733d037Sdrh           n = strlen(zBuf);
8024adee20fSdanielk1977           sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, zBuf, n,0);
803b733d037Sdrh           j = -1;
804b733d037Sdrh         }
805b733d037Sdrh       }
806b733d037Sdrh     }else if( p->span.z && p->span.z[0] ){
8074adee20fSdanielk1977       sqlite3SetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
80822f70c32Sdrh     }else{
80922f70c32Sdrh       char zBuf[30];
81022f70c32Sdrh       sprintf(zBuf, "column%d", i+1);
81122f70c32Sdrh       pTab->aCol[i].zName = sqliteStrDup(zBuf);
81222f70c32Sdrh     }
81322f70c32Sdrh   }
81422f70c32Sdrh   pTab->iPKey = -1;
81522f70c32Sdrh   return pTab;
81622f70c32Sdrh }
81722f70c32Sdrh 
81822f70c32Sdrh /*
819ad2d8307Sdrh ** For the given SELECT statement, do three things.
820d8bc7086Sdrh **
821ad3cab52Sdrh **    (1)  Fill in the pTabList->a[].pTab fields in the SrcList that
82263eb5f29Sdrh **         defines the set of tables that should be scanned.  For views,
82363eb5f29Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
82463eb5f29Sdrh **         that implements the view.  A copy is made of the view's SELECT
82563eb5f29Sdrh **         statement so that we can freely modify or delete that statement
82663eb5f29Sdrh **         without worrying about messing up the presistent representation
82763eb5f29Sdrh **         of the view.
828d8bc7086Sdrh **
829ad2d8307Sdrh **    (2)  Add terms to the WHERE clause to accomodate the NATURAL keyword
830ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
831ad2d8307Sdrh **
832ad2d8307Sdrh **    (3)  Scan the list of columns in the result set (pEList) looking
83354473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
83454473229Sdrh **         If found, expand each "*" to be every column in every table
83554473229Sdrh **         and TABLE.* to be every column in TABLE.
836d8bc7086Sdrh **
837d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
838d8bc7086Sdrh ** in pParse and return non-zero.
839d8bc7086Sdrh */
840d8bc7086Sdrh static int fillInColumnList(Parse *pParse, Select *p){
84154473229Sdrh   int i, j, k, rc;
842ad3cab52Sdrh   SrcList *pTabList;
843daffd0e5Sdrh   ExprList *pEList;
844a76b5dfcSdrh   Table *pTab;
845daffd0e5Sdrh 
846daffd0e5Sdrh   if( p==0 || p->pSrc==0 ) return 1;
847daffd0e5Sdrh   pTabList = p->pSrc;
848daffd0e5Sdrh   pEList = p->pEList;
849d8bc7086Sdrh 
850d8bc7086Sdrh   /* Look up every table in the table list.
851d8bc7086Sdrh   */
852ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
853d8bc7086Sdrh     if( pTabList->a[i].pTab ){
854d8bc7086Sdrh       /* This routine has run before!  No need to continue */
855d8bc7086Sdrh       return 0;
856d8bc7086Sdrh     }
857daffd0e5Sdrh     if( pTabList->a[i].zName==0 ){
85822f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
85922f70c32Sdrh       assert( pTabList->a[i].pSelect!=0 );
860ad2d8307Sdrh       if( pTabList->a[i].zAlias==0 ){
861ad2d8307Sdrh         char zFakeName[60];
862ad2d8307Sdrh         sprintf(zFakeName, "sqlite_subquery_%p_",
863ad2d8307Sdrh            (void*)pTabList->a[i].pSelect);
8644adee20fSdanielk1977         sqlite3SetString(&pTabList->a[i].zAlias, zFakeName, 0);
865ad2d8307Sdrh       }
86622f70c32Sdrh       pTabList->a[i].pTab = pTab =
8674adee20fSdanielk1977         sqlite3ResultSetOfSelect(pParse, pTabList->a[i].zAlias,
86822f70c32Sdrh                                         pTabList->a[i].pSelect);
86922f70c32Sdrh       if( pTab==0 ){
870daffd0e5Sdrh         return 1;
871daffd0e5Sdrh       }
8725cf590c1Sdrh       /* The isTransient flag indicates that the Table structure has been
8735cf590c1Sdrh       ** dynamically allocated and may be freed at any time.  In other words,
8745cf590c1Sdrh       ** pTab is not pointing to a persistent table structure that defines
8755cf590c1Sdrh       ** part of the schema. */
87622f70c32Sdrh       pTab->isTransient = 1;
87722f70c32Sdrh     }else{
878a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
879a76b5dfcSdrh       pTabList->a[i].pTab = pTab =
8804adee20fSdanielk1977         sqlite3LocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
881a76b5dfcSdrh       if( pTab==0 ){
882d8bc7086Sdrh         return 1;
883d8bc7086Sdrh       }
884a76b5dfcSdrh       if( pTab->pSelect ){
88563eb5f29Sdrh         /* We reach here if the named table is a really a view */
8864adee20fSdanielk1977         if( sqlite3ViewGetColumnNames(pParse, pTab) ){
887417be79cSdrh           return 1;
888417be79cSdrh         }
88963eb5f29Sdrh         /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
89063eb5f29Sdrh         ** view within a view.  The SELECT structure has already been
89163eb5f29Sdrh         ** copied by the outer view so we can skip the copy step here
89263eb5f29Sdrh         ** in the inner view.
89363eb5f29Sdrh         */
89463eb5f29Sdrh         if( pTabList->a[i].pSelect==0 ){
8954adee20fSdanielk1977           pTabList->a[i].pSelect = sqlite3SelectDup(pTab->pSelect);
896a76b5dfcSdrh         }
897d8bc7086Sdrh       }
89822f70c32Sdrh     }
89963eb5f29Sdrh   }
900d8bc7086Sdrh 
901ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
902ad2d8307Sdrh   */
903ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
904ad2d8307Sdrh 
9057c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
90654473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
90754473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
9087c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
9097c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
9107c917d19Sdrh   ** each one to the list of all columns in all tables.
91154473229Sdrh   **
91254473229Sdrh   ** The first loop just checks to see if there are any "*" operators
91354473229Sdrh   ** that need expanding.
914d8bc7086Sdrh   */
9157c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
91654473229Sdrh     Expr *pE = pEList->a[k].pExpr;
91754473229Sdrh     if( pE->op==TK_ALL ) break;
91854473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
91954473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
9207c917d19Sdrh   }
92154473229Sdrh   rc = 0;
9227c917d19Sdrh   if( k<pEList->nExpr ){
92354473229Sdrh     /*
92454473229Sdrh     ** If we get here it means the result set contains one or more "*"
92554473229Sdrh     ** operators that need to be expanded.  Loop through each expression
92654473229Sdrh     ** in the result set and expand them one by one.
92754473229Sdrh     */
9287c917d19Sdrh     struct ExprList_item *a = pEList->a;
9297c917d19Sdrh     ExprList *pNew = 0;
9307c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
93154473229Sdrh       Expr *pE = a[k].pExpr;
93254473229Sdrh       if( pE->op!=TK_ALL &&
93354473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
93454473229Sdrh         /* This particular expression does not need to be expanded.
93554473229Sdrh         */
9364adee20fSdanielk1977         pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
9377c917d19Sdrh         pNew->a[pNew->nExpr-1].zName = a[k].zName;
9387c917d19Sdrh         a[k].pExpr = 0;
9397c917d19Sdrh         a[k].zName = 0;
9407c917d19Sdrh       }else{
94154473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
94254473229Sdrh         ** expanded. */
94354473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
94454473229Sdrh         Token *pName;           /* text of name of TABLE */
94554473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
94654473229Sdrh           pName = &pE->pLeft->token;
94754473229Sdrh         }else{
94854473229Sdrh           pName = 0;
94954473229Sdrh         }
950ad3cab52Sdrh         for(i=0; i<pTabList->nSrc; i++){
951d8bc7086Sdrh           Table *pTab = pTabList->a[i].pTab;
95254473229Sdrh           char *zTabName = pTabList->a[i].zAlias;
95354473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
95454473229Sdrh             zTabName = pTab->zName;
95554473229Sdrh           }
95654473229Sdrh           if( pName && (zTabName==0 || zTabName[0]==0 ||
9574adee20fSdanielk1977                  sqlite3StrNICmp(pName->z, zTabName, pName->n)!=0 ||
958c754fa54Sdrh                  zTabName[pName->n]!=0) ){
95954473229Sdrh             continue;
96054473229Sdrh           }
96154473229Sdrh           tableSeen = 1;
962d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
96322f70c32Sdrh             Expr *pExpr, *pLeft, *pRight;
964ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
965ad2d8307Sdrh 
966ad2d8307Sdrh             if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
967ad2d8307Sdrh                 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
968ad2d8307Sdrh               /* In a NATURAL join, omit the join columns from the
969ad2d8307Sdrh               ** table on the right */
970ad2d8307Sdrh               continue;
971ad2d8307Sdrh             }
9724adee20fSdanielk1977             if( i>0 && sqlite3IdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
973ad2d8307Sdrh               /* In a join with a USING clause, omit columns in the
974ad2d8307Sdrh               ** using clause from the table on the right. */
975ad2d8307Sdrh               continue;
976ad2d8307Sdrh             }
9774adee20fSdanielk1977             pRight = sqlite3Expr(TK_ID, 0, 0, 0);
97822f70c32Sdrh             if( pRight==0 ) break;
979ad2d8307Sdrh             pRight->token.z = zName;
980ad2d8307Sdrh             pRight->token.n = strlen(zName);
9814b59ab5eSdrh             pRight->token.dyn = 0;
9824b59ab5eSdrh             if( zTabName && pTabList->nSrc>1 ){
9834adee20fSdanielk1977               pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
9844adee20fSdanielk1977               pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
98522f70c32Sdrh               if( pExpr==0 ) break;
9864b59ab5eSdrh               pLeft->token.z = zTabName;
9874b59ab5eSdrh               pLeft->token.n = strlen(zTabName);
9884b59ab5eSdrh               pLeft->token.dyn = 0;
9894adee20fSdanielk1977               sqlite3SetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
9906977fea8Sdrh               pExpr->span.n = strlen(pExpr->span.z);
9916977fea8Sdrh               pExpr->span.dyn = 1;
9926977fea8Sdrh               pExpr->token.z = 0;
9936977fea8Sdrh               pExpr->token.n = 0;
9946977fea8Sdrh               pExpr->token.dyn = 0;
99522f70c32Sdrh             }else{
99622f70c32Sdrh               pExpr = pRight;
9976977fea8Sdrh               pExpr->span = pExpr->token;
99822f70c32Sdrh             }
9994adee20fSdanielk1977             pNew = sqlite3ExprListAppend(pNew, pExpr, 0);
1000d8bc7086Sdrh           }
1001d8bc7086Sdrh         }
100254473229Sdrh         if( !tableSeen ){
1003f5db2d3eSdrh           if( pName ){
10044adee20fSdanielk1977             sqlite3ErrorMsg(pParse, "no such table: %T", pName);
1005f5db2d3eSdrh           }else{
10064adee20fSdanielk1977             sqlite3ErrorMsg(pParse, "no tables specified");
1007f5db2d3eSdrh           }
100854473229Sdrh           rc = 1;
100954473229Sdrh         }
10107c917d19Sdrh       }
10117c917d19Sdrh     }
10124adee20fSdanielk1977     sqlite3ExprListDelete(pEList);
10137c917d19Sdrh     p->pEList = pNew;
1014d8bc7086Sdrh   }
101554473229Sdrh   return rc;
1016d8bc7086Sdrh }
1017d8bc7086Sdrh 
1018d8bc7086Sdrh /*
1019ff78bd2fSdrh ** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1020ff78bd2fSdrh ** in a select structure.  It just sets the pointers to NULL.  This
1021ff78bd2fSdrh ** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1022ff78bd2fSdrh ** pointer is not NULL, this routine is called recursively on that pointer.
1023ff78bd2fSdrh **
1024ff78bd2fSdrh ** This routine is called on the Select structure that defines a
1025ff78bd2fSdrh ** VIEW in order to undo any bindings to tables.  This is necessary
1026ff78bd2fSdrh ** because those tables might be DROPed by a subsequent SQL command.
10275cf590c1Sdrh ** If the bindings are not removed, then the Select.pSrc->a[].pTab field
10285cf590c1Sdrh ** will be left pointing to a deallocated Table structure after the
10295cf590c1Sdrh ** DROP and a coredump will occur the next time the VIEW is used.
1030ff78bd2fSdrh */
10314adee20fSdanielk1977 void sqlite3SelectUnbind(Select *p){
1032ff78bd2fSdrh   int i;
1033ad3cab52Sdrh   SrcList *pSrc = p->pSrc;
1034ff78bd2fSdrh   Table *pTab;
1035ff78bd2fSdrh   if( p==0 ) return;
1036ad3cab52Sdrh   for(i=0; i<pSrc->nSrc; i++){
1037ff78bd2fSdrh     if( (pTab = pSrc->a[i].pTab)!=0 ){
1038ff78bd2fSdrh       if( pTab->isTransient ){
10394adee20fSdanielk1977         sqlite3DeleteTable(0, pTab);
1040ff78bd2fSdrh       }
1041ff78bd2fSdrh       pSrc->a[i].pTab = 0;
1042ff78bd2fSdrh       if( pSrc->a[i].pSelect ){
10434adee20fSdanielk1977         sqlite3SelectUnbind(pSrc->a[i].pSelect);
1044ff78bd2fSdrh       }
1045ff78bd2fSdrh     }
1046ff78bd2fSdrh   }
1047ff78bd2fSdrh }
1048ff78bd2fSdrh 
1049ff78bd2fSdrh /*
1050d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with
1051d8bc7086Sdrh ** columns in a result.  For each ORDER BY expression, the opcode of
1052967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of
1053d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable
1054d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter.
1055d8bc7086Sdrh **
1056d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first.  A match
1057d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT.
1058d8bc7086Sdrh **
1059d8bc7086Sdrh ** Any entry that does not match is flagged as an error.  The number
1060d8bc7086Sdrh ** of errors is returned.
1061fcb78a49Sdrh **
1062fcb78a49Sdrh ** This routine does NOT correctly initialize the Expr.dataType  field
1063fcb78a49Sdrh ** of the ORDER BY expressions.  The multiSelectSortOrder() routine
1064fcb78a49Sdrh ** must be called to do that after the individual select statements
1065fcb78a49Sdrh ** have all been analyzed.  This routine is unable to compute Expr.dataType
1066fcb78a49Sdrh ** because it must be called before the individual select statements
1067fcb78a49Sdrh ** have been analyzed.
1068d8bc7086Sdrh */
1069d8bc7086Sdrh static int matchOrderbyToColumn(
1070d8bc7086Sdrh   Parse *pParse,          /* A place to leave error messages */
1071d8bc7086Sdrh   Select *pSelect,        /* Match to result columns of this SELECT */
1072d8bc7086Sdrh   ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
1073e4de1febSdrh   int iTable,             /* Insert this value in iTable */
1074d8bc7086Sdrh   int mustComplete        /* If TRUE all ORDER BYs must match */
1075d8bc7086Sdrh ){
1076d8bc7086Sdrh   int nErr = 0;
1077d8bc7086Sdrh   int i, j;
1078d8bc7086Sdrh   ExprList *pEList;
1079d8bc7086Sdrh 
1080daffd0e5Sdrh   if( pSelect==0 || pOrderBy==0 ) return 1;
1081d8bc7086Sdrh   if( mustComplete ){
1082d8bc7086Sdrh     for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1083d8bc7086Sdrh   }
1084d8bc7086Sdrh   if( fillInColumnList(pParse, pSelect) ){
1085d8bc7086Sdrh     return 1;
1086d8bc7086Sdrh   }
1087d8bc7086Sdrh   if( pSelect->pPrior ){
108892cd52f5Sdrh     if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
108992cd52f5Sdrh       return 1;
109092cd52f5Sdrh     }
1091d8bc7086Sdrh   }
1092d8bc7086Sdrh   pEList = pSelect->pEList;
1093d8bc7086Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
1094d8bc7086Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
1095e4de1febSdrh     int iCol = -1;
1096d8bc7086Sdrh     if( pOrderBy->a[i].done ) continue;
10974adee20fSdanielk1977     if( sqlite3ExprIsInteger(pE, &iCol) ){
1098e4de1febSdrh       if( iCol<=0 || iCol>pEList->nExpr ){
10994adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
1100da93d238Sdrh           "ORDER BY position %d should be between 1 and %d",
1101e4de1febSdrh           iCol, pEList->nExpr);
1102e4de1febSdrh         nErr++;
1103e4de1febSdrh         break;
1104e4de1febSdrh       }
1105fcb78a49Sdrh       if( !mustComplete ) continue;
1106e4de1febSdrh       iCol--;
1107e4de1febSdrh     }
1108e4de1febSdrh     for(j=0; iCol<0 && j<pEList->nExpr; j++){
11094cfa7934Sdrh       if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
1110a76b5dfcSdrh         char *zName, *zLabel;
1111a76b5dfcSdrh         zName = pEList->a[j].zName;
1112a76b5dfcSdrh         assert( pE->token.z );
1113a76b5dfcSdrh         zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
11144adee20fSdanielk1977         sqlite3Dequote(zLabel);
11154adee20fSdanielk1977         if( sqlite3StrICmp(zName, zLabel)==0 ){
1116e4de1febSdrh           iCol = j;
1117d8bc7086Sdrh         }
11186e142f54Sdrh         sqliteFree(zLabel);
1119d8bc7086Sdrh       }
11204adee20fSdanielk1977       if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
1121e4de1febSdrh         iCol = j;
1122d8bc7086Sdrh       }
1123e4de1febSdrh     }
1124e4de1febSdrh     if( iCol>=0 ){
1125967e8b73Sdrh       pE->op = TK_COLUMN;
1126e4de1febSdrh       pE->iColumn = iCol;
1127d8bc7086Sdrh       pE->iTable = iTable;
1128d8bc7086Sdrh       pOrderBy->a[i].done = 1;
1129d8bc7086Sdrh     }
1130e4de1febSdrh     if( iCol<0 && mustComplete ){
11314adee20fSdanielk1977       sqlite3ErrorMsg(pParse,
1132da93d238Sdrh         "ORDER BY term number %d does not match any result column", i+1);
1133d8bc7086Sdrh       nErr++;
1134d8bc7086Sdrh       break;
1135d8bc7086Sdrh     }
1136d8bc7086Sdrh   }
1137d8bc7086Sdrh   return nErr;
1138d8bc7086Sdrh }
1139d8bc7086Sdrh 
1140d8bc7086Sdrh /*
1141d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1142d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1143d8bc7086Sdrh */
11444adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1145d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1146d8bc7086Sdrh   if( v==0 ){
11474adee20fSdanielk1977     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1148d8bc7086Sdrh   }
1149d8bc7086Sdrh   return v;
1150d8bc7086Sdrh }
1151d8bc7086Sdrh 
1152fcb78a49Sdrh /*
1153fcb78a49Sdrh ** This routine sets the Expr.dataType field on all elements of
1154fcb78a49Sdrh ** the pOrderBy expression list.  The pOrderBy list will have been
1155fcb78a49Sdrh ** set up by matchOrderbyToColumn().  Hence each expression has
1156fcb78a49Sdrh ** a TK_COLUMN as its root node.  The Expr.iColumn refers to a
1157fcb78a49Sdrh ** column in the result set.   The datatype is set to SQLITE_SO_TEXT
1158fcb78a49Sdrh ** if the corresponding column in p and every SELECT to the left of
1159fcb78a49Sdrh ** p has a datatype of SQLITE_SO_TEXT.  If the cooressponding column
1160fcb78a49Sdrh ** in p or any of the left SELECTs is SQLITE_SO_NUM, then the datatype
1161fcb78a49Sdrh ** of the order-by expression is set to SQLITE_SO_NUM.
1162fcb78a49Sdrh **
1163fcb78a49Sdrh ** Examples:
1164fcb78a49Sdrh **
1165e78e8284Sdrh **     CREATE TABLE one(a INTEGER, b TEXT);
1166e78e8284Sdrh **     CREATE TABLE two(c VARCHAR(5), d FLOAT);
1167e78e8284Sdrh **
1168e78e8284Sdrh **     SELECT b, b FROM one UNION SELECT d, c FROM two ORDER BY 1, 2;
1169e78e8284Sdrh **
1170e78e8284Sdrh ** The primary sort key will use SQLITE_SO_NUM because the "d" in
1171e78e8284Sdrh ** the second SELECT is numeric.  The 1st column of the first SELECT
1172e78e8284Sdrh ** is text but that does not matter because a numeric always overrides
1173e78e8284Sdrh ** a text.
1174e78e8284Sdrh **
1175e78e8284Sdrh ** The secondary key will use the SQLITE_SO_TEXT sort order because
1176e78e8284Sdrh ** both the (second) "b" in the first SELECT and the "c" in the second
1177e78e8284Sdrh ** SELECT have a datatype of text.
1178fcb78a49Sdrh */
1179fcb78a49Sdrh static void multiSelectSortOrder(Select *p, ExprList *pOrderBy){
1180fcb78a49Sdrh   int i;
1181fcb78a49Sdrh   ExprList *pEList;
1182fcb78a49Sdrh   if( pOrderBy==0 ) return;
1183fcb78a49Sdrh   if( p==0 ){
1184fcb78a49Sdrh     for(i=0; i<pOrderBy->nExpr; i++){
1185fcb78a49Sdrh       pOrderBy->a[i].pExpr->dataType = SQLITE_SO_TEXT;
1186fcb78a49Sdrh     }
1187fcb78a49Sdrh     return;
1188fcb78a49Sdrh   }
1189fcb78a49Sdrh   multiSelectSortOrder(p->pPrior, pOrderBy);
1190fcb78a49Sdrh   pEList = p->pEList;
1191fcb78a49Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
1192fcb78a49Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
1193fcb78a49Sdrh     if( pE->dataType==SQLITE_SO_NUM ) continue;
1194fcb78a49Sdrh     assert( pE->iColumn>=0 );
1195fcb78a49Sdrh     if( pEList->nExpr>pE->iColumn ){
11964adee20fSdanielk1977       pE->dataType = sqlite3ExprType(pEList->a[pE->iColumn].pExpr);
1197fcb78a49Sdrh     }
1198fcb78a49Sdrh   }
1199fcb78a49Sdrh }
1200d8bc7086Sdrh 
1201d8bc7086Sdrh /*
12027b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
12037b58daeaSdrh ** nLimit and nOffset fields.  nLimit and nOffset hold the integers
12047b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
12057b58daeaSdrh ** keywords.  Or that hold -1 and 0 if those keywords are omitted.
12067b58daeaSdrh ** iLimit and iOffset are the integer memory register numbers for
12077b58daeaSdrh ** counters used to compute the limit and offset.  If there is no
12087b58daeaSdrh ** limit and/or offset, then iLimit and iOffset are negative.
12097b58daeaSdrh **
12107b58daeaSdrh ** This routine changes the values if iLimit and iOffset only if
12117b58daeaSdrh ** a limit or offset is defined by nLimit and nOffset.  iLimit and
12127b58daeaSdrh ** iOffset should have been preset to appropriate default values
12137b58daeaSdrh ** (usually but not always -1) prior to calling this routine.
12147b58daeaSdrh ** Only if nLimit>=0 or nOffset>0 do the limit registers get
12157b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
12167b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
12177b58daeaSdrh ** SELECT statements.
12187b58daeaSdrh */
12197b58daeaSdrh static void computeLimitRegisters(Parse *pParse, Select *p){
12207b58daeaSdrh   /*
12217b58daeaSdrh   ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
12227b58daeaSdrh   ** all rows.  It is the same as no limit. If the comparision is
12237b58daeaSdrh   ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
12247b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
12257b58daeaSdrh   ** contraversy about what the correct behavior should be.
12267b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
12277b58daeaSdrh   ** no rows.
12287b58daeaSdrh   */
12297b58daeaSdrh   if( p->nLimit>=0 ){
12307b58daeaSdrh     int iMem = pParse->nMem++;
12314adee20fSdanielk1977     Vdbe *v = sqlite3GetVdbe(pParse);
12327b58daeaSdrh     if( v==0 ) return;
12334adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, -p->nLimit, 0);
12344adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
12357b58daeaSdrh     p->iLimit = iMem;
12367b58daeaSdrh   }
12377b58daeaSdrh   if( p->nOffset>0 ){
12387b58daeaSdrh     int iMem = pParse->nMem++;
12394adee20fSdanielk1977     Vdbe *v = sqlite3GetVdbe(pParse);
12407b58daeaSdrh     if( v==0 ) return;
12414adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, -p->nOffset, 0);
12424adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
12437b58daeaSdrh     p->iOffset = iMem;
12447b58daeaSdrh   }
12457b58daeaSdrh }
12467b58daeaSdrh 
12477b58daeaSdrh /*
124882c3d636Sdrh ** This routine is called to process a query that is really the union
124982c3d636Sdrh ** or intersection of two or more separate queries.
1250c926afbcSdrh **
1251e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1252e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1253e78e8284Sdrh ** in which case this routine will be called recursively.
1254e78e8284Sdrh **
1255e78e8284Sdrh ** The results of the total query are to be written into a destination
1256e78e8284Sdrh ** of type eDest with parameter iParm.
1257e78e8284Sdrh **
1258e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1259e78e8284Sdrh **
1260e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1261e78e8284Sdrh **
1262e78e8284Sdrh ** This statement is parsed up as follows:
1263e78e8284Sdrh **
1264e78e8284Sdrh **     SELECT c FROM t3
1265e78e8284Sdrh **      |
1266e78e8284Sdrh **      `----->  SELECT b FROM t2
1267e78e8284Sdrh **                |
12684b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1269e78e8284Sdrh **
1270e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1271e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1272e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1273e78e8284Sdrh **
1274e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1275e78e8284Sdrh ** individual selects always group from left to right.
127682c3d636Sdrh */
127782c3d636Sdrh static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
127810e5e3cfSdrh   int rc;             /* Success code from a subroutine */
127910e5e3cfSdrh   Select *pPrior;     /* Another SELECT immediately to our left */
128010e5e3cfSdrh   Vdbe *v;            /* Generate code to this VDBE */
128182c3d636Sdrh 
12827b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
12837b58daeaSdrh   ** the last SELECT in the series may have an ORDER BY or LIMIT.
128482c3d636Sdrh   */
1285daffd0e5Sdrh   if( p==0 || p->pPrior==0 ) return 1;
1286d8bc7086Sdrh   pPrior = p->pPrior;
1287d8bc7086Sdrh   if( pPrior->pOrderBy ){
12884adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1289da93d238Sdrh       selectOpName(p->op));
129082c3d636Sdrh     return 1;
129182c3d636Sdrh   }
12927b58daeaSdrh   if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
12934adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
12947b58daeaSdrh       selectOpName(p->op));
12957b58daeaSdrh     return 1;
12967b58daeaSdrh   }
129782c3d636Sdrh 
1298d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
1299d8bc7086Sdrh   */
13004adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
1301d8bc7086Sdrh   if( v==0 ) return 1;
1302d8bc7086Sdrh 
13031cc3d75fSdrh   /* Create the destination temporary table if necessary
13041cc3d75fSdrh   */
13051cc3d75fSdrh   if( eDest==SRT_TempTable ){
13064adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
13071cc3d75fSdrh     eDest = SRT_Table;
13081cc3d75fSdrh   }
13091cc3d75fSdrh 
1310f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1311d8bc7086Sdrh   */
131282c3d636Sdrh   switch( p->op ){
1313f46f905aSdrh     case TK_ALL: {
1314f46f905aSdrh       if( p->pOrderBy==0 ){
13157b58daeaSdrh         pPrior->nLimit = p->nLimit;
13167b58daeaSdrh         pPrior->nOffset = p->nOffset;
13174adee20fSdanielk1977         rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0);
1318f46f905aSdrh         if( rc ) return rc;
1319f46f905aSdrh         p->pPrior = 0;
13207b58daeaSdrh         p->iLimit = pPrior->iLimit;
13217b58daeaSdrh         p->iOffset = pPrior->iOffset;
13227b58daeaSdrh         p->nLimit = -1;
13237b58daeaSdrh         p->nOffset = 0;
13244adee20fSdanielk1977         rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0);
1325f46f905aSdrh         p->pPrior = pPrior;
1326f46f905aSdrh         if( rc ) return rc;
1327f46f905aSdrh         break;
1328f46f905aSdrh       }
1329f46f905aSdrh       /* For UNION ALL ... ORDER BY fall through to the next case */
1330f46f905aSdrh     }
133182c3d636Sdrh     case TK_EXCEPT:
133282c3d636Sdrh     case TK_UNION: {
1333d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1334d8bc7086Sdrh       int op;          /* One of the SRT_ operations to apply to self */
1335d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
13367b58daeaSdrh       int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
1337c926afbcSdrh       ExprList *pOrderBy;  /* The ORDER BY clause for the right SELECT */
133882c3d636Sdrh 
1339d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
13407b58daeaSdrh       if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
1341d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1342c926afbcSdrh         ** right.
1343d8bc7086Sdrh         */
134482c3d636Sdrh         unionTab = iParm;
134582c3d636Sdrh       }else{
1346d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1347d8bc7086Sdrh         ** intermediate results.
1348d8bc7086Sdrh         */
134982c3d636Sdrh         unionTab = pParse->nTab++;
1350d8bc7086Sdrh         if( p->pOrderBy
1351d8bc7086Sdrh         && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
1352d8bc7086Sdrh           return 1;
1353d8bc7086Sdrh         }
1354d8bc7086Sdrh         if( p->op!=TK_ALL ){
13554adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 1);
13564adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_KeyAsData, unionTab, 1);
1357345fda3eSdrh         }else{
13584adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
135982c3d636Sdrh         }
1360d8bc7086Sdrh       }
1361d8bc7086Sdrh 
1362d8bc7086Sdrh       /* Code the SELECT statements to our left
1363d8bc7086Sdrh       */
13644adee20fSdanielk1977       rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
136582c3d636Sdrh       if( rc ) return rc;
1366d8bc7086Sdrh 
1367d8bc7086Sdrh       /* Code the current SELECT statement
1368d8bc7086Sdrh       */
1369d8bc7086Sdrh       switch( p->op ){
1370d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
1371d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
1372d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
1373d8bc7086Sdrh       }
137482c3d636Sdrh       p->pPrior = 0;
1375c926afbcSdrh       pOrderBy = p->pOrderBy;
1376c926afbcSdrh       p->pOrderBy = 0;
13777b58daeaSdrh       nLimit = p->nLimit;
13787b58daeaSdrh       p->nLimit = -1;
13797b58daeaSdrh       nOffset = p->nOffset;
13807b58daeaSdrh       p->nOffset = 0;
13814adee20fSdanielk1977       rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0);
138282c3d636Sdrh       p->pPrior = pPrior;
1383c926afbcSdrh       p->pOrderBy = pOrderBy;
13847b58daeaSdrh       p->nLimit = nLimit;
13857b58daeaSdrh       p->nOffset = nOffset;
138682c3d636Sdrh       if( rc ) return rc;
1387d8bc7086Sdrh 
1388d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1389d8bc7086Sdrh       ** it is that we currently need.
1390d8bc7086Sdrh       */
1391c926afbcSdrh       if( eDest!=priorOp || unionTab!=iParm ){
13926b56344dSdrh         int iCont, iBreak, iStart;
139382c3d636Sdrh         assert( p->pEList );
139441202ccaSdrh         if( eDest==SRT_Callback ){
13956a3ea0e6Sdrh           generateColumnNames(pParse, 0, p->pEList);
13966a3ea0e6Sdrh           generateColumnTypes(pParse, p->pSrc, p->pEList);
139741202ccaSdrh         }
13984adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
13994adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
14004adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
14017b58daeaSdrh         computeLimitRegisters(pParse, p);
14024adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
1403fcb78a49Sdrh         multiSelectSortOrder(p, p->pOrderBy);
140438640e15Sdrh         rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
1405d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
140682c3d636Sdrh                              iCont, iBreak);
140782c3d636Sdrh         if( rc ) return 1;
14084adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
14094adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
14104adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
14114adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
1412d8bc7086Sdrh         if( p->pOrderBy ){
1413c926afbcSdrh           generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
1414d8bc7086Sdrh         }
141582c3d636Sdrh       }
141682c3d636Sdrh       break;
141782c3d636Sdrh     }
141882c3d636Sdrh     case TK_INTERSECT: {
141982c3d636Sdrh       int tab1, tab2;
14206b56344dSdrh       int iCont, iBreak, iStart;
14217b58daeaSdrh       int nLimit, nOffset;
142282c3d636Sdrh 
1423d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
14246206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
1425d8bc7086Sdrh       ** by allocating the tables we will need.
1426d8bc7086Sdrh       */
142782c3d636Sdrh       tab1 = pParse->nTab++;
142882c3d636Sdrh       tab2 = pParse->nTab++;
1429d8bc7086Sdrh       if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
1430d8bc7086Sdrh         return 1;
1431d8bc7086Sdrh       }
14324adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_OpenTemp, tab1, 1);
14334adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_KeyAsData, tab1, 1);
1434d8bc7086Sdrh 
1435d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1436d8bc7086Sdrh       */
14374adee20fSdanielk1977       rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
143882c3d636Sdrh       if( rc ) return rc;
1439d8bc7086Sdrh 
1440d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1441d8bc7086Sdrh       */
14424adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 1);
14434adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_KeyAsData, tab2, 1);
144482c3d636Sdrh       p->pPrior = 0;
14457b58daeaSdrh       nLimit = p->nLimit;
14467b58daeaSdrh       p->nLimit = -1;
14477b58daeaSdrh       nOffset = p->nOffset;
14487b58daeaSdrh       p->nOffset = 0;
14494adee20fSdanielk1977       rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0);
145082c3d636Sdrh       p->pPrior = pPrior;
14517b58daeaSdrh       p->nLimit = nLimit;
14527b58daeaSdrh       p->nOffset = nOffset;
145382c3d636Sdrh       if( rc ) return rc;
1454d8bc7086Sdrh 
1455d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1456d8bc7086Sdrh       ** tables.
1457d8bc7086Sdrh       */
145882c3d636Sdrh       assert( p->pEList );
145941202ccaSdrh       if( eDest==SRT_Callback ){
14606a3ea0e6Sdrh         generateColumnNames(pParse, 0, p->pEList);
14616a3ea0e6Sdrh         generateColumnTypes(pParse, p->pSrc, p->pEList);
146241202ccaSdrh       }
14634adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
14644adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
14654adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
14667b58daeaSdrh       computeLimitRegisters(pParse, p);
14674adee20fSdanielk1977       iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
14684adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
1469fcb78a49Sdrh       multiSelectSortOrder(p, p->pOrderBy);
147038640e15Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
1471d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
147282c3d636Sdrh                              iCont, iBreak);
147382c3d636Sdrh       if( rc ) return 1;
14744adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
14754adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
14764adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
14774adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
14784adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
1479d8bc7086Sdrh       if( p->pOrderBy ){
1480c926afbcSdrh         generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
1481d8bc7086Sdrh       }
148282c3d636Sdrh       break;
148382c3d636Sdrh     }
148482c3d636Sdrh   }
148582c3d636Sdrh   assert( p->pEList && pPrior->pEList );
148682c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
14874adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
1488da93d238Sdrh       " do not have the same number of result columns", selectOpName(p->op));
148982c3d636Sdrh     return 1;
14902282792aSdrh   }
14912282792aSdrh   return 0;
14922282792aSdrh }
14932282792aSdrh 
14942282792aSdrh /*
1495832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
14966a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
149784e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
14986a3ea0e6Sdrh ** unchanged.)
1499832508b7Sdrh **
1500832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
1501832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
1502832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
1503832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
1504832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
1505832508b7Sdrh ** of the subquery rather the result set of the subquery.
1506832508b7Sdrh */
15076a3ea0e6Sdrh static void substExprList(ExprList*,int,ExprList*);  /* Forward Decl */
15086a3ea0e6Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
1509832508b7Sdrh   if( pExpr==0 ) return;
151050350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
151150350a15Sdrh     if( pExpr->iColumn<0 ){
151250350a15Sdrh       pExpr->op = TK_NULL;
151350350a15Sdrh     }else{
1514832508b7Sdrh       Expr *pNew;
151584e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1516832508b7Sdrh       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1517832508b7Sdrh       pNew = pEList->a[pExpr->iColumn].pExpr;
1518832508b7Sdrh       assert( pNew!=0 );
1519832508b7Sdrh       pExpr->op = pNew->op;
1520fcb78a49Sdrh       pExpr->dataType = pNew->dataType;
1521d94a6698Sdrh       assert( pExpr->pLeft==0 );
15224adee20fSdanielk1977       pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
1523d94a6698Sdrh       assert( pExpr->pRight==0 );
15244adee20fSdanielk1977       pExpr->pRight = sqlite3ExprDup(pNew->pRight);
1525d94a6698Sdrh       assert( pExpr->pList==0 );
15264adee20fSdanielk1977       pExpr->pList = sqlite3ExprListDup(pNew->pList);
1527832508b7Sdrh       pExpr->iTable = pNew->iTable;
1528832508b7Sdrh       pExpr->iColumn = pNew->iColumn;
1529832508b7Sdrh       pExpr->iAgg = pNew->iAgg;
15304adee20fSdanielk1977       sqlite3TokenCopy(&pExpr->token, &pNew->token);
15314adee20fSdanielk1977       sqlite3TokenCopy(&pExpr->span, &pNew->span);
153250350a15Sdrh     }
1533832508b7Sdrh   }else{
15346a3ea0e6Sdrh     substExpr(pExpr->pLeft, iTable, pEList);
15356a3ea0e6Sdrh     substExpr(pExpr->pRight, iTable, pEList);
15366a3ea0e6Sdrh     substExprList(pExpr->pList, iTable, pEList);
1537832508b7Sdrh   }
1538832508b7Sdrh }
1539832508b7Sdrh static void
15406a3ea0e6Sdrh substExprList(ExprList *pList, int iTable, ExprList *pEList){
1541832508b7Sdrh   int i;
1542832508b7Sdrh   if( pList==0 ) return;
1543832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
15446a3ea0e6Sdrh     substExpr(pList->a[i].pExpr, iTable, pEList);
1545832508b7Sdrh   }
1546832508b7Sdrh }
1547832508b7Sdrh 
1548832508b7Sdrh /*
15491350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
15501350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
15511350b030Sdrh ** occurs.
15521350b030Sdrh **
15531350b030Sdrh ** To understand the concept of flattening, consider the following
15541350b030Sdrh ** query:
15551350b030Sdrh **
15561350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
15571350b030Sdrh **
15581350b030Sdrh ** The default way of implementing this query is to execute the
15591350b030Sdrh ** subquery first and store the results in a temporary table, then
15601350b030Sdrh ** run the outer query on that temporary table.  This requires two
15611350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
15621350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
1563832508b7Sdrh ** optimized.
15641350b030Sdrh **
1565832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
15661350b030Sdrh ** a single flat select, like this:
15671350b030Sdrh **
15681350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
15691350b030Sdrh **
15701350b030Sdrh ** The code generated for this simpification gives the same result
1571832508b7Sdrh ** but only has to scan the data once.  And because indices might
1572832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
1573832508b7Sdrh ** avoided.
15741350b030Sdrh **
1575832508b7Sdrh ** Flattening is only attempted if all of the following are true:
15761350b030Sdrh **
1577832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
15781350b030Sdrh **
1579832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
1580832508b7Sdrh **
15818af4d3acSdrh **   (3)  The subquery is not the right operand of a left outer join, or
15828af4d3acSdrh **        the subquery is not itself a join.  (Ticket #306)
1583832508b7Sdrh **
1584832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
1585832508b7Sdrh **
1586832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
1587832508b7Sdrh **        aggregates.
1588832508b7Sdrh **
1589832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
1590832508b7Sdrh **        DISTINCT.
1591832508b7Sdrh **
159208192d5fSdrh **   (7)  The subquery has a FROM clause.
159308192d5fSdrh **
1594df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
1595df199a25Sdrh **
1596df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
1597df199a25Sdrh **        aggregates.
1598df199a25Sdrh **
1599df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
1600df199a25Sdrh **        use LIMIT.
1601df199a25Sdrh **
1602174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
1603174b6195Sdrh **
16043fc673e6Sdrh **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
16053fc673e6Sdrh **        subquery has no WHERE clause.  (added by ticket #350)
16063fc673e6Sdrh **
1607832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
1608832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
1609832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1610832508b7Sdrh **
1611665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
1612832508b7Sdrh ** If flattening is attempted this routine returns 1.
1613832508b7Sdrh **
1614832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
1615832508b7Sdrh ** the subquery before this routine runs.
16161350b030Sdrh */
16178c74a8caSdrh static int flattenSubquery(
16188c74a8caSdrh   Parse *pParse,       /* The parsing context */
16198c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
16208c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
16218c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
16228c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
16238c74a8caSdrh ){
16240bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
1625ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
1626ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
16270bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
16286a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
1629832508b7Sdrh   int i;
1630832508b7Sdrh   Expr *pWhere;
16311350b030Sdrh 
1632832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
1633832508b7Sdrh   */
1634832508b7Sdrh   if( p==0 ) return 0;
1635832508b7Sdrh   pSrc = p->pSrc;
1636ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
1637832508b7Sdrh   pSub = pSrc->a[iFrom].pSelect;
1638832508b7Sdrh   assert( pSub!=0 );
1639832508b7Sdrh   if( isAgg && subqueryIsAgg ) return 0;
1640ad3cab52Sdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
1641832508b7Sdrh   pSubSrc = pSub->pSrc;
1642832508b7Sdrh   assert( pSubSrc );
1643c31c2eb8Sdrh   if( pSubSrc->nSrc==0 ) return 0;
1644df199a25Sdrh   if( (pSub->isDistinct || pSub->nLimit>=0) &&  (pSrc->nSrc>1 || isAgg) ){
1645df199a25Sdrh      return 0;
1646df199a25Sdrh   }
1647d11d382cSdrh   if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
1648174b6195Sdrh   if( p->pOrderBy && pSub->pOrderBy ) return 0;
1649832508b7Sdrh 
16508af4d3acSdrh   /* Restriction 3:  If the subquery is a join, make sure the subquery is
16518af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
16528af4d3acSdrh   ** is not allowed:
16538af4d3acSdrh   **
16548af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
16558af4d3acSdrh   **
16568af4d3acSdrh   ** If we flatten the above, we would get
16578af4d3acSdrh   **
16588af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
16598af4d3acSdrh   **
16608af4d3acSdrh   ** which is not at all the same thing.
16618af4d3acSdrh   */
16628af4d3acSdrh   if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
16638af4d3acSdrh     return 0;
16648af4d3acSdrh   }
16658af4d3acSdrh 
16663fc673e6Sdrh   /* Restriction 12:  If the subquery is the right operand of a left outer
16673fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
16683fc673e6Sdrh   ** An examples of why this is not allowed:
16693fc673e6Sdrh   **
16703fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
16713fc673e6Sdrh   **
16723fc673e6Sdrh   ** If we flatten the above, we would get
16733fc673e6Sdrh   **
16743fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
16753fc673e6Sdrh   **
16763fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
16773fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
16783fc673e6Sdrh   */
16793fc673e6Sdrh   if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
16803fc673e6Sdrh       && pSub->pWhere!=0 ){
16813fc673e6Sdrh     return 0;
16823fc673e6Sdrh   }
16833fc673e6Sdrh 
16840bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
168563eb5f29Sdrh   ** iFrom-th entry of the FROM clause in the outer query.
1686832508b7Sdrh   */
1687c31c2eb8Sdrh 
1688c31c2eb8Sdrh   /* Move all of the FROM elements of the subquery into the
1689c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
1690c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
1691c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
1692c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
1693c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
1694c31c2eb8Sdrh   ** elements we are now copying in.
1695c31c2eb8Sdrh   */
16966a3ea0e6Sdrh   iParent = pSrc->a[iFrom].iCursor;
1697c31c2eb8Sdrh   {
1698c31c2eb8Sdrh     int nSubSrc = pSubSrc->nSrc;
16998af4d3acSdrh     int jointype = pSrc->a[iFrom].jointype;
1700c31c2eb8Sdrh 
1701c31c2eb8Sdrh     if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
17024adee20fSdanielk1977       sqlite3DeleteTable(0, pSrc->a[iFrom].pTab);
1703c31c2eb8Sdrh     }
1704f26e09c8Sdrh     sqliteFree(pSrc->a[iFrom].zDatabase);
1705c31c2eb8Sdrh     sqliteFree(pSrc->a[iFrom].zName);
1706c31c2eb8Sdrh     sqliteFree(pSrc->a[iFrom].zAlias);
1707c31c2eb8Sdrh     if( nSubSrc>1 ){
1708c31c2eb8Sdrh       int extra = nSubSrc - 1;
1709c31c2eb8Sdrh       for(i=1; i<nSubSrc; i++){
17104adee20fSdanielk1977         pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
1711c31c2eb8Sdrh       }
1712c31c2eb8Sdrh       p->pSrc = pSrc;
1713c31c2eb8Sdrh       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1714c31c2eb8Sdrh         pSrc->a[i] = pSrc->a[i-extra];
1715c31c2eb8Sdrh       }
1716c31c2eb8Sdrh     }
1717c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
1718c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
1719c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1720c31c2eb8Sdrh     }
17218af4d3acSdrh     pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
1722c31c2eb8Sdrh   }
1723c31c2eb8Sdrh 
1724c31c2eb8Sdrh   /* Now begin substituting subquery result set expressions for
1725c31c2eb8Sdrh   ** references to the iParent in the outer query.
1726c31c2eb8Sdrh   **
1727c31c2eb8Sdrh   ** Example:
1728c31c2eb8Sdrh   **
1729c31c2eb8Sdrh   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1730c31c2eb8Sdrh   **   \                     \_____________ subquery __________/          /
1731c31c2eb8Sdrh   **    \_____________________ outer query ______________________________/
1732c31c2eb8Sdrh   **
1733c31c2eb8Sdrh   ** We look at every expression in the outer query and every place we see
1734c31c2eb8Sdrh   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1735c31c2eb8Sdrh   */
17366a3ea0e6Sdrh   substExprList(p->pEList, iParent, pSub->pEList);
1737832508b7Sdrh   pList = p->pEList;
1738832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
17396977fea8Sdrh     Expr *pExpr;
17406977fea8Sdrh     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
17416977fea8Sdrh       pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
1742832508b7Sdrh     }
1743832508b7Sdrh   }
17441b2e0329Sdrh   if( isAgg ){
17456a3ea0e6Sdrh     substExprList(p->pGroupBy, iParent, pSub->pEList);
17466a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
17471b2e0329Sdrh   }
1748174b6195Sdrh   if( pSub->pOrderBy ){
1749174b6195Sdrh     assert( p->pOrderBy==0 );
1750174b6195Sdrh     p->pOrderBy = pSub->pOrderBy;
1751174b6195Sdrh     pSub->pOrderBy = 0;
1752174b6195Sdrh   }else if( p->pOrderBy ){
17536a3ea0e6Sdrh     substExprList(p->pOrderBy, iParent, pSub->pEList);
1754174b6195Sdrh   }
1755832508b7Sdrh   if( pSub->pWhere ){
17564adee20fSdanielk1977     pWhere = sqlite3ExprDup(pSub->pWhere);
1757832508b7Sdrh   }else{
1758832508b7Sdrh     pWhere = 0;
1759832508b7Sdrh   }
1760832508b7Sdrh   if( subqueryIsAgg ){
1761832508b7Sdrh     assert( p->pHaving==0 );
17621b2e0329Sdrh     p->pHaving = p->pWhere;
17631b2e0329Sdrh     p->pWhere = pWhere;
17646a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
17651b2e0329Sdrh     if( pSub->pHaving ){
17664adee20fSdanielk1977       Expr *pHaving = sqlite3ExprDup(pSub->pHaving);
17671b2e0329Sdrh       if( p->pHaving ){
17684adee20fSdanielk1977         p->pHaving = sqlite3Expr(TK_AND, p->pHaving, pHaving, 0);
17691b2e0329Sdrh       }else{
17701b2e0329Sdrh         p->pHaving = pHaving;
17711b2e0329Sdrh       }
17721b2e0329Sdrh     }
17731b2e0329Sdrh     assert( p->pGroupBy==0 );
17744adee20fSdanielk1977     p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
1775832508b7Sdrh   }else if( p->pWhere==0 ){
1776832508b7Sdrh     p->pWhere = pWhere;
1777832508b7Sdrh   }else{
17786a3ea0e6Sdrh     substExpr(p->pWhere, iParent, pSub->pEList);
1779832508b7Sdrh     if( pWhere ){
17804adee20fSdanielk1977       p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pWhere, 0);
1781832508b7Sdrh     }
1782832508b7Sdrh   }
1783c31c2eb8Sdrh 
1784c31c2eb8Sdrh   /* The flattened query is distinct if either the inner or the
1785c31c2eb8Sdrh   ** outer query is distinct.
1786c31c2eb8Sdrh   */
1787832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
17888c74a8caSdrh 
1789c31c2eb8Sdrh   /* Transfer the limit expression from the subquery to the outer
1790c31c2eb8Sdrh   ** query.
1791c31c2eb8Sdrh   */
1792df199a25Sdrh   if( pSub->nLimit>=0 ){
1793df199a25Sdrh     if( p->nLimit<0 ){
1794df199a25Sdrh       p->nLimit = pSub->nLimit;
1795df199a25Sdrh     }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1796df199a25Sdrh       p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1797df199a25Sdrh     }
1798df199a25Sdrh   }
1799df199a25Sdrh   p->nOffset += pSub->nOffset;
18008c74a8caSdrh 
1801c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
1802c31c2eb8Sdrh   ** success.
1803c31c2eb8Sdrh   */
18044adee20fSdanielk1977   sqlite3SelectDelete(pSub);
1805832508b7Sdrh   return 1;
18061350b030Sdrh }
18071350b030Sdrh 
18081350b030Sdrh /*
18099562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it
18109562b551Sdrh ** is a simple min() or max() query.  If it is and this query can be
18119562b551Sdrh ** satisfied using a single seek to the beginning or end of an index,
1812e78e8284Sdrh ** then generate the code for this SELECT and return 1.  If this is not a
18139562b551Sdrh ** simple min() or max() query, then return 0;
18149562b551Sdrh **
18159562b551Sdrh ** A simply min() or max() query looks like this:
18169562b551Sdrh **
18179562b551Sdrh **    SELECT min(a) FROM table;
18189562b551Sdrh **    SELECT max(a) FROM table;
18199562b551Sdrh **
18209562b551Sdrh ** The query may have only a single table in its FROM argument.  There
18219562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
18229562b551Sdrh ** be the min() or max() of a single column of the table.  The column
18239562b551Sdrh ** in the min() or max() function must be indexed.
18249562b551Sdrh **
18254adee20fSdanielk1977 ** The parameters to this routine are the same as for sqlite3Select().
18269562b551Sdrh ** See the header comment on that routine for additional information.
18279562b551Sdrh */
18289562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
18299562b551Sdrh   Expr *pExpr;
18309562b551Sdrh   int iCol;
18319562b551Sdrh   Table *pTab;
18329562b551Sdrh   Index *pIdx;
18339562b551Sdrh   int base;
18349562b551Sdrh   Vdbe *v;
18359562b551Sdrh   int seekOp;
18369562b551Sdrh   int cont;
18376e17529eSdrh   ExprList *pEList, *pList, eList;
18389562b551Sdrh   struct ExprList_item eListItem;
18396e17529eSdrh   SrcList *pSrc;
18406e17529eSdrh 
18419562b551Sdrh 
18429562b551Sdrh   /* Check to see if this query is a simple min() or max() query.  Return
18439562b551Sdrh   ** zero if it is  not.
18449562b551Sdrh   */
18459562b551Sdrh   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
18466e17529eSdrh   pSrc = p->pSrc;
18476e17529eSdrh   if( pSrc->nSrc!=1 ) return 0;
18486e17529eSdrh   pEList = p->pEList;
18496e17529eSdrh   if( pEList->nExpr!=1 ) return 0;
18506e17529eSdrh   pExpr = pEList->a[0].pExpr;
18519562b551Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
18526e17529eSdrh   pList = pExpr->pList;
18536e17529eSdrh   if( pList==0 || pList->nExpr!=1 ) return 0;
18546977fea8Sdrh   if( pExpr->token.n!=3 ) return 0;
18554adee20fSdanielk1977   if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
18560bce8354Sdrh     seekOp = OP_Rewind;
18574adee20fSdanielk1977   }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
18580bce8354Sdrh     seekOp = OP_Last;
18590bce8354Sdrh   }else{
18600bce8354Sdrh     return 0;
18610bce8354Sdrh   }
18626e17529eSdrh   pExpr = pList->a[0].pExpr;
18639562b551Sdrh   if( pExpr->op!=TK_COLUMN ) return 0;
18649562b551Sdrh   iCol = pExpr->iColumn;
18656e17529eSdrh   pTab = pSrc->a[0].pTab;
18669562b551Sdrh 
18679562b551Sdrh   /* If we get to here, it means the query is of the correct form.
186817f71934Sdrh   ** Check to make sure we have an index and make pIdx point to the
186917f71934Sdrh   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
187017f71934Sdrh   ** key column, no index is necessary so set pIdx to NULL.  If no
187117f71934Sdrh   ** usable index is found, return 0.
18729562b551Sdrh   */
18739562b551Sdrh   if( iCol<0 ){
18749562b551Sdrh     pIdx = 0;
18759562b551Sdrh   }else{
18769562b551Sdrh     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
18779562b551Sdrh       assert( pIdx->nColumn>=1 );
18789562b551Sdrh       if( pIdx->aiColumn[0]==iCol ) break;
18799562b551Sdrh     }
18809562b551Sdrh     if( pIdx==0 ) return 0;
18819562b551Sdrh   }
18829562b551Sdrh 
1883e5f50722Sdrh   /* Identify column types if we will be using the callback.  This
18849562b551Sdrh   ** step is skipped if the output is going to a table or a memory cell.
1885e5f50722Sdrh   ** The column names have already been generated in the calling function.
18869562b551Sdrh   */
18874adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
18889562b551Sdrh   if( v==0 ) return 0;
18899562b551Sdrh   if( eDest==SRT_Callback ){
18906a3ea0e6Sdrh     generateColumnTypes(pParse, p->pSrc, p->pEList);
18919562b551Sdrh   }
18929562b551Sdrh 
18930c37e630Sdrh   /* If the output is destined for a temporary table, open that table.
18940c37e630Sdrh   */
18950c37e630Sdrh   if( eDest==SRT_TempTable ){
18964adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
18970c37e630Sdrh   }
18980c37e630Sdrh 
189917f71934Sdrh   /* Generating code to find the min or the max.  Basically all we have
190017f71934Sdrh   ** to do is find the first or the last entry in the chosen index.  If
190117f71934Sdrh   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
190217f71934Sdrh   ** or last entry in the main table.
19039562b551Sdrh   */
19044adee20fSdanielk1977   sqlite3CodeVerifySchema(pParse, pTab->iDb);
19056e17529eSdrh   base = pSrc->a[0].iCursor;
19067b58daeaSdrh   computeLimitRegisters(pParse, p);
19076e17529eSdrh   if( pSrc->a[0].pSelect==0 ){
19084adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
19094adee20fSdanielk1977     sqlite3VdbeOp3(v, OP_OpenRead, base, pTab->tnum, pTab->zName, 0);
19106e17529eSdrh   }
19114adee20fSdanielk1977   cont = sqlite3VdbeMakeLabel(v);
19129562b551Sdrh   if( pIdx==0 ){
19134adee20fSdanielk1977     sqlite3VdbeAddOp(v, seekOp, base, 0);
19149562b551Sdrh   }else{
19154adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
19164adee20fSdanielk1977     sqlite3VdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum, pIdx->zName, P3_STATIC);
19174adee20fSdanielk1977     sqlite3VdbeAddOp(v, seekOp, base+1, 0);
19184adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_IdxRecno, base+1, 0);
19194adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Close, base+1, 0);
19204adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MoveTo, base, 0);
19219562b551Sdrh   }
19225cf8e8c7Sdrh   eList.nExpr = 1;
19235cf8e8c7Sdrh   memset(&eListItem, 0, sizeof(eListItem));
19245cf8e8c7Sdrh   eList.a = &eListItem;
19255cf8e8c7Sdrh   eList.a[0].pExpr = pExpr;
192638640e15Sdrh   selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont);
19274adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, cont);
19284adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Close, base, 0);
19296e17529eSdrh 
19309562b551Sdrh   return 1;
19319562b551Sdrh }
19329562b551Sdrh 
19339562b551Sdrh /*
19349bb61fe7Sdrh ** Generate code for the given SELECT statement.
19359bb61fe7Sdrh **
1936fef5208cSdrh ** The results are distributed in various ways depending on the
1937fef5208cSdrh ** value of eDest and iParm.
1938fef5208cSdrh **
1939fef5208cSdrh **     eDest Value       Result
1940fef5208cSdrh **     ------------    -------------------------------------------
1941fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
1942fef5208cSdrh **
1943fef5208cSdrh **     SRT_Mem         Store first result in memory cell iParm
1944fef5208cSdrh **
1945fef5208cSdrh **     SRT_Set         Store results as keys of a table with cursor iParm
1946fef5208cSdrh **
194782c3d636Sdrh **     SRT_Union       Store results as a key in a temporary table iParm
194882c3d636Sdrh **
19494b11c6d3Sjplyon **     SRT_Except      Remove results from the temporary table iParm.
1950c4a3c779Sdrh **
1951c4a3c779Sdrh **     SRT_Table       Store results in temporary table iParm
19529bb61fe7Sdrh **
1953e78e8284Sdrh ** The table above is incomplete.  Additional eDist value have be added
1954e78e8284Sdrh ** since this comment was written.  See the selectInnerLoop() function for
1955e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings.
1956e78e8284Sdrh **
19579bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
19589bb61fe7Sdrh ** encountered, then an appropriate error message is left in
19599bb61fe7Sdrh ** pParse->zErrMsg.
19609bb61fe7Sdrh **
19619bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
19629bb61fe7Sdrh ** calling function needs to do that.
19631b2e0329Sdrh **
19641b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
19651b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
19661b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
19671b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
19681b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
19691b2e0329Sdrh ** can be changed.
1970e78e8284Sdrh **
1971e78e8284Sdrh ** Example 1:   The meaning of the pParent parameter.
1972e78e8284Sdrh **
1973e78e8284Sdrh **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
1974e78e8284Sdrh **    \                      \_______ subquery _______/        /
1975e78e8284Sdrh **     \                                                      /
1976e78e8284Sdrh **      \____________________ outer query ___________________/
1977e78e8284Sdrh **
1978e78e8284Sdrh ** This routine is called for the outer query first.   For that call,
1979e78e8284Sdrh ** pParent will be NULL.  During the processing of the outer query, this
1980e78e8284Sdrh ** routine is called recursively to handle the subquery.  For the recursive
1981e78e8284Sdrh ** call, pParent will point to the outer query.  Because the subquery is
1982e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will
1983e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.)
19849bb61fe7Sdrh */
19854adee20fSdanielk1977 int sqlite3Select(
1986cce7d176Sdrh   Parse *pParse,         /* The parser context */
19879bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
1988e78e8284Sdrh   int eDest,             /* How to dispose of the results */
1989e78e8284Sdrh   int iParm,             /* A parameter used by the eDest disposal method */
1990832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
1991832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
19921b2e0329Sdrh   int *pParentAgg        /* True if pParent uses aggregate functions */
1993cce7d176Sdrh ){
1994d8bc7086Sdrh   int i;
1995cce7d176Sdrh   WhereInfo *pWInfo;
1996cce7d176Sdrh   Vdbe *v;
1997cce7d176Sdrh   int isAgg = 0;         /* True for select lists like "count(*)" */
1998a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
1999ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
20009bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
20019bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
20022282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
20032282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
200419a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
200519a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
20061d83f052Sdrh   int rc = 1;            /* Value to return from this function */
20079bb61fe7Sdrh 
20086f8a503dSdanielk1977   if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
20094adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
2010daffd0e5Sdrh 
201182c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
201282c3d636Sdrh   */
201382c3d636Sdrh   if( p->pPrior ){
201482c3d636Sdrh     return multiSelect(pParse, p, eDest, iParm);
201582c3d636Sdrh   }
201682c3d636Sdrh 
201782c3d636Sdrh   /* Make local copies of the parameters for this query.
201882c3d636Sdrh   */
20199bb61fe7Sdrh   pTabList = p->pSrc;
20209bb61fe7Sdrh   pWhere = p->pWhere;
20219bb61fe7Sdrh   pOrderBy = p->pOrderBy;
20222282792aSdrh   pGroupBy = p->pGroupBy;
20232282792aSdrh   pHaving = p->pHaving;
202419a775c2Sdrh   isDistinct = p->isDistinct;
20259bb61fe7Sdrh 
20266a3ea0e6Sdrh   /* Allocate VDBE cursors for each table in the FROM clause
202710e5e3cfSdrh   */
20284adee20fSdanielk1977   sqlite3SrcListAssignCursors(pParse, pTabList);
202910e5e3cfSdrh 
20309bb61fe7Sdrh   /*
20319bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
20329bb61fe7Sdrh   ** errors before this routine starts.
20339bb61fe7Sdrh   */
20341d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
2035cce7d176Sdrh 
2036e78e8284Sdrh   /* Expand any "*" terms in the result set.  (For example the "*" in
2037e78e8284Sdrh   ** "SELECT * FROM t1")  The fillInColumnlist() routine also does some
2038e78e8284Sdrh   ** other housekeeping - see the header comment for details.
2039cce7d176Sdrh   */
2040d8bc7086Sdrh   if( fillInColumnList(pParse, p) ){
20411d83f052Sdrh     goto select_end;
2042cce7d176Sdrh   }
2043ad2d8307Sdrh   pWhere = p->pWhere;
2044d8bc7086Sdrh   pEList = p->pEList;
20451d83f052Sdrh   if( pEList==0 ) goto select_end;
2046cce7d176Sdrh 
20472282792aSdrh   /* If writing to memory or generating a set
20482282792aSdrh   ** only a single column may be output.
204919a775c2Sdrh   */
2050fef5208cSdrh   if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
20514adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "only a single result allowed for "
2052da93d238Sdrh        "a SELECT that is part of an expression");
20531d83f052Sdrh     goto select_end;
205419a775c2Sdrh   }
205519a775c2Sdrh 
2056c926afbcSdrh   /* ORDER BY is ignored for some destinations.
20572282792aSdrh   */
2058c926afbcSdrh   switch( eDest ){
2059c926afbcSdrh     case SRT_Union:
2060c926afbcSdrh     case SRT_Except:
2061c926afbcSdrh     case SRT_Discard:
2062acd4c695Sdrh       pOrderBy = 0;
2063c926afbcSdrh       break;
2064c926afbcSdrh     default:
2065c926afbcSdrh       break;
20662282792aSdrh   }
20672282792aSdrh 
206810e5e3cfSdrh   /* At this point, we should have allocated all the cursors that we
2069832508b7Sdrh   ** need to handle subquerys and temporary tables.
207010e5e3cfSdrh   **
2071967e8b73Sdrh   ** Resolve the column names and do a semantics check on all the expressions.
20722282792aSdrh   */
20734794b980Sdrh   for(i=0; i<pEList->nExpr; i++){
20744adee20fSdanielk1977     if( sqlite3ExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
20751d83f052Sdrh       goto select_end;
2076cce7d176Sdrh     }
20774adee20fSdanielk1977     if( sqlite3ExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
20781d83f052Sdrh       goto select_end;
2079cce7d176Sdrh     }
2080cce7d176Sdrh   }
2081cce7d176Sdrh   if( pWhere ){
20824adee20fSdanielk1977     if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pWhere) ){
20831d83f052Sdrh       goto select_end;
2084cce7d176Sdrh     }
20854adee20fSdanielk1977     if( sqlite3ExprCheck(pParse, pWhere, 0, 0) ){
20861d83f052Sdrh       goto select_end;
2087cce7d176Sdrh     }
2088cce7d176Sdrh   }
2089c66c5a26Sdrh   if( pHaving ){
2090c66c5a26Sdrh     if( pGroupBy==0 ){
20914adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2092c66c5a26Sdrh       goto select_end;
2093c66c5a26Sdrh     }
20944adee20fSdanielk1977     if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pHaving) ){
2095c66c5a26Sdrh       goto select_end;
2096c66c5a26Sdrh     }
20974adee20fSdanielk1977     if( sqlite3ExprCheck(pParse, pHaving, 1, &isAgg) ){
2098c66c5a26Sdrh       goto select_end;
2099c66c5a26Sdrh     }
2100c66c5a26Sdrh   }
2101cce7d176Sdrh   if( pOrderBy ){
2102cce7d176Sdrh     for(i=0; i<pOrderBy->nExpr; i++){
2103e4de1febSdrh       int iCol;
210488eee38aSdrh       Expr *pE = pOrderBy->a[i].pExpr;
21054adee20fSdanielk1977       if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
21064adee20fSdanielk1977         sqlite3ExprDelete(pE);
21074adee20fSdanielk1977         pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
210888eee38aSdrh       }
21094adee20fSdanielk1977       if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
211088eee38aSdrh         goto select_end;
211188eee38aSdrh       }
21124adee20fSdanielk1977       if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
211388eee38aSdrh         goto select_end;
211488eee38aSdrh       }
21154adee20fSdanielk1977       if( sqlite3ExprIsConstant(pE) ){
21164adee20fSdanielk1977         if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
21174adee20fSdanielk1977           sqlite3ErrorMsg(pParse,
2118da93d238Sdrh              "ORDER BY terms must not be non-integer constants");
21191d83f052Sdrh           goto select_end;
2120e4de1febSdrh         }else if( iCol<=0 || iCol>pEList->nExpr ){
21214adee20fSdanielk1977           sqlite3ErrorMsg(pParse,
2122da93d238Sdrh              "ORDER BY column number %d out of range - should be "
2123e4de1febSdrh              "between 1 and %d", iCol, pEList->nExpr);
2124e4de1febSdrh           goto select_end;
2125e4de1febSdrh         }
2126cce7d176Sdrh       }
2127cce7d176Sdrh     }
2128cce7d176Sdrh   }
21292282792aSdrh   if( pGroupBy ){
21302282792aSdrh     for(i=0; i<pGroupBy->nExpr; i++){
213188eee38aSdrh       int iCol;
21322282792aSdrh       Expr *pE = pGroupBy->a[i].pExpr;
21334adee20fSdanielk1977       if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
21344adee20fSdanielk1977         sqlite3ExprDelete(pE);
21354adee20fSdanielk1977         pE = pGroupBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
21369208643dSdrh       }
21374adee20fSdanielk1977       if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
21381d83f052Sdrh         goto select_end;
21392282792aSdrh       }
21404adee20fSdanielk1977       if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
21411d83f052Sdrh         goto select_end;
21422282792aSdrh       }
21434adee20fSdanielk1977       if( sqlite3ExprIsConstant(pE) ){
21444adee20fSdanielk1977         if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
21454adee20fSdanielk1977           sqlite3ErrorMsg(pParse,
2146da93d238Sdrh             "GROUP BY terms must not be non-integer constants");
214788eee38aSdrh           goto select_end;
214888eee38aSdrh         }else if( iCol<=0 || iCol>pEList->nExpr ){
21494adee20fSdanielk1977           sqlite3ErrorMsg(pParse,
2150da93d238Sdrh              "GROUP BY column number %d out of range - should be "
215188eee38aSdrh              "between 1 and %d", iCol, pEList->nExpr);
215288eee38aSdrh           goto select_end;
215388eee38aSdrh         }
215488eee38aSdrh       }
21552282792aSdrh     }
21562282792aSdrh   }
2157cce7d176Sdrh 
2158d820cb1bSdrh   /* Begin generating code.
2159d820cb1bSdrh   */
21604adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
2161d820cb1bSdrh   if( v==0 ) goto select_end;
2162d820cb1bSdrh 
2163e78e8284Sdrh   /* Identify column names if we will be using them in a callback.  This
2164e78e8284Sdrh   ** step is skipped if the output is going to some other destination.
21650bb28106Sdrh   */
21660bb28106Sdrh   if( eDest==SRT_Callback ){
21676a3ea0e6Sdrh     generateColumnNames(pParse, pTabList, pEList);
21680bb28106Sdrh   }
21690bb28106Sdrh 
2170d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
2171d820cb1bSdrh   */
2172ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
21735cf590c1Sdrh     const char *zSavedAuthContext;
2174c31c2eb8Sdrh     int needRestoreContext;
2175c31c2eb8Sdrh 
2176a76b5dfcSdrh     if( pTabList->a[i].pSelect==0 ) continue;
21775cf590c1Sdrh     if( pTabList->a[i].zName!=0 ){
21785cf590c1Sdrh       zSavedAuthContext = pParse->zAuthContext;
21795cf590c1Sdrh       pParse->zAuthContext = pTabList->a[i].zName;
2180c31c2eb8Sdrh       needRestoreContext = 1;
2181c31c2eb8Sdrh     }else{
2182c31c2eb8Sdrh       needRestoreContext = 0;
21835cf590c1Sdrh     }
21844adee20fSdanielk1977     sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
21856a3ea0e6Sdrh                  pTabList->a[i].iCursor, p, i, &isAgg);
2186c31c2eb8Sdrh     if( needRestoreContext ){
21875cf590c1Sdrh       pParse->zAuthContext = zSavedAuthContext;
21885cf590c1Sdrh     }
2189832508b7Sdrh     pTabList = p->pSrc;
2190832508b7Sdrh     pWhere = p->pWhere;
2191c31c2eb8Sdrh     if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
2192832508b7Sdrh       pOrderBy = p->pOrderBy;
2193acd4c695Sdrh     }
2194832508b7Sdrh     pGroupBy = p->pGroupBy;
2195832508b7Sdrh     pHaving = p->pHaving;
2196832508b7Sdrh     isDistinct = p->isDistinct;
21971b2e0329Sdrh   }
21981b2e0329Sdrh 
21996e17529eSdrh   /* Check for the special case of a min() or max() function by itself
22006e17529eSdrh   ** in the result set.
22016e17529eSdrh   */
22026e17529eSdrh   if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
22036e17529eSdrh     rc = 0;
22046e17529eSdrh     goto select_end;
22056e17529eSdrh   }
22066e17529eSdrh 
22071b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
22081b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
22091b2e0329Sdrh   */
22101b2e0329Sdrh   if( pParent && pParentAgg &&
22118c74a8caSdrh       flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
22121b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
22131b2e0329Sdrh     return rc;
22141b2e0329Sdrh   }
2215832508b7Sdrh 
22167b58daeaSdrh   /* Set the limiter.
22177b58daeaSdrh   */
22187b58daeaSdrh   computeLimitRegisters(pParse, p);
22197b58daeaSdrh 
2220e78e8284Sdrh   /* Identify column types if we will be using a callback.  This
2221e78e8284Sdrh   ** step is skipped if the output is going to a destination other
2222e78e8284Sdrh   ** than a callback.
2223e5f50722Sdrh   **
2224e5f50722Sdrh   ** We have to do this separately from the creation of column names
2225e5f50722Sdrh   ** above because if the pTabList contains views then they will not
2226e5f50722Sdrh   ** have been resolved and we will not know the column types until
2227e5f50722Sdrh   ** now.
2228fcb78a49Sdrh   */
2229fcb78a49Sdrh   if( eDest==SRT_Callback ){
22306a3ea0e6Sdrh     generateColumnTypes(pParse, pTabList, pEList);
2231fcb78a49Sdrh   }
2232fcb78a49Sdrh 
22332d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
22342d0794e3Sdrh   */
22352d0794e3Sdrh   if( eDest==SRT_TempTable ){
22364adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
22372d0794e3Sdrh   }
22382d0794e3Sdrh 
22392282792aSdrh   /* Do an analysis of aggregate expressions.
2240efb7251dSdrh   */
2241d820cb1bSdrh   sqliteAggregateInfoReset(pParse);
2242bb999ef6Sdrh   if( isAgg || pGroupBy ){
22430bce8354Sdrh     assert( pParse->nAgg==0 );
2244bb999ef6Sdrh     isAgg = 1;
22452282792aSdrh     for(i=0; i<pEList->nExpr; i++){
22464adee20fSdanielk1977       if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
22471d83f052Sdrh         goto select_end;
22482282792aSdrh       }
22492282792aSdrh     }
22502282792aSdrh     if( pGroupBy ){
22512282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
22524adee20fSdanielk1977         if( sqlite3ExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
22531d83f052Sdrh           goto select_end;
22542282792aSdrh         }
22552282792aSdrh       }
22562282792aSdrh     }
22574adee20fSdanielk1977     if( pHaving && sqlite3ExprAnalyzeAggregates(pParse, pHaving) ){
22581d83f052Sdrh       goto select_end;
22592282792aSdrh     }
2260191b690eSdrh     if( pOrderBy ){
2261191b690eSdrh       for(i=0; i<pOrderBy->nExpr; i++){
22624adee20fSdanielk1977         if( sqlite3ExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
22631d83f052Sdrh           goto select_end;
2264191b690eSdrh         }
2265191b690eSdrh       }
2266191b690eSdrh     }
2267efb7251dSdrh   }
2268efb7251dSdrh 
22692282792aSdrh   /* Reset the aggregator
2270cce7d176Sdrh   */
2271cce7d176Sdrh   if( isAgg ){
22724adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
2273e5095355Sdrh     for(i=0; i<pParse->nAgg; i++){
22740bce8354Sdrh       FuncDef *pFunc;
22750bce8354Sdrh       if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
22764adee20fSdanielk1977         sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_POINTER);
2277e5095355Sdrh       }
2278e5095355Sdrh     }
22791bee3d7bSdrh     if( pGroupBy==0 ){
22804adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_String, 0, 0);
22814adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AggFocus, 0, 0);
22821bee3d7bSdrh     }
2283cce7d176Sdrh   }
2284cce7d176Sdrh 
228519a775c2Sdrh   /* Initialize the memory cell to NULL
228619a775c2Sdrh   */
2287fef5208cSdrh   if( eDest==SRT_Mem ){
22884adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_String, 0, 0);
22894adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
229019a775c2Sdrh   }
229119a775c2Sdrh 
2292832508b7Sdrh   /* Open a temporary table to use for the distinct set.
2293cce7d176Sdrh   */
229419a775c2Sdrh   if( isDistinct ){
2295832508b7Sdrh     distinct = pParse->nTab++;
22964adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenTemp, distinct, 1);
2297832508b7Sdrh   }else{
2298832508b7Sdrh     distinct = -1;
2299efb7251dSdrh   }
2300832508b7Sdrh 
2301832508b7Sdrh   /* Begin the database scan
2302832508b7Sdrh   */
23034adee20fSdanielk1977   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
230468d2e591Sdrh                             pGroupBy ? 0 : &pOrderBy);
23051d83f052Sdrh   if( pWInfo==0 ) goto select_end;
2306cce7d176Sdrh 
23072282792aSdrh   /* Use the standard inner loop if we are not dealing with
23082282792aSdrh   ** aggregates
2309cce7d176Sdrh   */
2310da9d6c45Sdrh   if( !isAgg ){
2311df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2312df199a25Sdrh                     iParm, pWInfo->iContinue, pWInfo->iBreak) ){
23131d83f052Sdrh        goto select_end;
2314cce7d176Sdrh     }
2315da9d6c45Sdrh   }
2316cce7d176Sdrh 
2317e3184744Sdrh   /* If we are dealing with aggregates, then do the special aggregate
23182282792aSdrh   ** processing.
2319efb7251dSdrh   */
23202282792aSdrh   else{
2321268380caSdrh     AggExpr *pAgg;
23222282792aSdrh     if( pGroupBy ){
23231bee3d7bSdrh       int lbl1;
23242282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
23254adee20fSdanielk1977         sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
2326efb7251dSdrh       }
23274adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
2328*36a3c70bSdanielk1977       sqlite3AddKeyType(v, pGroupBy);
23294adee20fSdanielk1977       lbl1 = sqlite3VdbeMakeLabel(v);
23304adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
2331268380caSdrh       for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2332268380caSdrh         if( pAgg->isAgg ) continue;
23334adee20fSdanielk1977         sqlite3ExprCode(pParse, pAgg->pExpr);
23344adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
23352282792aSdrh       }
23364adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, lbl1);
23372282792aSdrh     }
2338268380caSdrh     for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
23392282792aSdrh       Expr *pE;
2340268380caSdrh       int nExpr;
2341268380caSdrh       FuncDef *pDef;
2342268380caSdrh       if( !pAgg->isAgg ) continue;
2343268380caSdrh       assert( pAgg->pFunc!=0 );
2344268380caSdrh       assert( pAgg->pFunc->xStep!=0 );
2345268380caSdrh       pDef = pAgg->pFunc;
2346268380caSdrh       pE = pAgg->pExpr;
2347268380caSdrh       assert( pE!=0 );
23482282792aSdrh       assert( pE->op==TK_AGG_FUNCTION );
23494adee20fSdanielk1977       nExpr = sqlite3ExprCodeExprList(pParse, pE->pList, pDef->includeTypes);
23504adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, i, 0);
23514adee20fSdanielk1977       sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
23522282792aSdrh     }
23532282792aSdrh   }
23542282792aSdrh 
2355cce7d176Sdrh   /* End the database scan loop.
2356cce7d176Sdrh   */
23574adee20fSdanielk1977   sqlite3WhereEnd(pWInfo);
2358cce7d176Sdrh 
23592282792aSdrh   /* If we are processing aggregates, we need to set up a second loop
23602282792aSdrh   ** over all of the aggregate values and process them.
23612282792aSdrh   */
23622282792aSdrh   if( isAgg ){
23634adee20fSdanielk1977     int endagg = sqlite3VdbeMakeLabel(v);
23642282792aSdrh     int startagg;
23654adee20fSdanielk1977     startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
23662282792aSdrh     pParse->useAgg = 1;
23672282792aSdrh     if( pHaving ){
23684adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
23692282792aSdrh     }
2370df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2371df199a25Sdrh                     iParm, startagg, endagg) ){
23721d83f052Sdrh       goto select_end;
23732282792aSdrh     }
23744adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
23754adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, endagg);
23764adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
23772282792aSdrh     pParse->useAgg = 0;
23782282792aSdrh   }
23792282792aSdrh 
2380cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
2381cce7d176Sdrh   ** and send them to the callback one by one.
2382cce7d176Sdrh   */
2383cce7d176Sdrh   if( pOrderBy ){
2384c926afbcSdrh     generateSortTail(p, v, pEList->nExpr, eDest, iParm);
2385cce7d176Sdrh   }
23866a535340Sdrh 
2387f620b4e2Sdrh   /* If this was a subquery, we have now converted the subquery into a
2388f620b4e2Sdrh   ** temporary table.  So delete the subquery structure from the parent
2389f620b4e2Sdrh   ** to prevent this subquery from being evaluated again and to force the
2390f620b4e2Sdrh   ** the use of the temporary table.
2391f620b4e2Sdrh   */
2392f620b4e2Sdrh   if( pParent ){
2393f620b4e2Sdrh     assert( pParent->pSrc->nSrc>parentTab );
2394f620b4e2Sdrh     assert( pParent->pSrc->a[parentTab].pSelect==p );
23954adee20fSdanielk1977     sqlite3SelectDelete(p);
2396f620b4e2Sdrh     pParent->pSrc->a[parentTab].pSelect = 0;
2397f620b4e2Sdrh   }
2398f620b4e2Sdrh 
23991d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
24001d83f052Sdrh   ** to indicate no errors.
24011d83f052Sdrh   */
24021d83f052Sdrh   rc = 0;
24031d83f052Sdrh 
24041d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
24051d83f052Sdrh   ** successful coding of the SELECT.
24061d83f052Sdrh   */
24071d83f052Sdrh select_end:
24081d83f052Sdrh   sqliteAggregateInfoReset(pParse);
24091d83f052Sdrh   return rc;
2410cce7d176Sdrh }
24114adee20fSdanielk1977 
24124adee20fSdanielk1977 
24134adee20fSdanielk1977 
2414