xref: /sqlite-3.40.0/src/select.c (revision e159fdf2)
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*e159fdf2Sdanielk1977 ** $Id: select.c,v 1.195 2004/06/21 10:45:09 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   int i;
316c926afbcSdrh   for(i=0; i<pOrderBy->nExpr; i++){
3174adee20fSdanielk1977     sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr);
318c926afbcSdrh   }
319ededfd5eSdanielk1977   sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr, 0);
3204adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_SortPut, 0, 0);
321c926afbcSdrh }
322c926afbcSdrh 
323c926afbcSdrh /*
3242282792aSdrh ** This routine generates the code for the inside of the inner loop
3252282792aSdrh ** of a SELECT.
32682c3d636Sdrh **
32738640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
32838640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
32938640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
33038640e15Sdrh ** datatypes for each column.
3312282792aSdrh */
3322282792aSdrh static int selectInnerLoop(
3332282792aSdrh   Parse *pParse,          /* The parser context */
334df199a25Sdrh   Select *p,              /* The complete select statement being coded */
3352282792aSdrh   ExprList *pEList,       /* List of values being extracted */
33682c3d636Sdrh   int srcTab,             /* Pull data from this table */
337967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
3382282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
3392282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
3402282792aSdrh   int eDest,              /* How to dispose of the results */
3412282792aSdrh   int iParm,              /* An argument to the disposal method */
3422282792aSdrh   int iContinue,          /* Jump here to continue with next row */
34384ac9d02Sdanielk1977   int iBreak,             /* Jump here to break out of the inner loop */
34484ac9d02Sdanielk1977   char *aff               /* affinity string if eDest is SRT_Union */
3452282792aSdrh ){
3462282792aSdrh   Vdbe *v = pParse->pVdbe;
3472282792aSdrh   int i;
34838640e15Sdrh 
349daffd0e5Sdrh   if( v==0 ) return 0;
35038640e15Sdrh   assert( pEList!=0 );
3512282792aSdrh 
352df199a25Sdrh   /* If there was a LIMIT clause on the SELECT statement, then do the check
353df199a25Sdrh   ** to see if this row should be output.
354df199a25Sdrh   */
355df199a25Sdrh   if( pOrderBy==0 ){
3567b58daeaSdrh     if( p->iOffset>=0 ){
3574adee20fSdanielk1977       int addr = sqlite3VdbeCurrentAddr(v);
3584adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+2);
3594adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
360df199a25Sdrh     }
3617b58daeaSdrh     if( p->iLimit>=0 ){
3624adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
363df199a25Sdrh     }
364df199a25Sdrh   }
365df199a25Sdrh 
366967e8b73Sdrh   /* Pull the requested columns.
3672282792aSdrh   */
36838640e15Sdrh   if( nColumn>0 ){
369967e8b73Sdrh     for(i=0; i<nColumn; i++){
3704adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
37182c3d636Sdrh     }
37238640e15Sdrh   }else{
37338640e15Sdrh     nColumn = pEList->nExpr;
37438640e15Sdrh     for(i=0; i<pEList->nExpr; i++){
3754adee20fSdanielk1977       sqlite3ExprCode(pParse, pEList->a[i].pExpr);
37638640e15Sdrh     }
37782c3d636Sdrh   }
3782282792aSdrh 
379daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
380daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
381daffd0e5Sdrh   ** part of the result.
3822282792aSdrh   */
383f5905aa7Sdrh   if( distinct>=0 && pEList && pEList->nExpr>0 ){
3840bd1f4eaSdrh #if NULL_ALWAYS_DISTINCT
3854adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
3860bd1f4eaSdrh #endif
387ededfd5eSdanielk1977     /* Deliberately leave the affinity string off of the following
388ededfd5eSdanielk1977     ** OP_MakeRecord */
389ededfd5eSdanielk1977     sqlite3VdbeAddOp(v, OP_MakeRecord, pEList->nExpr * -1, 0);
3904adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
3914adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
3924adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
3930f69c1e3Sdanielk1977     sqlite3VdbeAddOp(v, OP_String8, 0, 0);
3944adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
3952282792aSdrh   }
39682c3d636Sdrh 
397c926afbcSdrh   switch( eDest ){
39882c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
39982c3d636Sdrh     ** table iParm.
4002282792aSdrh     */
401c926afbcSdrh     case SRT_Union: {
4024adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
40384ac9d02Sdanielk1977       sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
4040f69c1e3Sdanielk1977       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
4054adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
406c926afbcSdrh       break;
407c926afbcSdrh     }
40882c3d636Sdrh 
4095974a30fSdrh     /* Store the result as data using a unique key.
4105974a30fSdrh     */
411c926afbcSdrh     case SRT_Table:
412c926afbcSdrh     case SRT_TempTable: {
4134adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
414c926afbcSdrh       if( pOrderBy ){
415c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
416c926afbcSdrh       }else{
4174adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
4184adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
4194adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
420c926afbcSdrh       }
421c926afbcSdrh       break;
422c926afbcSdrh     }
4235974a30fSdrh 
42482c3d636Sdrh     /* Construct a record from the query result, but instead of
42582c3d636Sdrh     ** saving that record, use it as a key to delete elements from
42682c3d636Sdrh     ** the temporary table iParm.
42782c3d636Sdrh     */
428c926afbcSdrh     case SRT_Except: {
4290bd1f4eaSdrh       int addr;
4304adee20fSdanielk1977       addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
43184ac9d02Sdanielk1977       sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
4324adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
4334adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
434c926afbcSdrh       break;
435c926afbcSdrh     }
4362282792aSdrh 
4372282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
4382282792aSdrh     ** then there should be a single item on the stack.  Write this
4392282792aSdrh     ** item into the set table with bogus data.
4402282792aSdrh     */
441c926afbcSdrh     case SRT_Set: {
4424adee20fSdanielk1977       int addr1 = sqlite3VdbeCurrentAddr(v);
44352b36cabSdrh       int addr2;
444e014a838Sdanielk1977 
445967e8b73Sdrh       assert( nColumn==1 );
4464adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
4474adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
4484adee20fSdanielk1977       addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
449c926afbcSdrh       if( pOrderBy ){
450c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
451c926afbcSdrh       }else{
452e014a838Sdanielk1977         char const *affStr;
453e014a838Sdanielk1977         char aff = (iParm>>16)&0xFF;
454e014a838Sdanielk1977         aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
455e014a838Sdanielk1977         affStr = sqlite3AffinityString(aff);
456ededfd5eSdanielk1977         sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, affStr, P3_STATIC);
4570f69c1e3Sdanielk1977         sqlite3VdbeAddOp(v, OP_String8, 0, 0);
458e014a838Sdanielk1977         sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
459c926afbcSdrh       }
4604adee20fSdanielk1977       sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
461c926afbcSdrh       break;
462c926afbcSdrh     }
46382c3d636Sdrh 
4642282792aSdrh     /* If this is a scalar select that is part of an expression, then
4652282792aSdrh     ** store the results in the appropriate memory cell and break out
4662282792aSdrh     ** of the scan loop.
4672282792aSdrh     */
468c926afbcSdrh     case SRT_Mem: {
469967e8b73Sdrh       assert( nColumn==1 );
470c926afbcSdrh       if( pOrderBy ){
471c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
472c926afbcSdrh       }else{
4734adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
4744adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
475c926afbcSdrh       }
476c926afbcSdrh       break;
477c926afbcSdrh     }
4782282792aSdrh 
479f46f905aSdrh     /* Send the data to the callback function.
480f46f905aSdrh     */
481f46f905aSdrh     case SRT_Callback:
482f46f905aSdrh     case SRT_Sorter: {
483f46f905aSdrh       if( pOrderBy ){
484ce665cf6Sdrh         sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
485f46f905aSdrh         pushOntoSorter(pParse, v, pOrderBy);
486f46f905aSdrh       }else{
487f46f905aSdrh         assert( eDest==SRT_Callback );
4884adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
489f46f905aSdrh       }
490f46f905aSdrh       break;
491f46f905aSdrh     }
492f46f905aSdrh 
493142e30dfSdrh     /* Invoke a subroutine to handle the results.  The subroutine itself
494142e30dfSdrh     ** is responsible for popping the results off of the stack.
495142e30dfSdrh     */
496142e30dfSdrh     case SRT_Subroutine: {
497ac82fcf5Sdrh       if( pOrderBy ){
4984adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
499ac82fcf5Sdrh         pushOntoSorter(pParse, v, pOrderBy);
500ac82fcf5Sdrh       }else{
5014adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
502ac82fcf5Sdrh       }
503142e30dfSdrh       break;
504142e30dfSdrh     }
505142e30dfSdrh 
506d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
507d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
508d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
509d7489c39Sdrh     ** about the actual results of the select.
510d7489c39Sdrh     */
511c926afbcSdrh     default: {
512f46f905aSdrh       assert( eDest==SRT_Discard );
5134adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
514c926afbcSdrh       break;
515c926afbcSdrh     }
516c926afbcSdrh   }
51782c3d636Sdrh   return 0;
51882c3d636Sdrh }
51982c3d636Sdrh 
52082c3d636Sdrh /*
521d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
522d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
523d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
524d8bc7086Sdrh ** routine generates the code needed to do that.
525d8bc7086Sdrh */
526c926afbcSdrh static void generateSortTail(
527ffbc3088Sdrh   Parse *pParse,   /* The parsing context */
528c926afbcSdrh   Select *p,       /* The SELECT statement */
529c926afbcSdrh   Vdbe *v,         /* Generate code into this VDBE */
530c926afbcSdrh   int nColumn,     /* Number of columns of data */
531c926afbcSdrh   int eDest,       /* Write the sorted results here */
532c926afbcSdrh   int iParm        /* Optional parameter associated with eDest */
533c926afbcSdrh ){
5344adee20fSdanielk1977   int end1 = sqlite3VdbeMakeLabel(v);
5354adee20fSdanielk1977   int end2 = sqlite3VdbeMakeLabel(v);
536d8bc7086Sdrh   int addr;
537ffbc3088Sdrh   KeyInfo *pInfo;
538ffbc3088Sdrh   ExprList *pOrderBy;
539ffbc3088Sdrh   int nCol, i;
540ffbc3088Sdrh   sqlite *db = pParse->db;
541ffbc3088Sdrh 
542f46f905aSdrh   if( eDest==SRT_Sorter ) return;
543ffbc3088Sdrh   pOrderBy = p->pOrderBy;
544ffbc3088Sdrh   nCol = pOrderBy->nExpr;
545ffbc3088Sdrh   pInfo = sqliteMalloc( sizeof(*pInfo) + nCol*(sizeof(CollSeq*)+1) );
546ffbc3088Sdrh   if( pInfo==0 ) return;
547ffbc3088Sdrh   pInfo->aSortOrder = (char*)&pInfo->aColl[nCol];
548ffbc3088Sdrh   pInfo->nField = nCol;
549ffbc3088Sdrh   for(i=0; i<nCol; i++){
5500202b29eSdanielk1977     /* If a collation sequence was specified explicity, then it
5510202b29eSdanielk1977     ** is stored in pOrderBy->a[i].zName. Otherwise, use the default
5520202b29eSdanielk1977     ** collation type for the expression.
5530202b29eSdanielk1977     */
5547cedc8d4Sdanielk1977     pInfo->aColl[i] = sqlite3ExprCollSeq(pParse, pOrderBy->a[i].pExpr);
5550202b29eSdanielk1977     if( !pInfo->aColl[i] ){
556ffbc3088Sdrh       pInfo->aColl[i] = db->pDfltColl;
5570202b29eSdanielk1977     }
558ffbc3088Sdrh     pInfo->aSortOrder[i] = pOrderBy->a[i].sortOrder;
559ffbc3088Sdrh   }
560ffbc3088Sdrh   sqlite3VdbeOp3(v, OP_Sort, 0, 0, (char*)pInfo, P3_KEYINFO_HANDOFF);
5614adee20fSdanielk1977   addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
5627b58daeaSdrh   if( p->iOffset>=0 ){
5634adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+4);
5644adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
5654adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
566df199a25Sdrh   }
5677b58daeaSdrh   if( p->iLimit>=0 ){
5684adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, end2);
569df199a25Sdrh   }
570c926afbcSdrh   switch( eDest ){
571c926afbcSdrh     case SRT_Table:
572c926afbcSdrh     case SRT_TempTable: {
5734adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
5744adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
5754adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
576c926afbcSdrh       break;
577c926afbcSdrh     }
578c926afbcSdrh     case SRT_Set: {
579c926afbcSdrh       assert( nColumn==1 );
5804adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
5814adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
5824adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
583ededfd5eSdanielk1977       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "n", P3_STATIC);
5840f69c1e3Sdanielk1977       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
585e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
586c926afbcSdrh       break;
587c926afbcSdrh     }
588c926afbcSdrh     case SRT_Mem: {
589c926afbcSdrh       assert( nColumn==1 );
5904adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
5914adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
592c926afbcSdrh       break;
593c926afbcSdrh     }
594ce665cf6Sdrh     case SRT_Callback:
595ac82fcf5Sdrh     case SRT_Subroutine: {
596ac82fcf5Sdrh       int i;
59784ac9d02Sdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
59884ac9d02Sdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
599ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
6004adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
601ac82fcf5Sdrh       }
602ce665cf6Sdrh       if( eDest==SRT_Callback ){
603ce665cf6Sdrh         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
604ce665cf6Sdrh       }else{
6054adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
606ce665cf6Sdrh       }
60784ac9d02Sdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
608ac82fcf5Sdrh       break;
609ac82fcf5Sdrh     }
610c926afbcSdrh     default: {
611f46f905aSdrh       /* Do nothing */
612c926afbcSdrh       break;
613c926afbcSdrh     }
614c926afbcSdrh   }
6154adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
6164adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, end2);
6174adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
6184adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, end1);
6194adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
620d8bc7086Sdrh }
621d8bc7086Sdrh 
622d8bc7086Sdrh /*
623517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
624517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
625e78e8284Sdrh **
626517eb646Sdanielk1977 ** If the declaration type is the exact datatype definition extracted from
627517eb646Sdanielk1977 ** the original CREATE TABLE statement if the expression is a column.
628e78e8284Sdrh **
629517eb646Sdanielk1977 ** The declaration type for an expression is either TEXT, NUMERIC or ANY.
630517eb646Sdanielk1977 ** The declaration type for a ROWID field is INTEGER.
631fcb78a49Sdrh */
632517eb646Sdanielk1977 static const char *columnType(Parse *pParse, SrcList *pTabList, Expr *pExpr){
63300e279d9Sdanielk1977   char const *zType;
634517eb646Sdanielk1977   int j;
63500e279d9Sdanielk1977   if( pExpr==0 || pTabList==0 ) return 0;
63600e279d9Sdanielk1977 
63700e279d9Sdanielk1977   switch( pExpr->op ){
63800e279d9Sdanielk1977     case TK_COLUMN: {
6396a3ea0e6Sdrh       Table *pTab;
640517eb646Sdanielk1977       int iCol = pExpr->iColumn;
641517eb646Sdanielk1977       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable; j++){}
6426a3ea0e6Sdrh       assert( j<pTabList->nSrc );
6436a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
644fcb78a49Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
645fcb78a49Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
646fcb78a49Sdrh       if( iCol<0 ){
647fcb78a49Sdrh         zType = "INTEGER";
648fcb78a49Sdrh       }else{
649fcb78a49Sdrh         zType = pTab->aCol[iCol].zType;
650fcb78a49Sdrh       }
65100e279d9Sdanielk1977       break;
652736c22b8Sdrh     }
65300e279d9Sdanielk1977     case TK_AS:
65400e279d9Sdanielk1977       zType = columnType(pParse, pTabList, pExpr->pLeft);
65500e279d9Sdanielk1977       break;
65600e279d9Sdanielk1977     case TK_SELECT: {
65700e279d9Sdanielk1977       Select *pS = pExpr->pSelect;
65800e279d9Sdanielk1977       zType = columnType(pParse, pS->pSrc, pS->pEList->a[0].pExpr);
65900e279d9Sdanielk1977       break;
660fcb78a49Sdrh     }
66100e279d9Sdanielk1977     default:
66200e279d9Sdanielk1977       zType = 0;
66300e279d9Sdanielk1977   }
66400e279d9Sdanielk1977 
665517eb646Sdanielk1977   return zType;
666517eb646Sdanielk1977 }
667517eb646Sdanielk1977 
668517eb646Sdanielk1977 /*
669517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
670517eb646Sdanielk1977 ** in the result set.
671517eb646Sdanielk1977 */
672517eb646Sdanielk1977 static void generateColumnTypes(
673517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
674517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
675517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
676517eb646Sdanielk1977 ){
677517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
678517eb646Sdanielk1977   int i;
679517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
680517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
681517eb646Sdanielk1977     const char *zType = columnType(pParse, pTabList, p);
68200e279d9Sdanielk1977     if( zType==0 ) continue;
683fbcd585fSdanielk1977     /* The vdbe must make it's own copy of the column-type, in case the
684fbcd585fSdanielk1977     ** schema is reset before this virtual machine is deleted.
685fbcd585fSdanielk1977     */
686fbcd585fSdanielk1977     sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
687fcb78a49Sdrh   }
688fcb78a49Sdrh }
689fcb78a49Sdrh 
690fcb78a49Sdrh /*
691fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
692fcb78a49Sdrh ** in the result set.  This information is used to provide the
693fcabd464Sdrh ** azCol[] values in the callback.
69482c3d636Sdrh */
695832508b7Sdrh static void generateColumnNames(
696832508b7Sdrh   Parse *pParse,      /* Parser context */
697ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
698832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
699832508b7Sdrh ){
700d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
7016a3ea0e6Sdrh   int i, j;
702fcabd464Sdrh   sqlite *db = pParse->db;
703fcabd464Sdrh   int fullNames, shortNames;
704fcabd464Sdrh 
7053cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
7063cf86063Sdanielk1977   if( pParse->explain ){
70761de0d1bSdanielk1977     return;
7083cf86063Sdanielk1977   }
7093cf86063Sdanielk1977 
710d6502758Sdrh   assert( v!=0 );
7116f8a503dSdanielk1977   if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
712d8bc7086Sdrh   pParse->colNamesSet = 1;
713fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
714fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
71522322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
71682c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
71782c3d636Sdrh     Expr *p;
7185a38705eSdrh     p = pEList->a[i].pExpr;
7195a38705eSdrh     if( p==0 ) continue;
72082c3d636Sdrh     if( pEList->a[i].zName ){
72182c3d636Sdrh       char *zName = pEList->a[i].zName;
722d8123366Sdanielk1977       sqlite3VdbeSetColName(v, i, zName, strlen(zName));
72382c3d636Sdrh       continue;
72482c3d636Sdrh     }
725fa173a76Sdrh     if( p->op==TK_COLUMN && pTabList ){
7266a3ea0e6Sdrh       Table *pTab;
72797665873Sdrh       char *zCol;
7288aff1015Sdrh       int iCol = p->iColumn;
7296a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
7306a3ea0e6Sdrh       assert( j<pTabList->nSrc );
7316a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
7328aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
73397665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
734b1363206Sdrh       if( iCol<0 ){
735b1363206Sdrh         zCol = "_ROWID_";
736b1363206Sdrh       }else{
737b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
738b1363206Sdrh       }
739fcabd464Sdrh       if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
7403cf86063Sdanielk1977         sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
741fcabd464Sdrh       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
74282c3d636Sdrh         char *zName = 0;
74382c3d636Sdrh         char *zTab;
74482c3d636Sdrh 
7456a3ea0e6Sdrh         zTab = pTabList->a[j].zAlias;
746fcabd464Sdrh         if( fullNames || zTab==0 ) zTab = pTab->zName;
7474adee20fSdanielk1977         sqlite3SetString(&zName, zTab, ".", zCol, 0);
7483cf86063Sdanielk1977         sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
74982c3d636Sdrh       }else{
7503cf86063Sdanielk1977         sqlite3VdbeSetColName(v, i, zCol, 0);
75182c3d636Sdrh       }
7526977fea8Sdrh     }else if( p->span.z && p->span.z[0] ){
7533cf86063Sdanielk1977       sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
7543cf86063Sdanielk1977       /* sqlite3VdbeCompressSpace(v, addr); */
7551bee3d7bSdrh     }else{
7561bee3d7bSdrh       char zName[30];
7571bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
7581bee3d7bSdrh       sprintf(zName, "column%d", i+1);
7593cf86063Sdanielk1977       sqlite3VdbeSetColName(v, i, zName, 0);
76082c3d636Sdrh     }
76182c3d636Sdrh   }
76276d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
7635080aaa7Sdrh }
76482c3d636Sdrh 
76582c3d636Sdrh /*
766d8bc7086Sdrh ** Name of the connection operator, used for error messages.
767d8bc7086Sdrh */
768d8bc7086Sdrh static const char *selectOpName(int id){
769d8bc7086Sdrh   char *z;
770d8bc7086Sdrh   switch( id ){
771d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
772d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
773d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
774d8bc7086Sdrh     default:           z = "UNION";       break;
775d8bc7086Sdrh   }
776d8bc7086Sdrh   return z;
777d8bc7086Sdrh }
778d8bc7086Sdrh 
779d8bc7086Sdrh /*
780315555caSdrh ** Forward declaration
781315555caSdrh */
782315555caSdrh static int fillInColumnList(Parse*, Select*);
783315555caSdrh 
784315555caSdrh /*
78522f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
78622f70c32Sdrh ** the result set of that SELECT.
78722f70c32Sdrh */
7884adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
78922f70c32Sdrh   Table *pTab;
790b733d037Sdrh   int i, j;
79122f70c32Sdrh   ExprList *pEList;
792b733d037Sdrh   Column *aCol;
79322f70c32Sdrh 
79422f70c32Sdrh   if( fillInColumnList(pParse, pSelect) ){
79522f70c32Sdrh     return 0;
79622f70c32Sdrh   }
79722f70c32Sdrh   pTab = sqliteMalloc( sizeof(Table) );
79822f70c32Sdrh   if( pTab==0 ){
79922f70c32Sdrh     return 0;
80022f70c32Sdrh   }
80122f70c32Sdrh   pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
80222f70c32Sdrh   pEList = pSelect->pEList;
80322f70c32Sdrh   pTab->nCol = pEList->nExpr;
804417be79cSdrh   assert( pTab->nCol>0 );
805b733d037Sdrh   pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
80622f70c32Sdrh   for(i=0; i<pTab->nCol; i++){
807517eb646Sdanielk1977     Expr *pR;
808517eb646Sdanielk1977     char *zType;
809517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
81022f70c32Sdrh     if( pEList->a[i].zName ){
811b733d037Sdrh       aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
812517eb646Sdanielk1977     }else if( p->op==TK_DOT
813b733d037Sdrh                && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
814b733d037Sdrh       int cnt;
8154adee20fSdanielk1977       sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, 0);
816b733d037Sdrh       for(j=cnt=0; j<i; j++){
8174adee20fSdanielk1977         if( sqlite3StrICmp(aCol[j].zName, aCol[i].zName)==0 ){
818b733d037Sdrh           int n;
819b733d037Sdrh           char zBuf[30];
820b733d037Sdrh           sprintf(zBuf,"_%d",++cnt);
821b733d037Sdrh           n = strlen(zBuf);
8224adee20fSdanielk1977           sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, zBuf,n,0);
823b733d037Sdrh           j = -1;
824b733d037Sdrh         }
825b733d037Sdrh       }
826b733d037Sdrh     }else if( p->span.z && p->span.z[0] ){
8274adee20fSdanielk1977       sqlite3SetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
82822f70c32Sdrh     }else{
82922f70c32Sdrh       char zBuf[30];
83022f70c32Sdrh       sprintf(zBuf, "column%d", i+1);
83122f70c32Sdrh       pTab->aCol[i].zName = sqliteStrDup(zBuf);
83222f70c32Sdrh     }
833e014a838Sdanielk1977 
834517eb646Sdanielk1977     zType = sqliteStrDup(columnType(pParse, pSelect->pSrc ,p));
835517eb646Sdanielk1977     pTab->aCol[i].zType = zType;
836517eb646Sdanielk1977     pTab->aCol[i].affinity = SQLITE_AFF_NUMERIC;
837517eb646Sdanielk1977     if( zType ){
838517eb646Sdanielk1977       pTab->aCol[i].affinity = sqlite3AffinityType(zType, strlen(zType));
839517eb646Sdanielk1977     }
8407cedc8d4Sdanielk1977     pTab->aCol[i].pColl = sqlite3ExprCollSeq(pParse, p);
8410202b29eSdanielk1977     if( !pTab->aCol[i].pColl ){
8420202b29eSdanielk1977       pTab->aCol[i].pColl = pParse->db->pDfltColl;
8430202b29eSdanielk1977     }
84422f70c32Sdrh   }
84522f70c32Sdrh   pTab->iPKey = -1;
84622f70c32Sdrh   return pTab;
84722f70c32Sdrh }
84822f70c32Sdrh 
84922f70c32Sdrh /*
850ad2d8307Sdrh ** For the given SELECT statement, do three things.
851d8bc7086Sdrh **
852ad3cab52Sdrh **    (1)  Fill in the pTabList->a[].pTab fields in the SrcList that
85363eb5f29Sdrh **         defines the set of tables that should be scanned.  For views,
85463eb5f29Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
85563eb5f29Sdrh **         that implements the view.  A copy is made of the view's SELECT
85663eb5f29Sdrh **         statement so that we can freely modify or delete that statement
85763eb5f29Sdrh **         without worrying about messing up the presistent representation
85863eb5f29Sdrh **         of the view.
859d8bc7086Sdrh **
860ad2d8307Sdrh **    (2)  Add terms to the WHERE clause to accomodate the NATURAL keyword
861ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
862ad2d8307Sdrh **
863ad2d8307Sdrh **    (3)  Scan the list of columns in the result set (pEList) looking
86454473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
86554473229Sdrh **         If found, expand each "*" to be every column in every table
86654473229Sdrh **         and TABLE.* to be every column in TABLE.
867d8bc7086Sdrh **
868d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
869d8bc7086Sdrh ** in pParse and return non-zero.
870d8bc7086Sdrh */
871d8bc7086Sdrh static int fillInColumnList(Parse *pParse, Select *p){
87254473229Sdrh   int i, j, k, rc;
873ad3cab52Sdrh   SrcList *pTabList;
874daffd0e5Sdrh   ExprList *pEList;
875a76b5dfcSdrh   Table *pTab;
876daffd0e5Sdrh 
877daffd0e5Sdrh   if( p==0 || p->pSrc==0 ) return 1;
878daffd0e5Sdrh   pTabList = p->pSrc;
879daffd0e5Sdrh   pEList = p->pEList;
880d8bc7086Sdrh 
881d8bc7086Sdrh   /* Look up every table in the table list.
882d8bc7086Sdrh   */
883ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
884d8bc7086Sdrh     if( pTabList->a[i].pTab ){
885d8bc7086Sdrh       /* This routine has run before!  No need to continue */
886d8bc7086Sdrh       return 0;
887d8bc7086Sdrh     }
888daffd0e5Sdrh     if( pTabList->a[i].zName==0 ){
88922f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
89022f70c32Sdrh       assert( pTabList->a[i].pSelect!=0 );
891ad2d8307Sdrh       if( pTabList->a[i].zAlias==0 ){
892ad2d8307Sdrh         char zFakeName[60];
893ad2d8307Sdrh         sprintf(zFakeName, "sqlite_subquery_%p_",
894ad2d8307Sdrh            (void*)pTabList->a[i].pSelect);
8954adee20fSdanielk1977         sqlite3SetString(&pTabList->a[i].zAlias, zFakeName, 0);
896ad2d8307Sdrh       }
89722f70c32Sdrh       pTabList->a[i].pTab = pTab =
8984adee20fSdanielk1977         sqlite3ResultSetOfSelect(pParse, pTabList->a[i].zAlias,
89922f70c32Sdrh                                         pTabList->a[i].pSelect);
90022f70c32Sdrh       if( pTab==0 ){
901daffd0e5Sdrh         return 1;
902daffd0e5Sdrh       }
9035cf590c1Sdrh       /* The isTransient flag indicates that the Table structure has been
9045cf590c1Sdrh       ** dynamically allocated and may be freed at any time.  In other words,
9055cf590c1Sdrh       ** pTab is not pointing to a persistent table structure that defines
9065cf590c1Sdrh       ** part of the schema. */
90722f70c32Sdrh       pTab->isTransient = 1;
90822f70c32Sdrh     }else{
909a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
910a76b5dfcSdrh       pTabList->a[i].pTab = pTab =
9114adee20fSdanielk1977         sqlite3LocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
912a76b5dfcSdrh       if( pTab==0 ){
913d8bc7086Sdrh         return 1;
914d8bc7086Sdrh       }
915a76b5dfcSdrh       if( pTab->pSelect ){
91663eb5f29Sdrh         /* We reach here if the named table is a really a view */
9174adee20fSdanielk1977         if( sqlite3ViewGetColumnNames(pParse, pTab) ){
918417be79cSdrh           return 1;
919417be79cSdrh         }
92063eb5f29Sdrh         /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
92163eb5f29Sdrh         ** view within a view.  The SELECT structure has already been
92263eb5f29Sdrh         ** copied by the outer view so we can skip the copy step here
92363eb5f29Sdrh         ** in the inner view.
92463eb5f29Sdrh         */
92563eb5f29Sdrh         if( pTabList->a[i].pSelect==0 ){
9264adee20fSdanielk1977           pTabList->a[i].pSelect = sqlite3SelectDup(pTab->pSelect);
927a76b5dfcSdrh         }
928d8bc7086Sdrh       }
92922f70c32Sdrh     }
93063eb5f29Sdrh   }
931d8bc7086Sdrh 
932ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
933ad2d8307Sdrh   */
934ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
935ad2d8307Sdrh 
9367c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
93754473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
93854473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
9397c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
9407c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
9417c917d19Sdrh   ** each one to the list of all columns in all tables.
94254473229Sdrh   **
94354473229Sdrh   ** The first loop just checks to see if there are any "*" operators
94454473229Sdrh   ** that need expanding.
945d8bc7086Sdrh   */
9467c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
94754473229Sdrh     Expr *pE = pEList->a[k].pExpr;
94854473229Sdrh     if( pE->op==TK_ALL ) break;
94954473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
95054473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
9517c917d19Sdrh   }
95254473229Sdrh   rc = 0;
9537c917d19Sdrh   if( k<pEList->nExpr ){
95454473229Sdrh     /*
95554473229Sdrh     ** If we get here it means the result set contains one or more "*"
95654473229Sdrh     ** operators that need to be expanded.  Loop through each expression
95754473229Sdrh     ** in the result set and expand them one by one.
95854473229Sdrh     */
9597c917d19Sdrh     struct ExprList_item *a = pEList->a;
9607c917d19Sdrh     ExprList *pNew = 0;
9617c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
96254473229Sdrh       Expr *pE = a[k].pExpr;
96354473229Sdrh       if( pE->op!=TK_ALL &&
96454473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
96554473229Sdrh         /* This particular expression does not need to be expanded.
96654473229Sdrh         */
9674adee20fSdanielk1977         pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
9687c917d19Sdrh         pNew->a[pNew->nExpr-1].zName = a[k].zName;
9697c917d19Sdrh         a[k].pExpr = 0;
9707c917d19Sdrh         a[k].zName = 0;
9717c917d19Sdrh       }else{
97254473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
97354473229Sdrh         ** expanded. */
97454473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
97554473229Sdrh         Token *pName;           /* text of name of TABLE */
97654473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
97754473229Sdrh           pName = &pE->pLeft->token;
97854473229Sdrh         }else{
97954473229Sdrh           pName = 0;
98054473229Sdrh         }
981ad3cab52Sdrh         for(i=0; i<pTabList->nSrc; i++){
982d8bc7086Sdrh           Table *pTab = pTabList->a[i].pTab;
98354473229Sdrh           char *zTabName = pTabList->a[i].zAlias;
98454473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
98554473229Sdrh             zTabName = pTab->zName;
98654473229Sdrh           }
98754473229Sdrh           if( pName && (zTabName==0 || zTabName[0]==0 ||
9884adee20fSdanielk1977                  sqlite3StrNICmp(pName->z, zTabName, pName->n)!=0 ||
989c754fa54Sdrh                  zTabName[pName->n]!=0) ){
99054473229Sdrh             continue;
99154473229Sdrh           }
99254473229Sdrh           tableSeen = 1;
993d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
99422f70c32Sdrh             Expr *pExpr, *pLeft, *pRight;
995ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
996ad2d8307Sdrh 
997ad2d8307Sdrh             if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
998ad2d8307Sdrh                 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
999ad2d8307Sdrh               /* In a NATURAL join, omit the join columns from the
1000ad2d8307Sdrh               ** table on the right */
1001ad2d8307Sdrh               continue;
1002ad2d8307Sdrh             }
10034adee20fSdanielk1977             if( i>0 && sqlite3IdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
1004ad2d8307Sdrh               /* In a join with a USING clause, omit columns in the
1005ad2d8307Sdrh               ** using clause from the table on the right. */
1006ad2d8307Sdrh               continue;
1007ad2d8307Sdrh             }
10084adee20fSdanielk1977             pRight = sqlite3Expr(TK_ID, 0, 0, 0);
100922f70c32Sdrh             if( pRight==0 ) break;
1010ad2d8307Sdrh             pRight->token.z = zName;
1011ad2d8307Sdrh             pRight->token.n = strlen(zName);
10124b59ab5eSdrh             pRight->token.dyn = 0;
10134b59ab5eSdrh             if( zTabName && pTabList->nSrc>1 ){
10144adee20fSdanielk1977               pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
10154adee20fSdanielk1977               pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
101622f70c32Sdrh               if( pExpr==0 ) break;
10174b59ab5eSdrh               pLeft->token.z = zTabName;
10184b59ab5eSdrh               pLeft->token.n = strlen(zTabName);
10194b59ab5eSdrh               pLeft->token.dyn = 0;
10204adee20fSdanielk1977               sqlite3SetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
10216977fea8Sdrh               pExpr->span.n = strlen(pExpr->span.z);
10226977fea8Sdrh               pExpr->span.dyn = 1;
10236977fea8Sdrh               pExpr->token.z = 0;
10246977fea8Sdrh               pExpr->token.n = 0;
10256977fea8Sdrh               pExpr->token.dyn = 0;
102622f70c32Sdrh             }else{
102722f70c32Sdrh               pExpr = pRight;
10286977fea8Sdrh               pExpr->span = pExpr->token;
102922f70c32Sdrh             }
10304adee20fSdanielk1977             pNew = sqlite3ExprListAppend(pNew, pExpr, 0);
1031d8bc7086Sdrh           }
1032d8bc7086Sdrh         }
103354473229Sdrh         if( !tableSeen ){
1034f5db2d3eSdrh           if( pName ){
10354adee20fSdanielk1977             sqlite3ErrorMsg(pParse, "no such table: %T", pName);
1036f5db2d3eSdrh           }else{
10374adee20fSdanielk1977             sqlite3ErrorMsg(pParse, "no tables specified");
1038f5db2d3eSdrh           }
103954473229Sdrh           rc = 1;
104054473229Sdrh         }
10417c917d19Sdrh       }
10427c917d19Sdrh     }
10434adee20fSdanielk1977     sqlite3ExprListDelete(pEList);
10447c917d19Sdrh     p->pEList = pNew;
1045d8bc7086Sdrh   }
104654473229Sdrh   return rc;
1047d8bc7086Sdrh }
1048d8bc7086Sdrh 
1049d8bc7086Sdrh /*
1050ff78bd2fSdrh ** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1051ff78bd2fSdrh ** in a select structure.  It just sets the pointers to NULL.  This
1052ff78bd2fSdrh ** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1053ff78bd2fSdrh ** pointer is not NULL, this routine is called recursively on that pointer.
1054ff78bd2fSdrh **
1055ff78bd2fSdrh ** This routine is called on the Select structure that defines a
1056ff78bd2fSdrh ** VIEW in order to undo any bindings to tables.  This is necessary
1057ff78bd2fSdrh ** because those tables might be DROPed by a subsequent SQL command.
10585cf590c1Sdrh ** If the bindings are not removed, then the Select.pSrc->a[].pTab field
10595cf590c1Sdrh ** will be left pointing to a deallocated Table structure after the
10605cf590c1Sdrh ** DROP and a coredump will occur the next time the VIEW is used.
1061ff78bd2fSdrh */
10624adee20fSdanielk1977 void sqlite3SelectUnbind(Select *p){
1063ff78bd2fSdrh   int i;
1064ad3cab52Sdrh   SrcList *pSrc = p->pSrc;
1065ff78bd2fSdrh   Table *pTab;
1066ff78bd2fSdrh   if( p==0 ) return;
1067ad3cab52Sdrh   for(i=0; i<pSrc->nSrc; i++){
1068ff78bd2fSdrh     if( (pTab = pSrc->a[i].pTab)!=0 ){
1069ff78bd2fSdrh       if( pTab->isTransient ){
10704adee20fSdanielk1977         sqlite3DeleteTable(0, pTab);
1071ff78bd2fSdrh       }
1072ff78bd2fSdrh       pSrc->a[i].pTab = 0;
1073ff78bd2fSdrh       if( pSrc->a[i].pSelect ){
10744adee20fSdanielk1977         sqlite3SelectUnbind(pSrc->a[i].pSelect);
1075ff78bd2fSdrh       }
1076ff78bd2fSdrh     }
1077ff78bd2fSdrh   }
1078ff78bd2fSdrh }
1079ff78bd2fSdrh 
1080ff78bd2fSdrh /*
1081d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with
1082d8bc7086Sdrh ** columns in a result.  For each ORDER BY expression, the opcode of
1083967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of
1084d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable
1085d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter.
1086d8bc7086Sdrh **
1087d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first.  A match
1088d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT.
1089d8bc7086Sdrh **
1090d8bc7086Sdrh ** Any entry that does not match is flagged as an error.  The number
1091d8bc7086Sdrh ** of errors is returned.
1092d8bc7086Sdrh */
1093d8bc7086Sdrh static int matchOrderbyToColumn(
1094d8bc7086Sdrh   Parse *pParse,          /* A place to leave error messages */
1095d8bc7086Sdrh   Select *pSelect,        /* Match to result columns of this SELECT */
1096d8bc7086Sdrh   ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
1097e4de1febSdrh   int iTable,             /* Insert this value in iTable */
1098d8bc7086Sdrh   int mustComplete        /* If TRUE all ORDER BYs must match */
1099d8bc7086Sdrh ){
1100d8bc7086Sdrh   int nErr = 0;
1101d8bc7086Sdrh   int i, j;
1102d8bc7086Sdrh   ExprList *pEList;
1103d8bc7086Sdrh 
1104daffd0e5Sdrh   if( pSelect==0 || pOrderBy==0 ) return 1;
1105d8bc7086Sdrh   if( mustComplete ){
1106d8bc7086Sdrh     for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1107d8bc7086Sdrh   }
1108d8bc7086Sdrh   if( fillInColumnList(pParse, pSelect) ){
1109d8bc7086Sdrh     return 1;
1110d8bc7086Sdrh   }
1111d8bc7086Sdrh   if( pSelect->pPrior ){
111292cd52f5Sdrh     if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
111392cd52f5Sdrh       return 1;
111492cd52f5Sdrh     }
1115d8bc7086Sdrh   }
1116d8bc7086Sdrh   pEList = pSelect->pEList;
1117d8bc7086Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
1118d8bc7086Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
1119e4de1febSdrh     int iCol = -1;
1120d8bc7086Sdrh     if( pOrderBy->a[i].done ) continue;
11214adee20fSdanielk1977     if( sqlite3ExprIsInteger(pE, &iCol) ){
1122e4de1febSdrh       if( iCol<=0 || iCol>pEList->nExpr ){
11234adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
1124da93d238Sdrh           "ORDER BY position %d should be between 1 and %d",
1125e4de1febSdrh           iCol, pEList->nExpr);
1126e4de1febSdrh         nErr++;
1127e4de1febSdrh         break;
1128e4de1febSdrh       }
1129fcb78a49Sdrh       if( !mustComplete ) continue;
1130e4de1febSdrh       iCol--;
1131e4de1febSdrh     }
1132e4de1febSdrh     for(j=0; iCol<0 && j<pEList->nExpr; j++){
11334cfa7934Sdrh       if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
1134a76b5dfcSdrh         char *zName, *zLabel;
1135a76b5dfcSdrh         zName = pEList->a[j].zName;
1136a99db3b6Sdrh         zLabel = sqlite3NameFromToken(&pE->token);
1137a99db3b6Sdrh         assert( zLabel!=0 );
11384adee20fSdanielk1977         if( sqlite3StrICmp(zName, zLabel)==0 ){
1139e4de1febSdrh           iCol = j;
1140d8bc7086Sdrh         }
11416e142f54Sdrh         sqliteFree(zLabel);
1142d8bc7086Sdrh       }
11434adee20fSdanielk1977       if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
1144e4de1febSdrh         iCol = j;
1145d8bc7086Sdrh       }
1146e4de1febSdrh     }
1147e4de1febSdrh     if( iCol>=0 ){
1148967e8b73Sdrh       pE->op = TK_COLUMN;
1149e4de1febSdrh       pE->iColumn = iCol;
1150d8bc7086Sdrh       pE->iTable = iTable;
1151d8bc7086Sdrh       pOrderBy->a[i].done = 1;
1152d8bc7086Sdrh     }
1153e4de1febSdrh     if( iCol<0 && mustComplete ){
11544adee20fSdanielk1977       sqlite3ErrorMsg(pParse,
1155da93d238Sdrh         "ORDER BY term number %d does not match any result column", i+1);
1156d8bc7086Sdrh       nErr++;
1157d8bc7086Sdrh       break;
1158d8bc7086Sdrh     }
1159d8bc7086Sdrh   }
1160d8bc7086Sdrh   return nErr;
1161d8bc7086Sdrh }
1162d8bc7086Sdrh 
1163d8bc7086Sdrh /*
1164d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1165d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1166d8bc7086Sdrh */
11674adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1168d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1169d8bc7086Sdrh   if( v==0 ){
11704adee20fSdanielk1977     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1171d8bc7086Sdrh   }
1172d8bc7086Sdrh   return v;
1173d8bc7086Sdrh }
1174d8bc7086Sdrh 
1175d3d39e93Sdrh #if 0  /***** This routine needs deleting *****/
117684ac9d02Sdanielk1977 static void multiSelectAffinity(Select *p, char *zAff){
117784ac9d02Sdanielk1977   int i;
117884ac9d02Sdanielk1977 
117984ac9d02Sdanielk1977   if( !p ) return;
118084ac9d02Sdanielk1977   multiSelectAffinity(p->pPrior, zAff);
118184ac9d02Sdanielk1977 
118284ac9d02Sdanielk1977   for(i=0; i<p->pEList->nExpr; i++){
118384ac9d02Sdanielk1977     if( zAff[i]=='\0' ){
118484ac9d02Sdanielk1977       zAff[i] = sqlite3ExprAffinity(p->pEList->a[i].pExpr);
118584ac9d02Sdanielk1977     }
118684ac9d02Sdanielk1977   }
118784ac9d02Sdanielk1977 }
1188d3d39e93Sdrh #endif
118984ac9d02Sdanielk1977 
1190d8bc7086Sdrh /*
11917b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
11927b58daeaSdrh ** nLimit and nOffset fields.  nLimit and nOffset hold the integers
11937b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
11947b58daeaSdrh ** keywords.  Or that hold -1 and 0 if those keywords are omitted.
11957b58daeaSdrh ** iLimit and iOffset are the integer memory register numbers for
11967b58daeaSdrh ** counters used to compute the limit and offset.  If there is no
11977b58daeaSdrh ** limit and/or offset, then iLimit and iOffset are negative.
11987b58daeaSdrh **
11997b58daeaSdrh ** This routine changes the values if iLimit and iOffset only if
12007b58daeaSdrh ** a limit or offset is defined by nLimit and nOffset.  iLimit and
12017b58daeaSdrh ** iOffset should have been preset to appropriate default values
12027b58daeaSdrh ** (usually but not always -1) prior to calling this routine.
12037b58daeaSdrh ** Only if nLimit>=0 or nOffset>0 do the limit registers get
12047b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
12057b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
12067b58daeaSdrh ** SELECT statements.
12077b58daeaSdrh */
12087b58daeaSdrh static void computeLimitRegisters(Parse *pParse, Select *p){
12097b58daeaSdrh   /*
12107b58daeaSdrh   ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
12117b58daeaSdrh   ** all rows.  It is the same as no limit. If the comparision is
12127b58daeaSdrh   ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
12137b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
12147b58daeaSdrh   ** contraversy about what the correct behavior should be.
12157b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
12167b58daeaSdrh   ** no rows.
12177b58daeaSdrh   */
12187b58daeaSdrh   if( p->nLimit>=0 ){
12197b58daeaSdrh     int iMem = pParse->nMem++;
12204adee20fSdanielk1977     Vdbe *v = sqlite3GetVdbe(pParse);
12217b58daeaSdrh     if( v==0 ) return;
12224adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, -p->nLimit, 0);
12234adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
12247b58daeaSdrh     p->iLimit = iMem;
12257b58daeaSdrh   }
12267b58daeaSdrh   if( p->nOffset>0 ){
12277b58daeaSdrh     int iMem = pParse->nMem++;
12284adee20fSdanielk1977     Vdbe *v = sqlite3GetVdbe(pParse);
12297b58daeaSdrh     if( v==0 ) return;
12304adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, -p->nOffset, 0);
12314adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
12327b58daeaSdrh     p->iOffset = iMem;
12337b58daeaSdrh   }
12347b58daeaSdrh }
12357b58daeaSdrh 
12367b58daeaSdrh /*
1237d3d39e93Sdrh ** Generate VDBE instructions that will open a transient table that
1238d3d39e93Sdrh ** will be used for an index or to store keyed results for a compound
1239d3d39e93Sdrh ** select.  In other words, open a transient table that needs a
1240d3d39e93Sdrh ** KeyInfo structure.  The number of columns in the KeyInfo is determined
1241d3d39e93Sdrh ** by the result set of the SELECT statement in the second argument.
1242d3d39e93Sdrh **
1243dc1bdc4fSdanielk1977 ** Specifically, this routine is called to open an index table for
1244dc1bdc4fSdanielk1977 ** DISTINCT, UNION, INTERSECT and EXCEPT select statements (but not
1245dc1bdc4fSdanielk1977 ** UNION ALL).
1246dc1bdc4fSdanielk1977 **
1247d3d39e93Sdrh ** Make the new table a KeyAsData table if keyAsData is true.
1248dc1bdc4fSdanielk1977 **
1249dc1bdc4fSdanielk1977 ** The value returned is the address of the OP_OpenTemp instruction.
1250d3d39e93Sdrh */
1251dc1bdc4fSdanielk1977 static int openTempIndex(Parse *pParse, Select *p, int iTab, int keyAsData){
1252d3d39e93Sdrh   KeyInfo *pKeyInfo;
1253736c22b8Sdrh   int nColumn;
1254d3d39e93Sdrh   sqlite *db = pParse->db;
1255d3d39e93Sdrh   int i;
1256d3d39e93Sdrh   Vdbe *v = pParse->pVdbe;
1257dc1bdc4fSdanielk1977   int addr;
1258d3d39e93Sdrh 
1259736c22b8Sdrh   if( fillInColumnList(pParse, p) ){
1260dc1bdc4fSdanielk1977     return 0;
1261736c22b8Sdrh   }
1262736c22b8Sdrh   nColumn = p->pEList->nExpr;
1263d3d39e93Sdrh   pKeyInfo = sqliteMalloc( sizeof(*pKeyInfo)+nColumn*sizeof(CollSeq*) );
1264dc1bdc4fSdanielk1977   if( pKeyInfo==0 ) return 0;
1265dc1bdc4fSdanielk1977   pKeyInfo->enc = pParse->db->enc;
1266d3d39e93Sdrh   pKeyInfo->nField = nColumn;
1267d3d39e93Sdrh   for(i=0; i<nColumn; i++){
1268dc1bdc4fSdanielk1977     pKeyInfo->aColl[i] = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
1269dc1bdc4fSdanielk1977     if( !pKeyInfo->aColl[i] ){
1270d3d39e93Sdrh       pKeyInfo->aColl[i] = db->pDfltColl;
1271d3d39e93Sdrh     }
1272dc1bdc4fSdanielk1977   }
1273dc1bdc4fSdanielk1977   addr = sqlite3VdbeOp3(v, OP_OpenTemp, iTab, 0,
1274dc1bdc4fSdanielk1977       (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
1275d3d39e93Sdrh   if( keyAsData ){
1276d3d39e93Sdrh     sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
1277d3d39e93Sdrh   }
1278dc1bdc4fSdanielk1977   return addr;
1279dc1bdc4fSdanielk1977 }
1280dc1bdc4fSdanielk1977 
1281dc1bdc4fSdanielk1977 static int multiSelectOpenTempAddr(Select *p, int addr, IdList **ppOpenTemp){
1282dc1bdc4fSdanielk1977   if( !p->ppOpenTemp ){
1283dc1bdc4fSdanielk1977     *ppOpenTemp = sqlite3IdListAppend(0, 0);
1284dc1bdc4fSdanielk1977     p->ppOpenTemp = ppOpenTemp;
1285dc1bdc4fSdanielk1977   }else{
1286dc1bdc4fSdanielk1977     *p->ppOpenTemp = sqlite3IdListAppend(*p->ppOpenTemp, 0);
1287dc1bdc4fSdanielk1977   }
1288dc1bdc4fSdanielk1977   if( !(*p->ppOpenTemp) ){
1289dc1bdc4fSdanielk1977     return SQLITE_NOMEM;
1290dc1bdc4fSdanielk1977   }
1291dc1bdc4fSdanielk1977   (*p->ppOpenTemp)->a[(*p->ppOpenTemp)->nId-1].idx = addr;
1292dc1bdc4fSdanielk1977   return SQLITE_OK;
1293dc1bdc4fSdanielk1977 }
1294dc1bdc4fSdanielk1977 
1295dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1296dc1bdc4fSdanielk1977   CollSeq *pRet = 0;
1297dc1bdc4fSdanielk1977   if( p->pPrior ){
1298dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1299dc1bdc4fSdanielk1977   }
1300dc1bdc4fSdanielk1977   if( !pRet ){
1301dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1302dc1bdc4fSdanielk1977   }
1303dc1bdc4fSdanielk1977   return pRet;
1304d3d39e93Sdrh }
1305d3d39e93Sdrh 
1306d3d39e93Sdrh /*
130782c3d636Sdrh ** This routine is called to process a query that is really the union
130882c3d636Sdrh ** or intersection of two or more separate queries.
1309c926afbcSdrh **
1310e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1311e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1312e78e8284Sdrh ** in which case this routine will be called recursively.
1313e78e8284Sdrh **
1314e78e8284Sdrh ** The results of the total query are to be written into a destination
1315e78e8284Sdrh ** of type eDest with parameter iParm.
1316e78e8284Sdrh **
1317e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1318e78e8284Sdrh **
1319e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1320e78e8284Sdrh **
1321e78e8284Sdrh ** This statement is parsed up as follows:
1322e78e8284Sdrh **
1323e78e8284Sdrh **     SELECT c FROM t3
1324e78e8284Sdrh **      |
1325e78e8284Sdrh **      `----->  SELECT b FROM t2
1326e78e8284Sdrh **                |
13274b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1328e78e8284Sdrh **
1329e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1330e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1331e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1332e78e8284Sdrh **
1333e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1334e78e8284Sdrh ** individual selects always group from left to right.
133582c3d636Sdrh */
133684ac9d02Sdanielk1977 static int multiSelect(
133784ac9d02Sdanielk1977   Parse *pParse,
133884ac9d02Sdanielk1977   Select *p,
133984ac9d02Sdanielk1977   int eDest,
134084ac9d02Sdanielk1977   int iParm,
134184ac9d02Sdanielk1977   char *aff           /* If eDest is SRT_Union, the affinity string */
134284ac9d02Sdanielk1977 ){
134384ac9d02Sdanielk1977   int rc = SQLITE_OK;  /* Success code from a subroutine */
134410e5e3cfSdrh   Select *pPrior;     /* Another SELECT immediately to our left */
134510e5e3cfSdrh   Vdbe *v;            /* Generate code to this VDBE */
1346dc1bdc4fSdanielk1977   IdList *pOpenTemp = 0;
134782c3d636Sdrh 
13487b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
13497b58daeaSdrh   ** the last SELECT in the series may have an ORDER BY or LIMIT.
135082c3d636Sdrh   */
135184ac9d02Sdanielk1977   if( p==0 || p->pPrior==0 ){
135284ac9d02Sdanielk1977     rc = 1;
135384ac9d02Sdanielk1977     goto multi_select_end;
135484ac9d02Sdanielk1977   }
1355d8bc7086Sdrh   pPrior = p->pPrior;
1356d8bc7086Sdrh   if( pPrior->pOrderBy ){
13574adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1358da93d238Sdrh       selectOpName(p->op));
135984ac9d02Sdanielk1977     rc = 1;
136084ac9d02Sdanielk1977     goto multi_select_end;
136182c3d636Sdrh   }
13627b58daeaSdrh   if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
13634adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
13647b58daeaSdrh       selectOpName(p->op));
136584ac9d02Sdanielk1977     rc = 1;
136684ac9d02Sdanielk1977     goto multi_select_end;
13677b58daeaSdrh   }
136882c3d636Sdrh 
1369d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
1370d8bc7086Sdrh   */
13714adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
137284ac9d02Sdanielk1977   if( v==0 ){
137384ac9d02Sdanielk1977     rc = 1;
137484ac9d02Sdanielk1977     goto multi_select_end;
137584ac9d02Sdanielk1977   }
1376d8bc7086Sdrh 
13771cc3d75fSdrh   /* Create the destination temporary table if necessary
13781cc3d75fSdrh   */
13791cc3d75fSdrh   if( eDest==SRT_TempTable ){
1380b4964b72Sdanielk1977     assert( p->pEList );
13814adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
1382b4964b72Sdanielk1977     sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, p->pEList->nExpr);
13831cc3d75fSdrh     eDest = SRT_Table;
13841cc3d75fSdrh   }
13851cc3d75fSdrh 
1386f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1387d8bc7086Sdrh   */
138882c3d636Sdrh   switch( p->op ){
1389f46f905aSdrh     case TK_ALL: {
1390f46f905aSdrh       if( p->pOrderBy==0 ){
13917b58daeaSdrh         pPrior->nLimit = p->nLimit;
13927b58daeaSdrh         pPrior->nOffset = p->nOffset;
1393dc1bdc4fSdanielk1977         pPrior->ppOpenTemp = p->ppOpenTemp;
139484ac9d02Sdanielk1977         rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
139584ac9d02Sdanielk1977         if( rc ){
139684ac9d02Sdanielk1977           goto multi_select_end;
139784ac9d02Sdanielk1977         }
1398f46f905aSdrh         p->pPrior = 0;
13997b58daeaSdrh         p->iLimit = pPrior->iLimit;
14007b58daeaSdrh         p->iOffset = pPrior->iOffset;
14017b58daeaSdrh         p->nLimit = -1;
14027b58daeaSdrh         p->nOffset = 0;
140384ac9d02Sdanielk1977         rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
1404f46f905aSdrh         p->pPrior = pPrior;
140584ac9d02Sdanielk1977         if( rc ){
140684ac9d02Sdanielk1977           goto multi_select_end;
140784ac9d02Sdanielk1977         }
1408f46f905aSdrh         break;
1409f46f905aSdrh       }
1410f46f905aSdrh       /* For UNION ALL ... ORDER BY fall through to the next case */
1411f46f905aSdrh     }
141282c3d636Sdrh     case TK_EXCEPT:
141382c3d636Sdrh     case TK_UNION: {
1414d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1415742f947bSdanielk1977       int op = 0;      /* One of the SRT_ operations to apply to self */
1416d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
14177b58daeaSdrh       int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
1418c926afbcSdrh       ExprList *pOrderBy;  /* The ORDER BY clause for the right SELECT */
1419dc1bdc4fSdanielk1977       int addr;
142082c3d636Sdrh 
1421d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
14227b58daeaSdrh       if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
1423d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1424c926afbcSdrh         ** right.
1425d8bc7086Sdrh         */
142682c3d636Sdrh         unionTab = iParm;
142782c3d636Sdrh       }else{
1428d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1429d8bc7086Sdrh         ** intermediate results.
1430d8bc7086Sdrh         */
143182c3d636Sdrh         unionTab = pParse->nTab++;
1432d8bc7086Sdrh         if( p->pOrderBy
1433d8bc7086Sdrh         && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
143484ac9d02Sdanielk1977           rc = 1;
143584ac9d02Sdanielk1977           goto multi_select_end;
1436d8bc7086Sdrh         }
1437dc1bdc4fSdanielk1977         addr = sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
1438d8bc7086Sdrh         if( p->op!=TK_ALL ){
1439dc1bdc4fSdanielk1977           rc = multiSelectOpenTempAddr(p, addr, &pOpenTemp);
1440dc1bdc4fSdanielk1977           if( rc!=SQLITE_OK ){
1441dc1bdc4fSdanielk1977             goto multi_select_end;
1442dc1bdc4fSdanielk1977           }
1443dc1bdc4fSdanielk1977           sqlite3VdbeAddOp(v, OP_KeyAsData, unionTab, 1);
144482c3d636Sdrh         }
144584ac9d02Sdanielk1977         assert( p->pEList );
1446d8bc7086Sdrh       }
1447d8bc7086Sdrh 
1448d8bc7086Sdrh       /* Code the SELECT statements to our left
1449d8bc7086Sdrh       */
1450dc1bdc4fSdanielk1977       pPrior->ppOpenTemp = p->ppOpenTemp;
145184ac9d02Sdanielk1977       rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
145284ac9d02Sdanielk1977       if( rc ){
145384ac9d02Sdanielk1977         goto multi_select_end;
145484ac9d02Sdanielk1977       }
145584ac9d02Sdanielk1977       if( p->op==TK_ALL ){
145684ac9d02Sdanielk1977         sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, pPrior->pEList->nExpr);
145784ac9d02Sdanielk1977       }
1458d8bc7086Sdrh 
1459d8bc7086Sdrh       /* Code the current SELECT statement
1460d8bc7086Sdrh       */
1461d8bc7086Sdrh       switch( p->op ){
1462d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
1463d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
1464d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
1465d8bc7086Sdrh       }
146682c3d636Sdrh       p->pPrior = 0;
1467c926afbcSdrh       pOrderBy = p->pOrderBy;
1468c926afbcSdrh       p->pOrderBy = 0;
14697b58daeaSdrh       nLimit = p->nLimit;
14707b58daeaSdrh       p->nLimit = -1;
14717b58daeaSdrh       nOffset = p->nOffset;
14727b58daeaSdrh       p->nOffset = 0;
147384ac9d02Sdanielk1977       rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
147482c3d636Sdrh       p->pPrior = pPrior;
1475c926afbcSdrh       p->pOrderBy = pOrderBy;
14767b58daeaSdrh       p->nLimit = nLimit;
14777b58daeaSdrh       p->nOffset = nOffset;
147884ac9d02Sdanielk1977       if( rc ){
147984ac9d02Sdanielk1977         goto multi_select_end;
148084ac9d02Sdanielk1977       }
148184ac9d02Sdanielk1977 
1482d8bc7086Sdrh 
1483d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1484d8bc7086Sdrh       ** it is that we currently need.
1485d8bc7086Sdrh       */
1486c926afbcSdrh       if( eDest!=priorOp || unionTab!=iParm ){
14876b56344dSdrh         int iCont, iBreak, iStart;
148882c3d636Sdrh         assert( p->pEList );
148941202ccaSdrh         if( eDest==SRT_Callback ){
14906a3ea0e6Sdrh           generateColumnNames(pParse, 0, p->pEList);
149141202ccaSdrh         }
14924adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
14934adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
14944adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
14957b58daeaSdrh         computeLimitRegisters(pParse, p);
14964adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
149738640e15Sdrh         rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
1498d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
149984ac9d02Sdanielk1977                              iCont, iBreak, 0);
150084ac9d02Sdanielk1977         if( rc ){
150184ac9d02Sdanielk1977           rc = 1;
150284ac9d02Sdanielk1977           goto multi_select_end;
150384ac9d02Sdanielk1977         }
15044adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
15054adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
15064adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
15074adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
150882c3d636Sdrh       }
150982c3d636Sdrh       break;
151082c3d636Sdrh     }
151182c3d636Sdrh     case TK_INTERSECT: {
151282c3d636Sdrh       int tab1, tab2;
15136b56344dSdrh       int iCont, iBreak, iStart;
15147b58daeaSdrh       int nLimit, nOffset;
1515dc1bdc4fSdanielk1977       int addr;
151682c3d636Sdrh 
1517d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
15186206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
1519d8bc7086Sdrh       ** by allocating the tables we will need.
1520d8bc7086Sdrh       */
152182c3d636Sdrh       tab1 = pParse->nTab++;
152282c3d636Sdrh       tab2 = pParse->nTab++;
1523d8bc7086Sdrh       if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
152484ac9d02Sdanielk1977         rc = 1;
152584ac9d02Sdanielk1977         goto multi_select_end;
1526d8bc7086Sdrh       }
1527dc1bdc4fSdanielk1977 
1528dc1bdc4fSdanielk1977       addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab1, 0);
1529dc1bdc4fSdanielk1977       rc = multiSelectOpenTempAddr(p, addr, &pOpenTemp);
1530dc1bdc4fSdanielk1977       if( rc!=SQLITE_OK ){
1531dc1bdc4fSdanielk1977         goto multi_select_end;
1532dc1bdc4fSdanielk1977       }
1533dc1bdc4fSdanielk1977       sqlite3VdbeAddOp(v, OP_KeyAsData, tab1, 1);
153484ac9d02Sdanielk1977       assert( p->pEList );
1535d8bc7086Sdrh 
1536d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1537d8bc7086Sdrh       */
1538dc1bdc4fSdanielk1977       pPrior->ppOpenTemp = p->ppOpenTemp;
153984ac9d02Sdanielk1977       rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
154084ac9d02Sdanielk1977       if( rc ){
154184ac9d02Sdanielk1977         goto multi_select_end;
154284ac9d02Sdanielk1977       }
1543d8bc7086Sdrh 
1544d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1545d8bc7086Sdrh       */
1546dc1bdc4fSdanielk1977       addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 0);
1547dc1bdc4fSdanielk1977       rc = multiSelectOpenTempAddr(p, addr, &pOpenTemp);
1548dc1bdc4fSdanielk1977       if( rc!=SQLITE_OK ){
1549dc1bdc4fSdanielk1977         goto multi_select_end;
1550dc1bdc4fSdanielk1977       }
1551dc1bdc4fSdanielk1977       sqlite3VdbeAddOp(v, OP_KeyAsData, tab2, 1);
155282c3d636Sdrh       p->pPrior = 0;
15537b58daeaSdrh       nLimit = p->nLimit;
15547b58daeaSdrh       p->nLimit = -1;
15557b58daeaSdrh       nOffset = p->nOffset;
15567b58daeaSdrh       p->nOffset = 0;
155784ac9d02Sdanielk1977       rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
155882c3d636Sdrh       p->pPrior = pPrior;
15597b58daeaSdrh       p->nLimit = nLimit;
15607b58daeaSdrh       p->nOffset = nOffset;
156184ac9d02Sdanielk1977       if( rc ){
156284ac9d02Sdanielk1977         goto multi_select_end;
156384ac9d02Sdanielk1977       }
1564d8bc7086Sdrh 
1565d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1566d8bc7086Sdrh       ** tables.
1567d8bc7086Sdrh       */
156882c3d636Sdrh       assert( p->pEList );
156941202ccaSdrh       if( eDest==SRT_Callback ){
15706a3ea0e6Sdrh         generateColumnNames(pParse, 0, p->pEList);
157141202ccaSdrh       }
15724adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
15734adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
15744adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
15757b58daeaSdrh       computeLimitRegisters(pParse, p);
15764adee20fSdanielk1977       iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
15774adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
157838640e15Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
1579d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
158084ac9d02Sdanielk1977                              iCont, iBreak, 0);
158184ac9d02Sdanielk1977       if( rc ){
158284ac9d02Sdanielk1977         rc = 1;
158384ac9d02Sdanielk1977         goto multi_select_end;
158484ac9d02Sdanielk1977       }
15854adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
15864adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
15874adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
15884adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
15894adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
159082c3d636Sdrh       break;
159182c3d636Sdrh     }
159282c3d636Sdrh   }
159382c3d636Sdrh   assert( p->pEList && pPrior->pEList );
159482c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
15954adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
1596da93d238Sdrh       " do not have the same number of result columns", selectOpName(p->op));
159784ac9d02Sdanielk1977     rc = 1;
159884ac9d02Sdanielk1977     goto multi_select_end;
15992282792aSdrh   }
160084ac9d02Sdanielk1977 
1601dc1bdc4fSdanielk1977   if( p->pOrderBy || (pOpenTemp && pOpenTemp->nId>0) ){
1602dc1bdc4fSdanielk1977     int nCol = p->pEList->nExpr;
1603dc1bdc4fSdanielk1977     int i;
1604dc1bdc4fSdanielk1977     KeyInfo *pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*sizeof(CollSeq*));
1605dc1bdc4fSdanielk1977     if( !pKeyInfo ){
1606dc1bdc4fSdanielk1977       rc = SQLITE_NOMEM;
1607dc1bdc4fSdanielk1977       goto multi_select_end;
1608dc1bdc4fSdanielk1977     }
1609dc1bdc4fSdanielk1977 
1610dc1bdc4fSdanielk1977     pKeyInfo->enc = pParse->db->enc;
1611dc1bdc4fSdanielk1977     pKeyInfo->nField = nCol;
1612dc1bdc4fSdanielk1977 
1613dc1bdc4fSdanielk1977     for(i=0; i<nCol; i++){
1614dc1bdc4fSdanielk1977       pKeyInfo->aColl[i] = multiSelectCollSeq(pParse, p, i);
1615dc1bdc4fSdanielk1977       if( !pKeyInfo->aColl[i] ){
1616dc1bdc4fSdanielk1977         pKeyInfo->aColl[i] = pParse->db->pDfltColl;
1617dc1bdc4fSdanielk1977       }
1618dc1bdc4fSdanielk1977     }
1619dc1bdc4fSdanielk1977 
1620dc1bdc4fSdanielk1977     for(i=0; pOpenTemp && i<pOpenTemp->nId; i++){
1621dc1bdc4fSdanielk1977       int p3type = (i==0?P3_KEYINFO_HANDOFF:P3_KEYINFO);
1622dc1bdc4fSdanielk1977       int addr = pOpenTemp->a[i].idx;
1623dc1bdc4fSdanielk1977       sqlite3VdbeChangeP3(v, addr, (char *)pKeyInfo, p3type);
1624dc1bdc4fSdanielk1977     }
1625dc1bdc4fSdanielk1977 
1626dc1bdc4fSdanielk1977     if( p->pOrderBy ){
1627dc1bdc4fSdanielk1977       for(i=0; i<p->pOrderBy->nExpr; i++){
1628dc1bdc4fSdanielk1977         Expr *pExpr = p->pOrderBy->a[i].pExpr;
1629dc1bdc4fSdanielk1977         char *zName = p->pOrderBy->a[i].zName;
1630dc1bdc4fSdanielk1977         assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
1631dc1bdc4fSdanielk1977         assert( !pExpr->pColl );
1632dc1bdc4fSdanielk1977         if( zName ){
1633dc1bdc4fSdanielk1977           pExpr->pColl = sqlite3LocateCollSeq(pParse, zName, -1);
163484ac9d02Sdanielk1977         }else{
1635dc1bdc4fSdanielk1977           pExpr->pColl = pKeyInfo->aColl[pExpr->iColumn];
163684ac9d02Sdanielk1977         }
163784ac9d02Sdanielk1977       }
1638dc1bdc4fSdanielk1977       generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1639dc1bdc4fSdanielk1977     }
1640dc1bdc4fSdanielk1977 
1641dc1bdc4fSdanielk1977     if( !pOpenTemp ){
1642dc1bdc4fSdanielk1977       /* This happens for UNION ALL ... ORDER BY */
1643dc1bdc4fSdanielk1977       sqliteFree(pKeyInfo);
1644dc1bdc4fSdanielk1977     }
1645dc1bdc4fSdanielk1977   }
1646dc1bdc4fSdanielk1977 
1647dc1bdc4fSdanielk1977 multi_select_end:
1648dc1bdc4fSdanielk1977   if( pOpenTemp ){
1649dc1bdc4fSdanielk1977     sqlite3IdListDelete(pOpenTemp);
1650dc1bdc4fSdanielk1977   }
1651dc1bdc4fSdanielk1977   p->ppOpenTemp = 0;
165284ac9d02Sdanielk1977   return rc;
16532282792aSdrh }
16542282792aSdrh 
16552282792aSdrh /*
1656832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
16576a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
165884e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
16596a3ea0e6Sdrh ** unchanged.)
1660832508b7Sdrh **
1661832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
1662832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
1663832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
1664832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
1665832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
1666832508b7Sdrh ** of the subquery rather the result set of the subquery.
1667832508b7Sdrh */
16686a3ea0e6Sdrh static void substExprList(ExprList*,int,ExprList*);  /* Forward Decl */
16696a3ea0e6Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
1670832508b7Sdrh   if( pExpr==0 ) return;
167150350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
167250350a15Sdrh     if( pExpr->iColumn<0 ){
167350350a15Sdrh       pExpr->op = TK_NULL;
167450350a15Sdrh     }else{
1675832508b7Sdrh       Expr *pNew;
167684e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1677832508b7Sdrh       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1678832508b7Sdrh       pNew = pEList->a[pExpr->iColumn].pExpr;
1679832508b7Sdrh       assert( pNew!=0 );
1680832508b7Sdrh       pExpr->op = pNew->op;
1681d94a6698Sdrh       assert( pExpr->pLeft==0 );
16824adee20fSdanielk1977       pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
1683d94a6698Sdrh       assert( pExpr->pRight==0 );
16844adee20fSdanielk1977       pExpr->pRight = sqlite3ExprDup(pNew->pRight);
1685d94a6698Sdrh       assert( pExpr->pList==0 );
16864adee20fSdanielk1977       pExpr->pList = sqlite3ExprListDup(pNew->pList);
1687832508b7Sdrh       pExpr->iTable = pNew->iTable;
1688832508b7Sdrh       pExpr->iColumn = pNew->iColumn;
1689832508b7Sdrh       pExpr->iAgg = pNew->iAgg;
16904adee20fSdanielk1977       sqlite3TokenCopy(&pExpr->token, &pNew->token);
16914adee20fSdanielk1977       sqlite3TokenCopy(&pExpr->span, &pNew->span);
169250350a15Sdrh     }
1693832508b7Sdrh   }else{
16946a3ea0e6Sdrh     substExpr(pExpr->pLeft, iTable, pEList);
16956a3ea0e6Sdrh     substExpr(pExpr->pRight, iTable, pEList);
16966a3ea0e6Sdrh     substExprList(pExpr->pList, iTable, pEList);
1697832508b7Sdrh   }
1698832508b7Sdrh }
1699832508b7Sdrh static void
17006a3ea0e6Sdrh substExprList(ExprList *pList, int iTable, ExprList *pEList){
1701832508b7Sdrh   int i;
1702832508b7Sdrh   if( pList==0 ) return;
1703832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
17046a3ea0e6Sdrh     substExpr(pList->a[i].pExpr, iTable, pEList);
1705832508b7Sdrh   }
1706832508b7Sdrh }
1707832508b7Sdrh 
1708832508b7Sdrh /*
17091350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
17101350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
17111350b030Sdrh ** occurs.
17121350b030Sdrh **
17131350b030Sdrh ** To understand the concept of flattening, consider the following
17141350b030Sdrh ** query:
17151350b030Sdrh **
17161350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
17171350b030Sdrh **
17181350b030Sdrh ** The default way of implementing this query is to execute the
17191350b030Sdrh ** subquery first and store the results in a temporary table, then
17201350b030Sdrh ** run the outer query on that temporary table.  This requires two
17211350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
17221350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
1723832508b7Sdrh ** optimized.
17241350b030Sdrh **
1725832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
17261350b030Sdrh ** a single flat select, like this:
17271350b030Sdrh **
17281350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
17291350b030Sdrh **
17301350b030Sdrh ** The code generated for this simpification gives the same result
1731832508b7Sdrh ** but only has to scan the data once.  And because indices might
1732832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
1733832508b7Sdrh ** avoided.
17341350b030Sdrh **
1735832508b7Sdrh ** Flattening is only attempted if all of the following are true:
17361350b030Sdrh **
1737832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
17381350b030Sdrh **
1739832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
1740832508b7Sdrh **
17418af4d3acSdrh **   (3)  The subquery is not the right operand of a left outer join, or
17428af4d3acSdrh **        the subquery is not itself a join.  (Ticket #306)
1743832508b7Sdrh **
1744832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
1745832508b7Sdrh **
1746832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
1747832508b7Sdrh **        aggregates.
1748832508b7Sdrh **
1749832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
1750832508b7Sdrh **        DISTINCT.
1751832508b7Sdrh **
175208192d5fSdrh **   (7)  The subquery has a FROM clause.
175308192d5fSdrh **
1754df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
1755df199a25Sdrh **
1756df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
1757df199a25Sdrh **        aggregates.
1758df199a25Sdrh **
1759df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
1760df199a25Sdrh **        use LIMIT.
1761df199a25Sdrh **
1762174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
1763174b6195Sdrh **
17643fc673e6Sdrh **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
17653fc673e6Sdrh **        subquery has no WHERE clause.  (added by ticket #350)
17663fc673e6Sdrh **
1767832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
1768832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
1769832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1770832508b7Sdrh **
1771665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
1772832508b7Sdrh ** If flattening is attempted this routine returns 1.
1773832508b7Sdrh **
1774832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
1775832508b7Sdrh ** the subquery before this routine runs.
17761350b030Sdrh */
17778c74a8caSdrh static int flattenSubquery(
17788c74a8caSdrh   Parse *pParse,       /* The parsing context */
17798c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
17808c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
17818c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
17828c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
17838c74a8caSdrh ){
17840bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
1785ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
1786ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
17870bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
17886a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
1789832508b7Sdrh   int i;
1790832508b7Sdrh   Expr *pWhere;
17911350b030Sdrh 
1792832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
1793832508b7Sdrh   */
1794832508b7Sdrh   if( p==0 ) return 0;
1795832508b7Sdrh   pSrc = p->pSrc;
1796ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
1797832508b7Sdrh   pSub = pSrc->a[iFrom].pSelect;
1798832508b7Sdrh   assert( pSub!=0 );
1799832508b7Sdrh   if( isAgg && subqueryIsAgg ) return 0;
1800ad3cab52Sdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
1801832508b7Sdrh   pSubSrc = pSub->pSrc;
1802832508b7Sdrh   assert( pSubSrc );
1803c31c2eb8Sdrh   if( pSubSrc->nSrc==0 ) return 0;
1804df199a25Sdrh   if( (pSub->isDistinct || pSub->nLimit>=0) &&  (pSrc->nSrc>1 || isAgg) ){
1805df199a25Sdrh      return 0;
1806df199a25Sdrh   }
1807d11d382cSdrh   if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
1808174b6195Sdrh   if( p->pOrderBy && pSub->pOrderBy ) return 0;
1809832508b7Sdrh 
18108af4d3acSdrh   /* Restriction 3:  If the subquery is a join, make sure the subquery is
18118af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
18128af4d3acSdrh   ** is not allowed:
18138af4d3acSdrh   **
18148af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
18158af4d3acSdrh   **
18168af4d3acSdrh   ** If we flatten the above, we would get
18178af4d3acSdrh   **
18188af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
18198af4d3acSdrh   **
18208af4d3acSdrh   ** which is not at all the same thing.
18218af4d3acSdrh   */
18228af4d3acSdrh   if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
18238af4d3acSdrh     return 0;
18248af4d3acSdrh   }
18258af4d3acSdrh 
18263fc673e6Sdrh   /* Restriction 12:  If the subquery is the right operand of a left outer
18273fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
18283fc673e6Sdrh   ** An examples of why this is not allowed:
18293fc673e6Sdrh   **
18303fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
18313fc673e6Sdrh   **
18323fc673e6Sdrh   ** If we flatten the above, we would get
18333fc673e6Sdrh   **
18343fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
18353fc673e6Sdrh   **
18363fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
18373fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
18383fc673e6Sdrh   */
18393fc673e6Sdrh   if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
18403fc673e6Sdrh       && pSub->pWhere!=0 ){
18413fc673e6Sdrh     return 0;
18423fc673e6Sdrh   }
18433fc673e6Sdrh 
18440bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
184563eb5f29Sdrh   ** iFrom-th entry of the FROM clause in the outer query.
1846832508b7Sdrh   */
1847c31c2eb8Sdrh 
1848c31c2eb8Sdrh   /* Move all of the FROM elements of the subquery into the
1849c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
1850c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
1851c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
1852c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
1853c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
1854c31c2eb8Sdrh   ** elements we are now copying in.
1855c31c2eb8Sdrh   */
18566a3ea0e6Sdrh   iParent = pSrc->a[iFrom].iCursor;
1857c31c2eb8Sdrh   {
1858c31c2eb8Sdrh     int nSubSrc = pSubSrc->nSrc;
18598af4d3acSdrh     int jointype = pSrc->a[iFrom].jointype;
1860c31c2eb8Sdrh 
1861c31c2eb8Sdrh     if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
18624adee20fSdanielk1977       sqlite3DeleteTable(0, pSrc->a[iFrom].pTab);
1863c31c2eb8Sdrh     }
1864f26e09c8Sdrh     sqliteFree(pSrc->a[iFrom].zDatabase);
1865c31c2eb8Sdrh     sqliteFree(pSrc->a[iFrom].zName);
1866c31c2eb8Sdrh     sqliteFree(pSrc->a[iFrom].zAlias);
1867c31c2eb8Sdrh     if( nSubSrc>1 ){
1868c31c2eb8Sdrh       int extra = nSubSrc - 1;
1869c31c2eb8Sdrh       for(i=1; i<nSubSrc; i++){
18704adee20fSdanielk1977         pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
1871c31c2eb8Sdrh       }
1872c31c2eb8Sdrh       p->pSrc = pSrc;
1873c31c2eb8Sdrh       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1874c31c2eb8Sdrh         pSrc->a[i] = pSrc->a[i-extra];
1875c31c2eb8Sdrh       }
1876c31c2eb8Sdrh     }
1877c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
1878c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
1879c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1880c31c2eb8Sdrh     }
18818af4d3acSdrh     pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
1882c31c2eb8Sdrh   }
1883c31c2eb8Sdrh 
1884c31c2eb8Sdrh   /* Now begin substituting subquery result set expressions for
1885c31c2eb8Sdrh   ** references to the iParent in the outer query.
1886c31c2eb8Sdrh   **
1887c31c2eb8Sdrh   ** Example:
1888c31c2eb8Sdrh   **
1889c31c2eb8Sdrh   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1890c31c2eb8Sdrh   **   \                     \_____________ subquery __________/          /
1891c31c2eb8Sdrh   **    \_____________________ outer query ______________________________/
1892c31c2eb8Sdrh   **
1893c31c2eb8Sdrh   ** We look at every expression in the outer query and every place we see
1894c31c2eb8Sdrh   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1895c31c2eb8Sdrh   */
18966a3ea0e6Sdrh   substExprList(p->pEList, iParent, pSub->pEList);
1897832508b7Sdrh   pList = p->pEList;
1898832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
18996977fea8Sdrh     Expr *pExpr;
19006977fea8Sdrh     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
19016977fea8Sdrh       pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
1902832508b7Sdrh     }
1903832508b7Sdrh   }
19041b2e0329Sdrh   if( isAgg ){
19056a3ea0e6Sdrh     substExprList(p->pGroupBy, iParent, pSub->pEList);
19066a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
19071b2e0329Sdrh   }
1908174b6195Sdrh   if( pSub->pOrderBy ){
1909174b6195Sdrh     assert( p->pOrderBy==0 );
1910174b6195Sdrh     p->pOrderBy = pSub->pOrderBy;
1911174b6195Sdrh     pSub->pOrderBy = 0;
1912174b6195Sdrh   }else if( p->pOrderBy ){
19136a3ea0e6Sdrh     substExprList(p->pOrderBy, iParent, pSub->pEList);
1914174b6195Sdrh   }
1915832508b7Sdrh   if( pSub->pWhere ){
19164adee20fSdanielk1977     pWhere = sqlite3ExprDup(pSub->pWhere);
1917832508b7Sdrh   }else{
1918832508b7Sdrh     pWhere = 0;
1919832508b7Sdrh   }
1920832508b7Sdrh   if( subqueryIsAgg ){
1921832508b7Sdrh     assert( p->pHaving==0 );
19221b2e0329Sdrh     p->pHaving = p->pWhere;
19231b2e0329Sdrh     p->pWhere = pWhere;
19246a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
19251b2e0329Sdrh     if( pSub->pHaving ){
19264adee20fSdanielk1977       Expr *pHaving = sqlite3ExprDup(pSub->pHaving);
19271b2e0329Sdrh       if( p->pHaving ){
19284adee20fSdanielk1977         p->pHaving = sqlite3Expr(TK_AND, p->pHaving, pHaving, 0);
19291b2e0329Sdrh       }else{
19301b2e0329Sdrh         p->pHaving = pHaving;
19311b2e0329Sdrh       }
19321b2e0329Sdrh     }
19331b2e0329Sdrh     assert( p->pGroupBy==0 );
19344adee20fSdanielk1977     p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
1935832508b7Sdrh   }else if( p->pWhere==0 ){
1936832508b7Sdrh     p->pWhere = pWhere;
1937832508b7Sdrh   }else{
19386a3ea0e6Sdrh     substExpr(p->pWhere, iParent, pSub->pEList);
1939832508b7Sdrh     if( pWhere ){
19404adee20fSdanielk1977       p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pWhere, 0);
1941832508b7Sdrh     }
1942832508b7Sdrh   }
1943c31c2eb8Sdrh 
1944c31c2eb8Sdrh   /* The flattened query is distinct if either the inner or the
1945c31c2eb8Sdrh   ** outer query is distinct.
1946c31c2eb8Sdrh   */
1947832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
19488c74a8caSdrh 
1949c31c2eb8Sdrh   /* Transfer the limit expression from the subquery to the outer
1950c31c2eb8Sdrh   ** query.
1951c31c2eb8Sdrh   */
1952df199a25Sdrh   if( pSub->nLimit>=0 ){
1953df199a25Sdrh     if( p->nLimit<0 ){
1954df199a25Sdrh       p->nLimit = pSub->nLimit;
1955df199a25Sdrh     }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1956df199a25Sdrh       p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1957df199a25Sdrh     }
1958df199a25Sdrh   }
1959df199a25Sdrh   p->nOffset += pSub->nOffset;
19608c74a8caSdrh 
1961c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
1962c31c2eb8Sdrh   ** success.
1963c31c2eb8Sdrh   */
19644adee20fSdanielk1977   sqlite3SelectDelete(pSub);
1965832508b7Sdrh   return 1;
19661350b030Sdrh }
19671350b030Sdrh 
19681350b030Sdrh /*
19699562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it
19709562b551Sdrh ** is a simple min() or max() query.  If it is and this query can be
19719562b551Sdrh ** satisfied using a single seek to the beginning or end of an index,
1972e78e8284Sdrh ** then generate the code for this SELECT and return 1.  If this is not a
19739562b551Sdrh ** simple min() or max() query, then return 0;
19749562b551Sdrh **
19759562b551Sdrh ** A simply min() or max() query looks like this:
19769562b551Sdrh **
19779562b551Sdrh **    SELECT min(a) FROM table;
19789562b551Sdrh **    SELECT max(a) FROM table;
19799562b551Sdrh **
19809562b551Sdrh ** The query may have only a single table in its FROM argument.  There
19819562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
19829562b551Sdrh ** be the min() or max() of a single column of the table.  The column
19839562b551Sdrh ** in the min() or max() function must be indexed.
19849562b551Sdrh **
19854adee20fSdanielk1977 ** The parameters to this routine are the same as for sqlite3Select().
19869562b551Sdrh ** See the header comment on that routine for additional information.
19879562b551Sdrh */
19889562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
19899562b551Sdrh   Expr *pExpr;
19909562b551Sdrh   int iCol;
19919562b551Sdrh   Table *pTab;
19929562b551Sdrh   Index *pIdx;
19939562b551Sdrh   int base;
19949562b551Sdrh   Vdbe *v;
19959562b551Sdrh   int seekOp;
19969562b551Sdrh   int cont;
19976e17529eSdrh   ExprList *pEList, *pList, eList;
19989562b551Sdrh   struct ExprList_item eListItem;
19996e17529eSdrh   SrcList *pSrc;
20006e17529eSdrh 
20019562b551Sdrh 
20029562b551Sdrh   /* Check to see if this query is a simple min() or max() query.  Return
20039562b551Sdrh   ** zero if it is  not.
20049562b551Sdrh   */
20059562b551Sdrh   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
20066e17529eSdrh   pSrc = p->pSrc;
20076e17529eSdrh   if( pSrc->nSrc!=1 ) return 0;
20086e17529eSdrh   pEList = p->pEList;
20096e17529eSdrh   if( pEList->nExpr!=1 ) return 0;
20106e17529eSdrh   pExpr = pEList->a[0].pExpr;
20119562b551Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
20126e17529eSdrh   pList = pExpr->pList;
20136e17529eSdrh   if( pList==0 || pList->nExpr!=1 ) return 0;
20146977fea8Sdrh   if( pExpr->token.n!=3 ) return 0;
20154adee20fSdanielk1977   if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
20160bce8354Sdrh     seekOp = OP_Rewind;
20174adee20fSdanielk1977   }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
20180bce8354Sdrh     seekOp = OP_Last;
20190bce8354Sdrh   }else{
20200bce8354Sdrh     return 0;
20210bce8354Sdrh   }
20226e17529eSdrh   pExpr = pList->a[0].pExpr;
20239562b551Sdrh   if( pExpr->op!=TK_COLUMN ) return 0;
20249562b551Sdrh   iCol = pExpr->iColumn;
20256e17529eSdrh   pTab = pSrc->a[0].pTab;
20269562b551Sdrh 
20279562b551Sdrh   /* If we get to here, it means the query is of the correct form.
202817f71934Sdrh   ** Check to make sure we have an index and make pIdx point to the
202917f71934Sdrh   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
203017f71934Sdrh   ** key column, no index is necessary so set pIdx to NULL.  If no
203117f71934Sdrh   ** usable index is found, return 0.
20329562b551Sdrh   */
20339562b551Sdrh   if( iCol<0 ){
20349562b551Sdrh     pIdx = 0;
20359562b551Sdrh   }else{
2036dc1bdc4fSdanielk1977     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
20379562b551Sdrh     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
20389562b551Sdrh       assert( pIdx->nColumn>=1 );
2039dc1bdc4fSdanielk1977       if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
20409562b551Sdrh     }
20419562b551Sdrh     if( pIdx==0 ) return 0;
20429562b551Sdrh   }
20439562b551Sdrh 
2044e5f50722Sdrh   /* Identify column types if we will be using the callback.  This
20459562b551Sdrh   ** step is skipped if the output is going to a table or a memory cell.
2046e5f50722Sdrh   ** The column names have already been generated in the calling function.
20479562b551Sdrh   */
20484adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
20499562b551Sdrh   if( v==0 ) return 0;
20509562b551Sdrh 
20510c37e630Sdrh   /* If the output is destined for a temporary table, open that table.
20520c37e630Sdrh   */
20530c37e630Sdrh   if( eDest==SRT_TempTable ){
20544adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
2055b4964b72Sdanielk1977     sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
20560c37e630Sdrh   }
20570c37e630Sdrh 
205817f71934Sdrh   /* Generating code to find the min or the max.  Basically all we have
205917f71934Sdrh   ** to do is find the first or the last entry in the chosen index.  If
206017f71934Sdrh   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
206117f71934Sdrh   ** or last entry in the main table.
20629562b551Sdrh   */
20634adee20fSdanielk1977   sqlite3CodeVerifySchema(pParse, pTab->iDb);
20646e17529eSdrh   base = pSrc->a[0].iCursor;
20657b58daeaSdrh   computeLimitRegisters(pParse, p);
20666e17529eSdrh   if( pSrc->a[0].pSelect==0 ){
20674adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
2068d3d39e93Sdrh     sqlite3VdbeAddOp(v, OP_OpenRead, base, pTab->tnum);
2069b4964b72Sdanielk1977     sqlite3VdbeAddOp(v, OP_SetNumColumns, base, pTab->nCol);
20706e17529eSdrh   }
20714adee20fSdanielk1977   cont = sqlite3VdbeMakeLabel(v);
20729562b551Sdrh   if( pIdx==0 ){
20734adee20fSdanielk1977     sqlite3VdbeAddOp(v, seekOp, base, 0);
20749562b551Sdrh   }else{
20754adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
2076d3d39e93Sdrh     sqlite3VdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum,
2077d3d39e93Sdrh                    (char*)&pIdx->keyInfo, P3_KEYINFO);
20784adee20fSdanielk1977     sqlite3VdbeAddOp(v, seekOp, base+1, 0);
20794adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_IdxRecno, base+1, 0);
20804adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Close, base+1, 0);
20817cf6e4deSdrh     sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
20829562b551Sdrh   }
20835cf8e8c7Sdrh   eList.nExpr = 1;
20845cf8e8c7Sdrh   memset(&eListItem, 0, sizeof(eListItem));
20855cf8e8c7Sdrh   eList.a = &eListItem;
20865cf8e8c7Sdrh   eList.a[0].pExpr = pExpr;
208784ac9d02Sdanielk1977   selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
20884adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, cont);
20894adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Close, base, 0);
20906e17529eSdrh 
20919562b551Sdrh   return 1;
20929562b551Sdrh }
20939562b551Sdrh 
20949562b551Sdrh /*
20959bb61fe7Sdrh ** Generate code for the given SELECT statement.
20969bb61fe7Sdrh **
2097fef5208cSdrh ** The results are distributed in various ways depending on the
2098fef5208cSdrh ** value of eDest and iParm.
2099fef5208cSdrh **
2100fef5208cSdrh **     eDest Value       Result
2101fef5208cSdrh **     ------------    -------------------------------------------
2102fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
2103fef5208cSdrh **
2104fef5208cSdrh **     SRT_Mem         Store first result in memory cell iParm
2105fef5208cSdrh **
2106e014a838Sdanielk1977 **     SRT_Set         Store results as keys of table iParm.
2107fef5208cSdrh **
210882c3d636Sdrh **     SRT_Union       Store results as a key in a temporary table iParm
210982c3d636Sdrh **
21104b11c6d3Sjplyon **     SRT_Except      Remove results from the temporary table iParm.
2111c4a3c779Sdrh **
2112c4a3c779Sdrh **     SRT_Table       Store results in temporary table iParm
21139bb61fe7Sdrh **
2114e78e8284Sdrh ** The table above is incomplete.  Additional eDist value have be added
2115e78e8284Sdrh ** since this comment was written.  See the selectInnerLoop() function for
2116e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings.
2117e78e8284Sdrh **
21189bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
21199bb61fe7Sdrh ** encountered, then an appropriate error message is left in
21209bb61fe7Sdrh ** pParse->zErrMsg.
21219bb61fe7Sdrh **
21229bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
21239bb61fe7Sdrh ** calling function needs to do that.
21241b2e0329Sdrh **
21251b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
21261b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
21271b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
21281b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
21291b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
21301b2e0329Sdrh ** can be changed.
2131e78e8284Sdrh **
2132e78e8284Sdrh ** Example 1:   The meaning of the pParent parameter.
2133e78e8284Sdrh **
2134e78e8284Sdrh **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2135e78e8284Sdrh **    \                      \_______ subquery _______/        /
2136e78e8284Sdrh **     \                                                      /
2137e78e8284Sdrh **      \____________________ outer query ___________________/
2138e78e8284Sdrh **
2139e78e8284Sdrh ** This routine is called for the outer query first.   For that call,
2140e78e8284Sdrh ** pParent will be NULL.  During the processing of the outer query, this
2141e78e8284Sdrh ** routine is called recursively to handle the subquery.  For the recursive
2142e78e8284Sdrh ** call, pParent will point to the outer query.  Because the subquery is
2143e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will
2144e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.)
21459bb61fe7Sdrh */
21464adee20fSdanielk1977 int sqlite3Select(
2147cce7d176Sdrh   Parse *pParse,         /* The parser context */
21489bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
2149e78e8284Sdrh   int eDest,             /* How to dispose of the results */
2150e78e8284Sdrh   int iParm,             /* A parameter used by the eDest disposal method */
2151832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
2152832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
215384ac9d02Sdanielk1977   int *pParentAgg,       /* True if pParent uses aggregate functions */
215484ac9d02Sdanielk1977   char *aff              /* If eDest is SRT_Union, the affinity string */
2155cce7d176Sdrh ){
2156d8bc7086Sdrh   int i;
2157cce7d176Sdrh   WhereInfo *pWInfo;
2158cce7d176Sdrh   Vdbe *v;
2159cce7d176Sdrh   int isAgg = 0;         /* True for select lists like "count(*)" */
2160a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
2161ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
21629bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
21639bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
21642282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
21652282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
216619a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
216719a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
21681d83f052Sdrh   int rc = 1;            /* Value to return from this function */
21699bb61fe7Sdrh 
21706f8a503dSdanielk1977   if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
21714adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
2172daffd0e5Sdrh 
217382c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
217482c3d636Sdrh   */
217582c3d636Sdrh   if( p->pPrior ){
217684ac9d02Sdanielk1977     return multiSelect(pParse, p, eDest, iParm, aff);
217782c3d636Sdrh   }
217882c3d636Sdrh 
217982c3d636Sdrh   /* Make local copies of the parameters for this query.
218082c3d636Sdrh   */
21819bb61fe7Sdrh   pTabList = p->pSrc;
21829bb61fe7Sdrh   pWhere = p->pWhere;
21839bb61fe7Sdrh   pOrderBy = p->pOrderBy;
21842282792aSdrh   pGroupBy = p->pGroupBy;
21852282792aSdrh   pHaving = p->pHaving;
218619a775c2Sdrh   isDistinct = p->isDistinct;
21879bb61fe7Sdrh 
21886a3ea0e6Sdrh   /* Allocate VDBE cursors for each table in the FROM clause
218910e5e3cfSdrh   */
21904adee20fSdanielk1977   sqlite3SrcListAssignCursors(pParse, pTabList);
219110e5e3cfSdrh 
21929bb61fe7Sdrh   /*
21939bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
21949bb61fe7Sdrh   ** errors before this routine starts.
21959bb61fe7Sdrh   */
21961d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
2197cce7d176Sdrh 
2198e78e8284Sdrh   /* Expand any "*" terms in the result set.  (For example the "*" in
2199e78e8284Sdrh   ** "SELECT * FROM t1")  The fillInColumnlist() routine also does some
2200e78e8284Sdrh   ** other housekeeping - see the header comment for details.
2201cce7d176Sdrh   */
2202d8bc7086Sdrh   if( fillInColumnList(pParse, p) ){
22031d83f052Sdrh     goto select_end;
2204cce7d176Sdrh   }
2205ad2d8307Sdrh   pWhere = p->pWhere;
2206d8bc7086Sdrh   pEList = p->pEList;
22071d83f052Sdrh   if( pEList==0 ) goto select_end;
2208cce7d176Sdrh 
22092282792aSdrh   /* If writing to memory or generating a set
22102282792aSdrh   ** only a single column may be output.
221119a775c2Sdrh   */
2212fef5208cSdrh   if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
22134adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "only a single result allowed for "
2214da93d238Sdrh        "a SELECT that is part of an expression");
22151d83f052Sdrh     goto select_end;
221619a775c2Sdrh   }
221719a775c2Sdrh 
2218c926afbcSdrh   /* ORDER BY is ignored for some destinations.
22192282792aSdrh   */
2220c926afbcSdrh   switch( eDest ){
2221c926afbcSdrh     case SRT_Union:
2222c926afbcSdrh     case SRT_Except:
2223c926afbcSdrh     case SRT_Discard:
2224f93bbbeaSdanielk1977     case SRT_Set:
2225acd4c695Sdrh       pOrderBy = 0;
2226c926afbcSdrh       break;
2227c926afbcSdrh     default:
2228c926afbcSdrh       break;
22292282792aSdrh   }
22302282792aSdrh 
223110e5e3cfSdrh   /* At this point, we should have allocated all the cursors that we
2232832508b7Sdrh   ** need to handle subquerys and temporary tables.
223310e5e3cfSdrh   **
2234967e8b73Sdrh   ** Resolve the column names and do a semantics check on all the expressions.
22352282792aSdrh   */
22364794b980Sdrh   for(i=0; i<pEList->nExpr; i++){
22374adee20fSdanielk1977     if( sqlite3ExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
22381d83f052Sdrh       goto select_end;
2239cce7d176Sdrh     }
22404adee20fSdanielk1977     if( sqlite3ExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
22411d83f052Sdrh       goto select_end;
2242cce7d176Sdrh     }
2243cce7d176Sdrh   }
2244cce7d176Sdrh   if( pWhere ){
22454adee20fSdanielk1977     if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pWhere) ){
22461d83f052Sdrh       goto select_end;
2247cce7d176Sdrh     }
22484adee20fSdanielk1977     if( sqlite3ExprCheck(pParse, pWhere, 0, 0) ){
22491d83f052Sdrh       goto select_end;
2250cce7d176Sdrh     }
2251cce7d176Sdrh   }
2252c66c5a26Sdrh   if( pHaving ){
2253c66c5a26Sdrh     if( pGroupBy==0 ){
22544adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2255c66c5a26Sdrh       goto select_end;
2256c66c5a26Sdrh     }
22574adee20fSdanielk1977     if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pHaving) ){
2258c66c5a26Sdrh       goto select_end;
2259c66c5a26Sdrh     }
22604adee20fSdanielk1977     if( sqlite3ExprCheck(pParse, pHaving, 1, &isAgg) ){
2261c66c5a26Sdrh       goto select_end;
2262c66c5a26Sdrh     }
2263c66c5a26Sdrh   }
2264cce7d176Sdrh   if( pOrderBy ){
2265cce7d176Sdrh     for(i=0; i<pOrderBy->nExpr; i++){
2266e4de1febSdrh       int iCol;
226788eee38aSdrh       Expr *pE = pOrderBy->a[i].pExpr;
22684adee20fSdanielk1977       if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
22694adee20fSdanielk1977         sqlite3ExprDelete(pE);
22704adee20fSdanielk1977         pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
227188eee38aSdrh       }
22724adee20fSdanielk1977       if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
227388eee38aSdrh         goto select_end;
227488eee38aSdrh       }
22754adee20fSdanielk1977       if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
227688eee38aSdrh         goto select_end;
227788eee38aSdrh       }
22784adee20fSdanielk1977       if( sqlite3ExprIsConstant(pE) ){
22794adee20fSdanielk1977         if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
22804adee20fSdanielk1977           sqlite3ErrorMsg(pParse,
2281da93d238Sdrh              "ORDER BY terms must not be non-integer constants");
22821d83f052Sdrh           goto select_end;
2283e4de1febSdrh         }else if( iCol<=0 || iCol>pEList->nExpr ){
22844adee20fSdanielk1977           sqlite3ErrorMsg(pParse,
2285da93d238Sdrh              "ORDER BY column number %d out of range - should be "
2286e4de1febSdrh              "between 1 and %d", iCol, pEList->nExpr);
2287e4de1febSdrh           goto select_end;
2288e4de1febSdrh         }
2289cce7d176Sdrh       }
2290cce7d176Sdrh     }
2291cce7d176Sdrh   }
22922282792aSdrh   if( pGroupBy ){
22932282792aSdrh     for(i=0; i<pGroupBy->nExpr; i++){
229488eee38aSdrh       int iCol;
22952282792aSdrh       Expr *pE = pGroupBy->a[i].pExpr;
22964adee20fSdanielk1977       if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
22974adee20fSdanielk1977         sqlite3ExprDelete(pE);
22984adee20fSdanielk1977         pE = pGroupBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
22999208643dSdrh       }
23004adee20fSdanielk1977       if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
23011d83f052Sdrh         goto select_end;
23022282792aSdrh       }
23034adee20fSdanielk1977       if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
23041d83f052Sdrh         goto select_end;
23052282792aSdrh       }
23064adee20fSdanielk1977       if( sqlite3ExprIsConstant(pE) ){
23074adee20fSdanielk1977         if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
23084adee20fSdanielk1977           sqlite3ErrorMsg(pParse,
2309da93d238Sdrh             "GROUP BY terms must not be non-integer constants");
231088eee38aSdrh           goto select_end;
231188eee38aSdrh         }else if( iCol<=0 || iCol>pEList->nExpr ){
23124adee20fSdanielk1977           sqlite3ErrorMsg(pParse,
2313da93d238Sdrh              "GROUP BY column number %d out of range - should be "
231488eee38aSdrh              "between 1 and %d", iCol, pEList->nExpr);
231588eee38aSdrh           goto select_end;
231688eee38aSdrh         }
231788eee38aSdrh       }
23182282792aSdrh     }
23192282792aSdrh   }
2320cce7d176Sdrh 
2321d820cb1bSdrh   /* Begin generating code.
2322d820cb1bSdrh   */
23234adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
2324d820cb1bSdrh   if( v==0 ) goto select_end;
2325d820cb1bSdrh 
2326e78e8284Sdrh   /* Identify column names if we will be using them in a callback.  This
2327e78e8284Sdrh   ** step is skipped if the output is going to some other destination.
23280bb28106Sdrh   */
23290bb28106Sdrh   if( eDest==SRT_Callback ){
23306a3ea0e6Sdrh     generateColumnNames(pParse, pTabList, pEList);
23310bb28106Sdrh   }
23320bb28106Sdrh 
2333d3d39e93Sdrh #if 1  /* I do not think we need the following code any more.... */
233484ac9d02Sdanielk1977   /* If the destination is SRT_Union, then set the number of columns in
233584ac9d02Sdanielk1977   ** the records that will be inserted into the temporary table. The caller
233684ac9d02Sdanielk1977   ** couldn't do this, in case the select statement is of the form
233784ac9d02Sdanielk1977   ** "SELECT * FROM ....".
233884ac9d02Sdanielk1977   **
233984ac9d02Sdanielk1977   ** We need to do this before we start inserting records into the
234084ac9d02Sdanielk1977   ** temporary table (which has had OP_KeyAsData executed on it), because
234184ac9d02Sdanielk1977   ** it is required by the key comparison function. So do it now, even
234284ac9d02Sdanielk1977   ** though this means that OP_SetNumColumns may be executed on the same
234384ac9d02Sdanielk1977   ** cursor more than once.
234484ac9d02Sdanielk1977   */
234584ac9d02Sdanielk1977   if( eDest==SRT_Union ){
234684ac9d02Sdanielk1977     sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
234784ac9d02Sdanielk1977   }
2348d3d39e93Sdrh #endif
234984ac9d02Sdanielk1977 
2350d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
2351d820cb1bSdrh   */
2352ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
2353742f947bSdanielk1977     const char *zSavedAuthContext = 0;
2354c31c2eb8Sdrh     int needRestoreContext;
2355c31c2eb8Sdrh 
2356a76b5dfcSdrh     if( pTabList->a[i].pSelect==0 ) continue;
23575cf590c1Sdrh     if( pTabList->a[i].zName!=0 ){
23585cf590c1Sdrh       zSavedAuthContext = pParse->zAuthContext;
23595cf590c1Sdrh       pParse->zAuthContext = pTabList->a[i].zName;
2360c31c2eb8Sdrh       needRestoreContext = 1;
2361c31c2eb8Sdrh     }else{
2362c31c2eb8Sdrh       needRestoreContext = 0;
23635cf590c1Sdrh     }
23644adee20fSdanielk1977     sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
236584ac9d02Sdanielk1977                  pTabList->a[i].iCursor, p, i, &isAgg, 0);
2366c31c2eb8Sdrh     if( needRestoreContext ){
23675cf590c1Sdrh       pParse->zAuthContext = zSavedAuthContext;
23685cf590c1Sdrh     }
2369832508b7Sdrh     pTabList = p->pSrc;
2370832508b7Sdrh     pWhere = p->pWhere;
2371c31c2eb8Sdrh     if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
2372832508b7Sdrh       pOrderBy = p->pOrderBy;
2373acd4c695Sdrh     }
2374832508b7Sdrh     pGroupBy = p->pGroupBy;
2375832508b7Sdrh     pHaving = p->pHaving;
2376832508b7Sdrh     isDistinct = p->isDistinct;
23771b2e0329Sdrh   }
23781b2e0329Sdrh 
23796e17529eSdrh   /* Check for the special case of a min() or max() function by itself
23806e17529eSdrh   ** in the result set.
23816e17529eSdrh   */
23826e17529eSdrh   if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
23836e17529eSdrh     rc = 0;
23846e17529eSdrh     goto select_end;
23856e17529eSdrh   }
23866e17529eSdrh 
23871b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
23881b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
23891b2e0329Sdrh   */
23901b2e0329Sdrh   if( pParent && pParentAgg &&
23918c74a8caSdrh       flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
23921b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
23931b2e0329Sdrh     return rc;
23941b2e0329Sdrh   }
2395832508b7Sdrh 
23967cedc8d4Sdanielk1977   /* If there is an ORDER BY clause, resolve any collation sequences
23977cedc8d4Sdanielk1977   ** names that have been explicitly specified.
23987cedc8d4Sdanielk1977   */
23997cedc8d4Sdanielk1977   if( pOrderBy ){
24007cedc8d4Sdanielk1977     for(i=0; i<pOrderBy->nExpr; i++){
24017cedc8d4Sdanielk1977       if( pOrderBy->a[i].zName ){
24027cedc8d4Sdanielk1977         pOrderBy->a[i].pExpr->pColl =
24037cedc8d4Sdanielk1977             sqlite3LocateCollSeq(pParse, pOrderBy->a[i].zName, -1);
24047cedc8d4Sdanielk1977       }
24057cedc8d4Sdanielk1977     }
24067cedc8d4Sdanielk1977     if( pParse->nErr ){
24077cedc8d4Sdanielk1977       goto select_end;
24087cedc8d4Sdanielk1977     }
24097cedc8d4Sdanielk1977   }
24107cedc8d4Sdanielk1977 
24117b58daeaSdrh   /* Set the limiter.
24127b58daeaSdrh   */
24137b58daeaSdrh   computeLimitRegisters(pParse, p);
24147b58daeaSdrh 
24152d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
24162d0794e3Sdrh   */
24172d0794e3Sdrh   if( eDest==SRT_TempTable ){
24184adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
2419b4964b72Sdanielk1977     sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
24202d0794e3Sdrh   }
24212d0794e3Sdrh 
24222282792aSdrh   /* Do an analysis of aggregate expressions.
2423efb7251dSdrh   */
2424d820cb1bSdrh   sqliteAggregateInfoReset(pParse);
2425bb999ef6Sdrh   if( isAgg || pGroupBy ){
24260bce8354Sdrh     assert( pParse->nAgg==0 );
2427bb999ef6Sdrh     isAgg = 1;
24282282792aSdrh     for(i=0; i<pEList->nExpr; i++){
24294adee20fSdanielk1977       if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
24301d83f052Sdrh         goto select_end;
24312282792aSdrh       }
24322282792aSdrh     }
24332282792aSdrh     if( pGroupBy ){
24342282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
24354adee20fSdanielk1977         if( sqlite3ExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
24361d83f052Sdrh           goto select_end;
24372282792aSdrh         }
24382282792aSdrh       }
24392282792aSdrh     }
24404adee20fSdanielk1977     if( pHaving && sqlite3ExprAnalyzeAggregates(pParse, pHaving) ){
24411d83f052Sdrh       goto select_end;
24422282792aSdrh     }
2443191b690eSdrh     if( pOrderBy ){
2444191b690eSdrh       for(i=0; i<pOrderBy->nExpr; i++){
24454adee20fSdanielk1977         if( sqlite3ExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
24461d83f052Sdrh           goto select_end;
2447191b690eSdrh         }
2448191b690eSdrh       }
2449191b690eSdrh     }
2450efb7251dSdrh   }
2451efb7251dSdrh 
24522282792aSdrh   /* Reset the aggregator
2453cce7d176Sdrh   */
2454cce7d176Sdrh   if( isAgg ){
2455*e159fdf2Sdanielk1977     int addr = sqlite3VdbeAddOp(v, OP_AggReset, (pGroupBy?0:1), pParse->nAgg);
2456e5095355Sdrh     for(i=0; i<pParse->nAgg; i++){
24570bce8354Sdrh       FuncDef *pFunc;
24580bce8354Sdrh       if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
2459f9b596ebSdrh         sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_FUNCDEF);
2460e5095355Sdrh       }
2461e5095355Sdrh     }
2462*e159fdf2Sdanielk1977     if( pGroupBy ){
2463ce2663ccSdanielk1977       int sz = sizeof(KeyInfo) + pGroupBy->nExpr*sizeof(CollSeq*);
2464ce2663ccSdanielk1977       KeyInfo *pKey = (KeyInfo *)sqliteMalloc(sz);
2465ce2663ccSdanielk1977       if( 0==pKey ){
2466ce2663ccSdanielk1977         goto select_end;
2467ce2663ccSdanielk1977       }
2468ce2663ccSdanielk1977       pKey->enc = pParse->db->enc;
2469ce2663ccSdanielk1977       pKey->nField = pGroupBy->nExpr;
2470ce2663ccSdanielk1977       for(i=0; i<pGroupBy->nExpr; i++){
2471ce2663ccSdanielk1977         pKey->aColl[i] = sqlite3ExprCollSeq(pParse, pGroupBy->a[i].pExpr);
2472ce2663ccSdanielk1977         if( !pKey->aColl[i] ){
2473ce2663ccSdanielk1977           pKey->aColl[i] = pParse->db->pDfltColl;
2474ce2663ccSdanielk1977         }
2475ce2663ccSdanielk1977       }
2476ce2663ccSdanielk1977       sqlite3VdbeChangeP3(v, addr, (char *)pKey, P3_KEYINFO_HANDOFF);
24771bee3d7bSdrh     }
2478cce7d176Sdrh   }
2479cce7d176Sdrh 
248019a775c2Sdrh   /* Initialize the memory cell to NULL
248119a775c2Sdrh   */
2482fef5208cSdrh   if( eDest==SRT_Mem ){
24830f69c1e3Sdanielk1977     sqlite3VdbeAddOp(v, OP_String8, 0, 0);
24844adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
248519a775c2Sdrh   }
248619a775c2Sdrh 
2487832508b7Sdrh   /* Open a temporary table to use for the distinct set.
2488cce7d176Sdrh   */
248919a775c2Sdrh   if( isDistinct ){
2490832508b7Sdrh     distinct = pParse->nTab++;
2491d3d39e93Sdrh     openTempIndex(pParse, p, distinct, 0);
2492832508b7Sdrh   }else{
2493832508b7Sdrh     distinct = -1;
2494efb7251dSdrh   }
2495832508b7Sdrh 
2496832508b7Sdrh   /* Begin the database scan
2497832508b7Sdrh   */
24984adee20fSdanielk1977   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
249968d2e591Sdrh                             pGroupBy ? 0 : &pOrderBy);
25001d83f052Sdrh   if( pWInfo==0 ) goto select_end;
2501cce7d176Sdrh 
25022282792aSdrh   /* Use the standard inner loop if we are not dealing with
25032282792aSdrh   ** aggregates
2504cce7d176Sdrh   */
2505da9d6c45Sdrh   if( !isAgg ){
2506df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
250784ac9d02Sdanielk1977                     iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
25081d83f052Sdrh        goto select_end;
2509cce7d176Sdrh     }
2510da9d6c45Sdrh   }
2511cce7d176Sdrh 
2512e3184744Sdrh   /* If we are dealing with aggregates, then do the special aggregate
25132282792aSdrh   ** processing.
2514efb7251dSdrh   */
25152282792aSdrh   else{
2516268380caSdrh     AggExpr *pAgg;
25172282792aSdrh     if( pGroupBy ){
25181bee3d7bSdrh       int lbl1;
25192282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
25204adee20fSdanielk1977         sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
2521efb7251dSdrh       }
2522ededfd5eSdanielk1977       /* No affinity string is attached to the following OP_MakeRecord
2523d3d39e93Sdrh       ** because we do not need to do any coercion of datatypes. */
2524ededfd5eSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, pGroupBy->nExpr, 0);
25254adee20fSdanielk1977       lbl1 = sqlite3VdbeMakeLabel(v);
25264adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
2527268380caSdrh       for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2528268380caSdrh         if( pAgg->isAgg ) continue;
25294adee20fSdanielk1977         sqlite3ExprCode(pParse, pAgg->pExpr);
25304adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
25312282792aSdrh       }
25324adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, lbl1);
25332282792aSdrh     }
2534268380caSdrh     for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
25352282792aSdrh       Expr *pE;
2536268380caSdrh       int nExpr;
2537268380caSdrh       FuncDef *pDef;
2538268380caSdrh       if( !pAgg->isAgg ) continue;
2539268380caSdrh       assert( pAgg->pFunc!=0 );
2540268380caSdrh       assert( pAgg->pFunc->xStep!=0 );
2541268380caSdrh       pDef = pAgg->pFunc;
2542268380caSdrh       pE = pAgg->pExpr;
2543268380caSdrh       assert( pE!=0 );
25442282792aSdrh       assert( pE->op==TK_AGG_FUNCTION );
2545f9b596ebSdrh       nExpr = sqlite3ExprCodeExprList(pParse, pE->pList);
25464adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, i, 0);
2547dc1bdc4fSdanielk1977       if( pDef->needCollSeq ){
2548dc1bdc4fSdanielk1977         CollSeq *pColl = 0;
2549dc1bdc4fSdanielk1977         int j;
2550dc1bdc4fSdanielk1977         for(j=0; !pColl && j<nExpr; j++){
2551dc1bdc4fSdanielk1977           pColl = sqlite3ExprCollSeq(pParse, pE->pList->a[j].pExpr);
2552dc1bdc4fSdanielk1977         }
2553dc1bdc4fSdanielk1977         if( !pColl ) pColl = pParse->db->pDfltColl;
2554dc1bdc4fSdanielk1977         sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2555dc1bdc4fSdanielk1977       }
25564adee20fSdanielk1977       sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
25572282792aSdrh     }
25582282792aSdrh   }
25592282792aSdrh 
2560cce7d176Sdrh   /* End the database scan loop.
2561cce7d176Sdrh   */
25624adee20fSdanielk1977   sqlite3WhereEnd(pWInfo);
2563cce7d176Sdrh 
25642282792aSdrh   /* If we are processing aggregates, we need to set up a second loop
25652282792aSdrh   ** over all of the aggregate values and process them.
25662282792aSdrh   */
25672282792aSdrh   if( isAgg ){
25684adee20fSdanielk1977     int endagg = sqlite3VdbeMakeLabel(v);
25692282792aSdrh     int startagg;
25704adee20fSdanielk1977     startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
25712282792aSdrh     pParse->useAgg = 1;
25722282792aSdrh     if( pHaving ){
25734adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
25742282792aSdrh     }
2575df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
257684ac9d02Sdanielk1977                     iParm, startagg, endagg, aff) ){
25771d83f052Sdrh       goto select_end;
25782282792aSdrh     }
25794adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
25804adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, endagg);
25814adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
25822282792aSdrh     pParse->useAgg = 0;
25832282792aSdrh   }
25842282792aSdrh 
2585cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
2586cce7d176Sdrh   ** and send them to the callback one by one.
2587cce7d176Sdrh   */
2588cce7d176Sdrh   if( pOrderBy ){
2589ffbc3088Sdrh     generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
2590cce7d176Sdrh   }
25916a535340Sdrh 
2592f620b4e2Sdrh   /* If this was a subquery, we have now converted the subquery into a
2593f620b4e2Sdrh   ** temporary table.  So delete the subquery structure from the parent
2594f620b4e2Sdrh   ** to prevent this subquery from being evaluated again and to force the
2595f620b4e2Sdrh   ** the use of the temporary table.
2596f620b4e2Sdrh   */
2597f620b4e2Sdrh   if( pParent ){
2598f620b4e2Sdrh     assert( pParent->pSrc->nSrc>parentTab );
2599f620b4e2Sdrh     assert( pParent->pSrc->a[parentTab].pSelect==p );
26004adee20fSdanielk1977     sqlite3SelectDelete(p);
2601f620b4e2Sdrh     pParent->pSrc->a[parentTab].pSelect = 0;
2602f620b4e2Sdrh   }
2603f620b4e2Sdrh 
26041d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
26051d83f052Sdrh   ** to indicate no errors.
26061d83f052Sdrh   */
26071d83f052Sdrh   rc = 0;
26081d83f052Sdrh 
26091d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
26101d83f052Sdrh   ** successful coding of the SELECT.
26111d83f052Sdrh   */
26121d83f052Sdrh select_end:
26131d83f052Sdrh   sqliteAggregateInfoReset(pParse);
26141d83f052Sdrh   return rc;
2615cce7d176Sdrh }
2616